PHP hook, building hooks in your application
Introduction
One of the real challenges in building any type of framework, core or application is making it possible for the developers to hook into the business logic at specific points. Since PHP is not event based, nor it works with interrupts you have to come up an alternative.
The test case
Lets assume we are the main developers of a webshop framework. Programmers can use our framework to build complete webshops. Programmers can manage the orders that are placed on the webshop with the order class. The order class is part of our framework and we don’t want it to be extended by any programmer. However we don’t want to limit to programmers in their possibilities to hook into the orders process.
For example programmers should be able to send an email to the webshopowner if an order changes from one specific delivery status to another. This functionality is not part of the default behavior in our framework and is custom for the progammers webshop implementation.
Like said before, PHP doesn’t provide interrupts or real events so we need to come up with another way to implement hooks into our application. Lets take a look at the observer pattern.
Implementing the Observer pattern
The observer pattern is a design-pattern that describes a way for objects to be notified to specific state-changes in objects of the application.
For the first implementation we can use SPL. The SPL provides in two simple objects:
SPLSubject
- attach (new observer to attach)
- detach (existing observer to detach)
- notify (notify all observers)
SPLObserver
- update (Called from the subject (i.e. when it’s value has changed).
iOrderRef = $iOrderRef;
// Get order information from the database or an other resources
$this->iStatus = Order::STATUS_SHIPPED;
}
/**
* Attach an observer
*
* @param SplObserver $oObserver
* @return void
*/
public function attach(SplObserver $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (isset($this->aObservers[$sHash])) {
throw new Exception('Observer is already attached');
}
$this->aObservers[$sHash] = $oObserver;
}
/**
* Detach observer
*
* @param SplObserver $oObserver
* @return void
*/
public function detach(SplObserver $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (!isset($this->aObservers[$sHash])) {
throw new Exception('Observer not attached');
}
unset($this->aObservers[$sHash]);
}
/**
* Notify the attached observers
*
* @param string $sEvent, name of the event
* @param mixed $mData, optional data that is not directly available for the observers
* @return void
*/
public function notify()
{
foreach ($this->aObservers as $oObserver) {
try {
$oObserver->update($this);
} catch(Exception $e) {
}
}
}
/**
* Add an order
*
* @param array $aOrder
* @return void
*/
public function delete()
{
$this->notify();
}
/**
* Return the order reference number
*
* @return int
*/
public function getRef()
{
return $this->iOrderRef;
}
/**
* Return the current order status
*
* @return int
*/
public function getStatus()
{
return $this->iStatus;
}
/**
* Update the order status
*/
public function updateStatus($iStatus)
{
$this->notify();
// ...
$this->iStatus = $iStatus;
// ...
$this->notify();
}
}
/**
* Order status handler, observer that sends an email to secretary
* if the status of an order changes from shipped to delivered, so the
* secratary can make a phone call to our customer to ask for his opinion about the service
*
* @package Shop
*/
class OrderStatusHandler implements SplObserver
{
/**
* Previous orderstatus
* @var int
*/
protected $iPreviousOrderStatus;
/**
* Current orderstatus
* @var int
*/
protected $iCurrentOrderStatus;
/**
* Update, called by the observable object order
*
* @param Observable_Interface $oSubject
* @param string $sEvent
* @param mixed $mData
* @return void
*/
public function update(SplSubject $oSubject)
{
if(!$oSubject instanceof Order) {
return;
}
if(is_null($this->iPreviousOrderStatus)) {
$this->iPreviousOrderStatus = $oSubject->getStatus();
} else {
$this->iCurrentOrderStatus = $oSubject->getStatus();
if($this->iPreviousOrderStatus === Order::STATUS_SHIPPED && $this->iCurrentOrderStatus === Order::STATUS_DELIVERED) {
$sSubject = sprintf('Order number %d is shipped', $oSubject->getRef());
//mail('secratary@example.com', 'Order number %d is shipped', 'Text');
echo 'Mail sended to the secratary to help her remember to call our customer for a survey.';
}
}
}
}
$oOrder = new Order(26012011);
$oOrder->attach(new OrderStatusHandler());
$oOrder->updateStatus(Order::STATUS_DELIVERED);
$oOrder->delete();
?>
There are several problems with the implementation above. To most important disadvantage is that we have only one update method in our observer. In this update method we don’t know when and why we are getting notified, just that something happened. We should keep track of everything that happens in the subject. (Or use debug_backtrace… just joking, don’t even think about using it that way ever!).
Taking it a step further, events
Lets take a look at the next example, we will extend the Observer implementation with some an additional parameter for the eventname that occured.
Finishing up, optional data
iOrderRef = $iOrderRef;
// Get order information from the database or something else...
$this->iStatus = Order::STATUS_SHIPPED;
}
/**
* Attach an observer
*
* @param Observer_Interface $oObserver
* @return void
*/
public function attachObserver(Observer_Interface $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (isset($this->aObservers[$sHash])) {
throw new Exception('Observer is already attached');
}
$this->aObservers[$sHash] = $oObserver;
}
/**
* Detach observer
*
* @param Observer_Interface $oObserver
* @return void
*/
public function detachObserver(Observer_Interface $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (!isset($this->aObservers[$sHash])) {
throw new Exception('Observer not attached');
}
unset($this->aObservers[$sHash]);
}
/**
* Notify the attached observers
*
* @param string $sEvent, name of the event
* @param mixed $mData, optional data that is not directly available for the observers
* @return void
*/
public function notifyObserver($sEvent, $mData=null)
{
foreach ($this->aObservers as $oObserver) {
try {
$oObserver->update($this, $sEvent, $mData);
} catch(Exception $e) {
}
}
}
/**
* Add an order
*
* @param array $aOrder
* @return void
*/
public function add($aOrder = array())
{
$this->notifyObserver('onAdd');
}
/**
* Return the order reference number
*
* @return int
*/
public function getRef()
{
return $this->iOrderRef;
}
/**
* Return the current order status
*
* @return int
*/
public function getStatus()
{
return $this->iStatus;
}
/**
* Update the order status
*/
public function updateStatus($iStatus)
{
$this->notifyObserver('onBeforeUpdateStatus');
// ...
$this->iStatus = $iStatus;
// ...
$this->notifyObserver('onAfterUpdateStatus');
}
}
/**
* Order status handler, observer that sends an email to secretary
* if the status of an order changes from shipped to delivered, so the
* secratary can make a phone call to our customer to ask for his opinion about the service
*
* @package Shop
*/
class OrderStatusHandler implements Observer_Interface
{
protected $iPreviousOrderStatus;
protected $iCurrentOrderStatus;
/**
* Update, called by the observable object order
*
* @param Observable_Interface $oObservable
* @param string $sEvent
* @param mixed $mData
* @return void
*/
public function update(Observable_Interface $oObservable, $sEvent, $mData=null)
{
if(!$oObservable instanceof Order) {
return;
}
switch($sEvent) {
case 'onBeforeUpdateStatus':
$this->iPreviousOrderStatus = $oObservable->getStatus();
return;
case 'onAfterUpdateStatus':
$this->iCurrentOrderStatus = $oObservable->getStatus();
if($this->iPreviousOrderStatus === Order::STATUS_SHIPPED && $this->iCurrentOrderStatus === Order::STATUS_DELIVERED) {
$sSubject = sprintf('Order number %d is shipped', $oObservable->getRef());
//mail('secratary@example.com', 'Order number %d is shipped', 'Text');
echo 'Mail sended to the secratary to help her remember to call our customer for a survey.';
}
}
}
}
$oOrder = new Order(26012011);
$oOrder->attachObserver(new OrderStatusHandler());
$oOrder->updateStatus(Order::STATUS_DELIVERED);
$oOrder->add();
?>
Now we are able to take action on different events that occur.
Disadvantages
Although this implementation works quite well there are some drawbacks. One of those drawbacks is that we need to dispatch an event in our framework, if we don’t programmers can’t hook into our application. Triggering events everywhere give us a small performance penalty however I do think this way of working gives the programmers a nice way to hook into your application on those spots that you want them to hook in.
Just for the record
Notice that this code is just an example and can still use some improvements, for example: each observer is initialized even it will maybe never be notified, therefore I suggest to make use of lazy in some cases for loading the objects. There are other systems to hook into an application, more to follow!
купить vip диплом об окончании техникума [url=http://www.frei-diplom12.ru]купить vip диплом об окончании техникума[/url] .
Diplomi_ajPt
21 Oct 25 at 8:09 am
Thanks for another informative blog. The place else may just I am getting that type of information written in such a perfect manner?
I have a project that I am simply now working on, and I’ve been at the glance out for such
information.
buôn bán nội tạng
21 Oct 25 at 8:10 am
кракен онион
kraken client
JamesDaync
21 Oct 25 at 8:10 am
pin up ro‘yxatdan qanday o‘tish [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]
pin_up_uz_aiSt
21 Oct 25 at 8:12 am
купить диплом о среднем образовании с занесением в реестр [url=https://frei-diplom6.ru]купить диплом о среднем образовании с занесением в реестр[/url] .
Diplomi_bmOl
21 Oct 25 at 8:12 am
купить диплом внесенный в реестр [url=http://www.frei-diplom5.ru]купить диплом внесенный в реестр[/url] .
Diplomi_jgPa
21 Oct 25 at 8:13 am
купить диплом в белогорске [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_nxSa
21 Oct 25 at 8:13 am
купить диплом в ишиме [url=https://rudik-diplom11.ru/]https://rudik-diplom11.ru/[/url] .
Diplomi_irMi
21 Oct 25 at 8:14 am
купить диплом о профессиональном образовании [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_raea
21 Oct 25 at 8:15 am
купить техникум диплом [url=www.frei-diplom12.ru]купить техникум диплом[/url] .
Diplomi_wqPt
21 Oct 25 at 8:18 am
каталог seo агентств [url=https://reiting-seo-kompanii.ru/]https://reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_cxsn
21 Oct 25 at 8:19 am
The $MTAUR coin ICO partnerships key. Token conversions seamless. Hype deserved.
minotaurus coin
WilliamPargy
21 Oct 25 at 8:20 am
https://pushnews.com.ua/tsikavi-fakty-pro-sobor-sviatoho-petra-istoriia-arkhitektura-ta-znachennia/
Jamesstalm
21 Oct 25 at 8:20 am
пин ап надёжный сайт [url=https://pinup5008.ru]https://pinup5008.ru[/url]
pin_up_uz_guSt
21 Oct 25 at 8:21 am
кракен маркетплейс
kraken вход
JamesDaync
21 Oct 25 at 8:21 am
You made some really good points there. I looked on the internet for more info about the issue and found most people will go
along with your views on this web site.
Skyline Nexus Pro
21 Oct 25 at 8:22 am
ranking seo [url=https://www.reiting-seo-kompaniy.ru]ranking seo[/url] .
reiting seo kompanii_wcon
21 Oct 25 at 8:22 am
купить диплом в орске [url=http://rudik-diplom1.ru/]купить диплом в орске[/url] .
Diplomi_gaer
21 Oct 25 at 8:23 am
pin up uz [url=http://pinup5007.ru/]http://pinup5007.ru/[/url]
pin_up_uz_cqsr
21 Oct 25 at 8:23 am
где купить диплом колледжа в астрахани [url=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_zgPt
21 Oct 25 at 8:23 am
пин ап бонус [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_txsr
21 Oct 25 at 8:25 am
купить диплом института образования [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_npea
21 Oct 25 at 8:25 am
купить диплом в прокопьевске [url=https://rudik-diplom8.ru]купить диплом в прокопьевске[/url] .
Diplomi_csMt
21 Oct 25 at 8:25 am
pin up aviator yuklab olish [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_tnsr
21 Oct 25 at 8:26 am
купить диплом в волгодонске [url=https://rudik-diplom4.ru/]купить диплом в волгодонске[/url] .
Diplomi_bjOr
21 Oct 25 at 8:26 am
продвижение сайта в топ москва [url=http://reiting-seo-agentstv-moskvy.ru/]http://reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_naMl
21 Oct 25 at 8:28 am
Как купить СК в Николаевске?Посмотрите сайт https://GrillsMarket.ru
– нормальные цены, есть оперативная доставка. Может, кто брал у них? Как с чистотой товар?
Stevenref
21 Oct 25 at 8:29 am
Получи 32500 руб. по актуальному промо коду для 1хБет бесплатно. Новые купоны на регистрацию каждый час на сайте. В ваших силах получить до шести с половиной тысяч рублей при регистрации. Читайте ниже как использовать наши промо-коды. промокоды на 1хбет на фриспины. Букмекерская контора позволяет использовать промокод 1хБет на ставку-бонус. Забирайте новые купоны ежедневно. Внимание! Наши промо-купоны подходят для всех акций букмекера. Этот купон также универсальный – используйте его везде, не только при регистрации на сайте БК 1хБет и всех известных его зеркал. Введите его в форме для регистрации и получите увеличенный бонус на первый депозит до 32500 рублей. Кроме того, букмекер постоянно дарит активным клиентам выгодные подарки. Чтобы получить промокод в 1xBet бесплатно: Подпишитесь на рассылку новостей по смс или электронной почте. Регулярно заходите в раздел «Бонусы и подарки» в Личном кабинете.
Stanleyvonna
21 Oct 25 at 8:29 am
топ агентств россии [url=www.luchshie-digital-agencstva.ru]www.luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_aqoi
21 Oct 25 at 8:29 am
Hey There. I found your blog using msn. This is an extremely
well written article. I’ll be sure to bookmark it and return to read more of your useful information. Thanks for
the post. I will definitely comeback.
종류별대출상품
21 Oct 25 at 8:30 am
купить красный мухомор Магазин muhomorus в интернете предлагает возможность купить мухоморы с доставкой в любую точку России. Предлагаем выгодные цены на экологически чистую продукцию, предназначенную для снятия тревожных состояний, стресса, депрессии, хронической усталости, а также для облегчения признаков различных заболеваний. Подчеркиваем, что сушеные мухоморы не являются лекарством, а относятся к парафармацевтике – альтернативному средству, применяемому каждым человеком по собственному желанию в качестве дополнительной терапии. Законность сбора, сушки, продажи и покупки гарантируется. У нас вы можете законно приобрести микродозы.
GradyBus
21 Oct 25 at 8:30 am
https://pilloleverdi.com/# cialis
LarryArrix
21 Oct 25 at 8:31 am
В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
Перейти к полной версии – https://apolin.org/bertemu-jokowi-pm-india-janji-beri-treatment-yang-fair-untuk-sawit-indonesia
HenryACCOR
21 Oct 25 at 8:31 am
pin up akkaunt yaratish [url=https://pinup5008.ru]https://pinup5008.ru[/url]
pin_up_uz_tjSt
21 Oct 25 at 8:32 am
купить диплом московского торгово экономического техникума [url=www.frei-diplom10.ru]купить диплом московского торгово экономического техникума[/url] .
Diplomi_lpEa
21 Oct 25 at 8:32 am
seo продвижение рейтинг [url=http://seo-prodvizhenie-reiting.ru]seo продвижение рейтинг[/url] .
seo prodvijenie reiting_okEa
21 Oct 25 at 8:32 am
Эта статья для ознакомления предлагает читателям общее представление об актуальной теме. Мы стремимся представить ключевые факты и идеи, которые помогут читателям получить представление о предмете и решить, стоит ли углубляться в изучение.
Нажми и узнай всё – https://craftart.ro/cum-se-defineste-o-pusca-sniper-airsoft
Harryhutty
21 Oct 25 at 8:33 am
купить проведенный диплом всеми [url=frei-diplom6.ru]купить проведенный диплом всеми[/url] .
Diplomi_tiOl
21 Oct 25 at 8:34 am
If you desire to take a great deal from this post then you have to apply
these methods to your won weblog.
buôn bán nội tạng
21 Oct 25 at 8:34 am
kraken ios
kraken darknet
JamesDaync
21 Oct 25 at 8:35 am
купить диплом в троицке [url=https://rudik-diplom4.ru]https://rudik-diplom4.ru[/url] .
Diplomi_uzOr
21 Oct 25 at 8:35 am
best seo agency [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_wqma
21 Oct 25 at 8:35 am
globalnetworkvision.bond – I hope they add more interactive content or community features in the future.
Neville Gahr
21 Oct 25 at 8:35 am
пин ап вход узбекистан [url=www.pinup5007.ru]www.pinup5007.ru[/url]
pin_up_uz_ydsr
21 Oct 25 at 8:36 am
Visit https://cryptomonitor.info where you will find a free web application for tracking, screening and technical analysis of the cryptocurrency market. Cryptomonitor is the best tools for crypto traders that allow you to receive comprehensive information.
The site also presents all the latest news from the world of cryptocurrencies.
togesrew
21 Oct 25 at 8:36 am
купить диплом в альметьевске [url=http://rudik-diplom1.ru]купить диплом в альметьевске[/url] .
Diplomi_drer
21 Oct 25 at 8:38 am
Have you ever thought about writing an ebook or guest authoring on other
sites? I have a blog based on the same topics you discuss and would love to have you share some stories/information. I
know my visitors would enjoy your work. If you’re even remotely
interested, feel free to send me an email.
longevity
21 Oct 25 at 8:40 am
купить диплом в соликамске [url=rudik-diplom4.ru]купить диплом в соликамске[/url] .
Diplomi_duOr
21 Oct 25 at 8:41 am
Промо-код 1xBet — укажите его в специальное поле при регистрации на сайте, пополните свой аккаунт на сумму от 100? и воспользуйтесь вознаграждением в размере 100 процентов (до 32 500 RUB).В меню игрока перейдите в раздел «Бонусные предложения» и активируйте вариант «Ввести код».Введите полученный промокод в строку для промокода. Сохраните изменения и ознакомьтесь с условиями использования.Актуальный промокод 1xBet 2026 можно узнать по ссылке — https://efaflex.ru/include/pages/?promokod_pri_registracii_6.html.
Jasonbrado
21 Oct 25 at 8:41 am
В этой статье вы найдете уникальные исторические пересечения с научными открытиями. Каждый абзац — это шаг к пониманию того, как наука и события прошлого создают основу для технологического будущего.
Получить больше информации – https://pravinasar.com/blog/?p=459
JamesHipsy
21 Oct 25 at 8:41 am