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!
dragonmoney
драгон мани
8 Sep 25 at 10:13 pm
para que sirve las tabletas cialis tadalafil de 5mg [url=http://evergreenrxusas.com/#]EverGreenRx USA[/url] EverGreenRx USA
Gregoryaerof
8 Sep 25 at 10:14 pm
мостбет вывести деньги [url=http://mostbet4172.ru]http://mostbet4172.ru[/url]
mostbet_ipKa
8 Sep 25 at 10:16 pm
Thanks for finally writing about > PHP hook, building hooks in your application – Sjoerd
Maessen blog at Sjoerd Maessen blog < Loved it!
kingslot96
8 Sep 25 at 10:18 pm
https://hub.docker.com/u/odopafedat
RichardWroli
8 Sep 25 at 10:19 pm
Thanks for sharing such a nice idea, paragraph is nice, thats
why i have read it entirely
haloperidol for child
8 Sep 25 at 10:21 pm
Ищете HOMAKOLL в России? Посетите сайт https://homakoll-market.ru/ – это официальный дилер клеевых составов HOMAKOLL. У нас представлена вся линейка продукции Хомакол, которую можно заказать с доставкой или забрать самовывозом. Ознакомьтесь с каталогом товаров по выгодным ценам, а мы осуществим бесплатную доставку оптовых заказов по всей территории России.
DyfijLyday
8 Sep 25 at 10:26 pm
EverGreenRx USA: does cialis make you last longer in bed – cialis professional
Jamespycle
8 Sep 25 at 10:28 pm
Howdy! This is my 1st comment here so I just wanted to give a
quick shout out and tell you I genuinely enjoy reading your articles.
Can you recommend any other blogs/websites/forums that cover
the same subjects? Thanks a lot!
Cards
8 Sep 25 at 10:29 pm
купить диплом о высшем образовании реестр [url=https://educ-ua13.ru]купить диплом о высшем образовании реестр[/url] .
Diplomi_ixpn
8 Sep 25 at 10:30 pm
mostbet lisenziyasi uz [url=http://mostbet4172.ru]mostbet lisenziyasi uz[/url]
mostbet_vgKa
8 Sep 25 at 10:36 pm
диплом купить с занесением в реестр [url=www.educ-ua13.ru]диплом купить с занесением в реестр[/url] .
Diplomi_atpn
8 Sep 25 at 10:37 pm
nexus darknet shop nexusdarknet site link bitcoin dark web [url=https://privatedarknetmarket.com/ ]darknet websites [/url]
Robertalima
8 Sep 25 at 10:39 pm
Ваш дом – ваши правила:
выбирайте, как быстро
хотите заехать
Вы сами решаете, на каком этапе завершить строительство. Дом можно получить в базовой комплектации, подготовленным к чистовой отделке или укомплектованным к заселению
Фиксированные сроки строительства и стоимость по договору для любого варианта готовности.
[url=https://ms-stroy.ru/stroitelstvo_monolitnyh_domov/]дом монолитно каркасный[/url]
Теплый контур
Включает в себя:
Подготовительные работы: выбор или разработка проекта дома
Устройство фундамента с устройством закладных под коммуникации
Устройство несущих стен, внешних и внутренних
Устройство перекрытий
Монтаж внутренних перегородок
Устройство монолитной железобетонной лестницы
Устройство утепленной кровли
Изготовление и монтаж окон
Рассчитать стоимость >
White box
Включает в себя «теплый контур», а также:
Работы по отделке фасада
Монтаж водосточной системы
Подшивка карнизных свесов
Внутренняя штукатурка стен и откосов
Монтаж системы отопления и водоснабжения
Монтаж черновой электрики со щитом и заземлением
Устройство черновой стяжки пола
Рассчитать стоимость > [url=https://ms-stroy.ru/stroitelstvo_domov_iz_gazobetonnyh_blokov/]готовые проекты домов из газобетона[/url]
Под ключ
Включает в себя «вайтбокс», а также:
Подготовка стен к финишному покрытию
Покраска оконных откосов и монтаж подоконников
Поклейка обоев, покраска стен, монтаж плитки
Монтаж напольных покрытий (плитка, ламинат и пр.)
Монтаж потолков и приборов освещения
Монтаж межкомнатных дверей
Монтаж чистовой сантехники, розеток и выключателей
Меблировка помещений и установка бытовой техники (Набор опций и материалов подбирается индивидуально)
Рассчитать стоимость >
https://ms-stroy.ru/
цокольный этаж цена
Jessesaf
8 Sep 25 at 10:42 pm
mostbet canlı kazino [url=www.mostbet4142.ru]www.mostbet4142.ru[/url]
mostbet_cbSi
8 Sep 25 at 10:42 pm
https://hub.docker.com/u/godarebahuly26
RichardWroli
8 Sep 25 at 10:42 pm
Hello to all, it’s genuinely a good for me to visit this
web page, it contains important Information.
KILLING CHILD
8 Sep 25 at 10:43 pm
What’s up colleagues, how is the whole thing, and what you wish for to
say concerning this paragraph, in my view its really awesome designed for me.
online medicine order discount
8 Sep 25 at 10:43 pm
легальный диплом купить [url=https://arus-diplom34.ru]легальный диплом купить[/url] .
Diplomi_lser
8 Sep 25 at 10:43 pm
купить диплом специалиста [url=www.educ-ua16.ru/]купить диплом специалиста[/url] .
Diplomi_bvmi
8 Sep 25 at 10:46 pm
https://mykredit-online.ru/
Travistug
8 Sep 25 at 10:46 pm
Big Max Books and Pearls KZ
Thomassmich
8 Sep 25 at 10:47 pm
mostbet azerbaycan rəsmisi [url=mostbet4145.ru]mostbet4145.ru[/url]
mostbet_jpot
8 Sep 25 at 10:48 pm
Ahaa, its good discussion on the topic of this paragraph at this place at this
web site, I have read all that, so now me also commenting
at this place.
شهریه پردیس خودگردان دانشگاه تهران
8 Sep 25 at 10:48 pm
mostbet canlı kazino [url=http://mostbet4142.ru/]http://mostbet4142.ru/[/url]
mostbet_ahSi
8 Sep 25 at 10:52 pm
mostbet aviator az [url=http://mostbet4145.ru]mostbet aviator az[/url]
mostbet_fvot
8 Sep 25 at 10:56 pm
Wow, superb blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of
your web site is magnificent, let alone the content!
kra7
8 Sep 25 at 11:02 pm
https://redclara.net/news/pgs/?1xbet_promo_code_free_bet_bonus.html
Michaelurirm
8 Sep 25 at 11:02 pm
Je suis totalement envoute par Luckland Casino, ca degage une vibe de jeu magique. La selection du casino est une cascade de plaisirs, incluant des jeux de table de casino d’une elegance feerique. Le support du casino est disponible 24/7, joignable par chat ou email. Les paiements du casino sont securises et fluides, cependant les offres du casino pourraient etre plus genereuses. Au final, Luckland Casino offre une experience de casino enchantee pour les joueurs qui aiment parier avec panache au casino ! Bonus le site du casino est une merveille graphique eclatante, ajoute une touche de feerie au casino.
luckland casino bonus code ohne einzahlung|
whimsyglowworm2zef
8 Sep 25 at 11:03 pm
диплом с проводкой купить [url=arus-diplom34.ru]диплом с проводкой купить[/url] .
Diplomi_iger
8 Sep 25 at 11:03 pm
https://vocologycenter.com/
Jameschize
8 Sep 25 at 11:03 pm
bj88
bj88
8 Sep 25 at 11:04 pm
I’m gone to inform my little brother, that he should
also pay a visit this web site on regular basis
to get updated from most recent news.
kra38 сс
8 Sep 25 at 11:04 pm
I got this website from my friend who informed me concerning this web page and at the moment this time I am visiting this web page and reading very informative posts at this place.
Immutable Azopt
8 Sep 25 at 11:04 pm
Thanks for some other excellent post. The place else may anyone get that type
of info in such a perfect manner of writing? I’ve a presentation subsequent
week, and I’m at the look for such info.
Index
8 Sep 25 at 11:06 pm
Казино Joycasino
DavidSwima
8 Sep 25 at 11:08 pm
Fine way of explaining, and nice piece of writing to obtain facts on the topic of my presentation subject matter,
which i am going to convey in institution of higher education.
pink salt trick reviews
8 Sep 25 at 11:10 pm
darknet market list nexus onion link dark market [url=https://darkmarketsdirectory.com/ ]darkmarkets [/url]
BrianWeX
8 Sep 25 at 11:11 pm
cialis precio: EverGreenRx USA – EverGreenRx USA
JamesMes
8 Sep 25 at 11:11 pm
В Люберцах капельница от запоя может спасти здоровье — в Stop Alko работают опытные наркологи, которые точно знают, как снять интоксикацию без вреда.
Углубиться в тему – [url=https://kapelnica-ot-zapoya-lyubercy12.ru/]капельница от запоя цена в подольске[/url]
Jamesjaw
8 Sep 25 at 11:11 pm
https://qna.habr.com/user/officialpromocode
qvtphkp
8 Sep 25 at 11:13 pm
Если нужен быстрый и безопасный способ восстановиться после запоя в Люберцах, обратитесь в Stop Alko — капельница с выводом токсинов помогает уже в первые часы.
Получить больше информации – [url=https://kapelnica-ot-zapoya-lyubercy13.ru/]врача капельницу от запоя подольск[/url]
EdwardSlatt
8 Sep 25 at 11:13 pm
купить диплом с занесением в реестры [url=https://educ-ua13.ru/]купить диплом с занесением в реестры[/url] .
Diplomi_lxpn
8 Sep 25 at 11:13 pm
I think this is among the most significant info for me.
And i am glad reading your article. But should remark
on some general things, The site style is ideal, the articles is really great : D.
Good job, cheers
Immediate Growth
8 Sep 25 at 11:13 pm
курсы seo [url=https://www.kursy-seo-2.ru]курсы seo[/url] .
kyrsi seo_fuEr
8 Sep 25 at 11:15 pm
https://t.me/Reyting_Casino_Russia
Casino
8 Sep 25 at 11:17 pm
купить диплом специалиста дешево [url=https://educ-ua16.ru/]купить диплом специалиста дешево[/url] .
Diplomi_pimi
8 Sep 25 at 11:18 pm
Beastie Bux играть в леонбетс
Bradleyetesy
8 Sep 25 at 11:18 pm
Je suis accro a Luckster Casino, ca pulse avec une energie de casino envoutante. Il y a une tempete de jeux de casino captivants, offrant des sessions de casino en direct qui enchantent. Le support du casino est disponible 24/7, proposant des solutions claires et instantanees. Les gains du casino arrivent a une vitesse magique, mais les offres du casino pourraient etre plus genereuses. Dans l’ensemble, Luckster Casino promet un divertissement de casino scintillant pour les chasseurs de fortune du casino ! A noter l’interface du casino est fluide et lumineuse comme une aurore magique, ce qui rend chaque session de casino encore plus magique.
luckster casino no deposit bonus|
spunkysnail4zef
8 Sep 25 at 11:20 pm
Jako žurnalista vím, že klíčem je text, který sluší čtenáři, obsahuje jednoduchá slova, srozumitelný styl a praktické informace, zvlášť když jde o „cz casino online“ a „kasina“. Tady je vaše nové, svěží a užitečné čtení: https://telegra.ph/Vyberte-si-to-prav%C3%A9-online-casino-cz-bezpe%C4%8Dn%C4%9B-v%C3%BDhodn%C4%9B-a-zodpov%C4%9Bdn%C4%9B-09-05
LeslieNurse
8 Sep 25 at 11:20 pm