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!
Строительный сайт https://vitamax.dp.ua с полезными материалами о ремонте, дизайне и современных технологиях. Обзоры стройматериалов, инструкции по монтажу, проекты домов и советы экспертов.
Jesusnut
17 Aug 25 at 1:39 pm
mostbet baixar [url=www.mostbet11072.ru]www.mostbet11072.ru[/url]
mostbet_kg_edKr
17 Aug 25 at 1:41 pm
What’s up friends, how is the whole thing,
and what you would like to say concerning this post, in my view its actually awesome in support of me.
Source of information
17 Aug 25 at 1:43 pm
скачать мостбет официальный сайт [url=https://www.mostbet11074.ru]https://www.mostbet11074.ru[/url]
mostbet_kg_gzsn
17 Aug 25 at 1:45 pm
Have you ever considered about including a little bit more than just your articles?
I mean, what you say is fundamental and everything.
But think of if you added some great graphics or video clips
to give your posts more, “pop”! Your content is excellent but with pics and videos,
this blog could undeniably be one of the greatest in its niche.
Great blog!
trojan value pack
17 Aug 25 at 1:46 pm
Hi, I do believe this is a great site. I stumbledupon it 😉 I may come back once again since i have book marked it.
Money and freedom is the greatest way to change, may you be rich and continue to guide others.
gacor internasional
17 Aug 25 at 1:47 pm
мостьет [url=http://mostbet11068.ru]мостьет[/url]
mostbet_gqpn
17 Aug 25 at 1:47 pm
https://sildenapeak.com/# SildenaPeak
Danielchumn
17 Aug 25 at 1:48 pm
South African bookmakers supply free bets and bonus bets in a number of various types once yyou turn into a brand new buyer.
With a huge number of South African bookmakers,
you wish to know you are getting the very bes free bets available when joining.
Many consider this to be the best sports
betting sites bonus, because it has no risk connected to iit in any respect.
You possibly can read every thing that you must know about South Africa new betting websites by visiting our sports betting
sites critiques part. No deposit bonus sports activities bonuses are sometimes in the
form of a free guess on registration. You can find
extra MLB betting bonuses proper right here. However,
sporadic attempts of faar proper organisations tto make use of tthe tournament as a platform foor their propaganda remained unsuccessful.
New betting sites are launched usualy ass new
names come to the market, and we are proper available to offer
you aall the information aboht them. New buyer free guess offers and
bonuses are incredible, as they give new gamers
the chance to earn a great deal of actual money from the second they arrive at a site.
Instead of merely providing bettors free bets, some bookmakers use a
new type of promotion through whuch they provide clients money again as money through PayPal or different
strategies once thuey join.
My blkog post: national lottery casino
national lottery casino
17 Aug 25 at 1:50 pm
выигрышные live ставки на мостбет [url=http://mostbet11069.ru/]выигрышные live ставки на мостбет[/url]
mostbet_fvSa
17 Aug 25 at 1:51 pm
купить аттестат за 11 класс с занесением в [url=https://www.arus-diplom22.ru]https://www.arus-diplom22.ru[/url] .
Diplomi_amsl
17 Aug 25 at 1:53 pm
жить в моменте Жить в моменте: Растворитесь в окружающем мире, почувствуйте его энергию, соединитесь с ним. Жить в моменте – значит быть полностью осознанным, присутствующим и благодарным.
RichardUnich
17 Aug 25 at 1:55 pm
купить официальный аттестат 11 классов [url=www.arus-diplom25.ru]купить официальный аттестат 11 классов[/url] .
Diplomi_udot
17 Aug 25 at 1:55 pm
Every weekend i սsed to go to see tһis web site, for the reasⲟn that
i want enjoyment, since this this ѕite conations actually gоod funny material too.
Here is my Ƅlog post :: canvas bag
canvas bag
17 Aug 25 at 1:56 pm
Инфузии выполняются с помощью автоматизированных насосов, позволяющих скорректировать скорость введения в зависимости от показателей безопасности.
Исследовать вопрос подробнее – [url=https://medicinskij-vyvod-iz-zapoya.ru/]вывод из запоя капельница в красноярске[/url]
RobertExevy
17 Aug 25 at 1:58 pm
mostbet com скачать [url=http://mostbet11073.ru]mostbet com скачать[/url]
mostbet_kg_guSl
17 Aug 25 at 1:59 pm
самый точный прогноз на футбол сегодня [url=http://kompyuternye-prognozy-na-futbol13.ru]http://kompyuternye-prognozy-na-futbol13.ru[/url] .
komputernie prognozi na fytbol_hhSr
17 Aug 25 at 2:06 pm
cialis information: cialis from canada – Tadalify
PeterTEEFS
17 Aug 25 at 2:07 pm
купить диплом занесенный в реестр [url=www.arus-diplom32.ru/]купить диплом занесенный в реестр[/url] .
Diplomi_mdpi
17 Aug 25 at 2:09 pm
купить аттестат за 11 классов в иваново [url=https://www.arus-diplom24.ru]купить аттестат за 11 классов в иваново[/url] .
Diplomi_naKn
17 Aug 25 at 2:09 pm
I don’t know whether it’s just me or if everybody
else encountering issues with your blog. It looks like some of the text in your
posts are running off the screen. Can somebody else
please provide feedback and let me know if this is happening to them as well?
This could be a issue with my web browser because I’ve had this happen previously.
Cheers
pawbiotix
17 Aug 25 at 2:11 pm
точные прогнозы на футбол [url=kompyuternye-prognozy-na-futbol13.ru]точные прогнозы на футбол[/url] .
komputernie prognozi na fytbol_ukSr
17 Aug 25 at 2:11 pm
купить аттестат за 11 класс в уфе [url=http://arus-diplom22.ru/]http://arus-diplom22.ru/[/url] .
Diplomi_jssl
17 Aug 25 at 2:15 pm
Миссия клиники “Путь к выздоровлению” заключается в содействии восстановлению здоровья и социальной реинтеграции людей, столкнувшихся с проблемами зависимости. Мы стремимся к комплексному решению этой сложной задачи, учитывая физические, психологические и социальные аспекты зависимости. Наша цель — не только помочь пациентам избавиться от физической зависимости, но и обеспечить их психологическое восстановление и возвращение к нормальной жизни в обществе.
Подробнее тут – https://нарко-фильтр.рф/vivod-iz-zapoya-na-domu-v-rostove-na-donu
Billymub
17 Aug 25 at 2:16 pm
купить аттестат за 11 класс новосибирск [url=www.arus-diplom25.ru/]www.arus-diplom25.ru/[/url] .
Diplomi_fdot
17 Aug 25 at 2:17 pm
диплом настоящий купить с занесением в реестр [url=http://arus-diplom33.ru]http://arus-diplom33.ru[/url] .
Bistro i prosto priobresti diplom o visshem obrazovanii!_tgoi
17 Aug 25 at 2:19 pm
где в омске купить 11 классов аттестат [url=https://arus-diplom22.ru]где в омске купить 11 классов аттестат[/url] .
Diplomi_njsl
17 Aug 25 at 2:21 pm
купить красный аттестаты за 11 класс 2022 [url=http://arus-diplom25.ru/]http://arus-diplom25.ru/[/url] .
Diplomi_zuot
17 Aug 25 at 2:23 pm
get flexeril cyclobenzaprine no prescription online
how to order flexeril cyclobenzaprine buy dublin
cheapest buy flexeril cyclobenzaprine without recipe
17 Aug 25 at 2:29 pm
Medicines information for patients. Generic Name.
buy cheap valtrex prices
All about medicines. Get information here.
buy cheap valtrex prices
17 Aug 25 at 2:34 pm
Tadalify: Tadalify – Tadalify
ElijahKic
17 Aug 25 at 2:34 pm
топ прогнозы на футбол сегодня [url=http://www.kompyuternye-prognozy-na-futbol14.ru]http://www.kompyuternye-prognozy-na-futbol14.ru[/url] .
komputernie prognozi na fytbol_pxet
17 Aug 25 at 2:36 pm
точный прогноз на спорт сегодня [url=http://www.kompyuternye-prognozy-na-futbol13.ru]точный прогноз на спорт сегодня[/url] .
komputernie prognozi na fytbol_taSr
17 Aug 25 at 2:38 pm
Hey there, I think your blog might be having browser compatibility issues.
When I look at your blog in Safari, it looks fine but when opening in Internet Explorer,
it has some overlapping. I just wanted to give you
a quick heads up! Other then that, great blog!
Global Hub for Artists & Writers
17 Aug 25 at 2:39 pm
военнаЯ пенсиЯ онлайн
Willardken
17 Aug 25 at 2:40 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ɗr c121,
Charlotte, NC 28273, United Ѕtates
+19803517882
Build and renovations design custom
Build and renovations design custom
17 Aug 25 at 2:41 pm
как зайти на сайт mostbet [url=http://mostbet11073.ru/]как зайти на сайт mostbet[/url]
mostbet_kg_foSl
17 Aug 25 at 2:44 pm
Hello all, here every one is sharing these familiarity, so it’s fastidious to read this web site, and I used to pay a visit this web site daily.
water damage restoration Gresham OR
17 Aug 25 at 2:44 pm
Наш подход охватывает все аспекты реабилитации, помогая пациентам справиться с зависимостями и вернуться к полноценной жизни.
Исследовать вопрос подробнее – https://медицина-вывод-из-запоя.рф/vyvod-iz-zapoya-na-domu-v-nizhnem-novgoroge.xn--p1ai/
Floydmom
17 Aug 25 at 2:46 pm
мостбет скачат [url=mostbet11067.ru]mostbet11067.ru[/url]
mostbet_gion
17 Aug 25 at 2:47 pm
mostbet игры [url=https://www.mostbet11067.ru]https://www.mostbet11067.ru[/url]
mostbet_pkon
17 Aug 25 at 2:48 pm
Sildenafil oral jelly fast absorption effect: KamaMeds – Sildenafil oral jelly fast absorption effect
PeterTEEFS
17 Aug 25 at 2:49 pm
где можно купить аттестат 11 класса 2016 [url=https://arus-diplom22.ru]где можно купить аттестат 11 класса 2016[/url] .
Diplomi_sysl
17 Aug 25 at 2:50 pm
инъектирование [url=https://remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi /]remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi [/url] .
inektirovanie_pxOr
17 Aug 25 at 2:51 pm
Листала Facebook и наткнулась на пост о том, как [url=https://licenz.pro/med-litsenziya/]получить медицинскую лицензию на помещение[/url]. Сначала подумала, что очередная реклама. Но почитала отзывы, рискнула — и не пожалела. Компания всё сделала быстро и грамотно, помогла пройти проверку. Теперь кабинет полностью соответствует требованиям и работает по закону.
Roveryza
17 Aug 25 at 2:52 pm
купить аттестат 11 класс чебоксары [url=arus-diplom25.ru]купить аттестат 11 класс чебоксары[/url] .
Diplomi_npot
17 Aug 25 at 2:52 pm
компьютерные прогнозы на футбол [url=www.kompyuternye-prognozy-na-futbol13.ru]компьютерные прогнозы на футбол[/url] .
komputernie prognozi na fytbol_yxSr
17 Aug 25 at 2:52 pm
мостбет официальное приложение [url=http://mostbet11071.ru]http://mostbet11071.ru[/url]
mostbet_knKr
17 Aug 25 at 2:52 pm
mostbet kg скачать на андроид [url=http://mostbet11075.ru/]http://mostbet11075.ru/[/url]
mostbet_kg_kqei
17 Aug 25 at 2:57 pm
купить аттестат за 11 класс пермь [url=http://arus-diplom24.ru/]купить аттестат за 11 класс пермь[/url] .
Diplomi_ydKn
17 Aug 25 at 2:57 pm