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!
купить диплом в кирове [url=https://www.rudik-diplom10.ru]купить диплом в кирове[/url] .
Diplomi_vbSa
19 Oct 25 at 6:48 am
shopwithsmile.cfd – Great user experience, easy to navigate and find useful content.
Bao Danielovich
19 Oct 25 at 6:48 am
Excited for Minotaurus presale’s deals. $MTAUR’s zones special. Engagement high.
minotaurus token
WilliamPargy
19 Oct 25 at 6:48 am
купить диплом в самаре [url=www.rudik-diplom11.ru/]купить диплом в самаре[/url] .
Diplomi_kuMi
19 Oct 25 at 6:48 am
купить диплом занесением реестр киев [url=http://frei-diplom4.ru]http://frei-diplom4.ru[/url] .
Diplomi_aqOl
19 Oct 25 at 6:48 am
как купить диплом техникума с занесением в реестр цена в [url=http://frei-diplom5.ru]как купить диплом техникума с занесением в реестр цена в[/url] .
Diplomi_ibPa
19 Oct 25 at 6:49 am
купить диплом медсестры [url=https://www.frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_xokt
19 Oct 25 at 6:49 am
miglior prezzo Cialis originale: acquistare Cialis online Italia – tadalafil italiano approvato AIFA
JosephPseus
19 Oct 25 at 6:50 am
купить диплом реестр [url=www.frei-diplom4.ru/]купить диплом реестр[/url] .
Diplomi_bhOl
19 Oct 25 at 6:53 am
купить диплом в шахтах [url=https://rudik-diplom1.ru/]https://rudik-diplom1.ru/[/url] .
Diplomi_qyer
19 Oct 25 at 6:54 am
где купить диплом с занесением реестр [url=https://frei-diplom5.ru]где купить диплом с занесением реестр[/url] .
Diplomi_diPa
19 Oct 25 at 6:55 am
сделать проект квартиры для перепланировки [url=https://proekt-pereplanirovki-kvartiry17.ru]https://proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_vyml
19 Oct 25 at 6:55 am
купить диплом массажиста [url=https://rudik-diplom10.ru/]купить диплом массажиста[/url] .
Diplomi_kkSa
19 Oct 25 at 6:56 am
investsmarttoday.bond – Interesting articles and tips, definitely worth checking every day.
Brent Mckew
19 Oct 25 at 6:56 am
Nice post. I was checking constantly this blog and I am inspired!
Extremely useful info specifically the remaining part :
) I deal with such information much. I used to be seeking
this certain information for a long time. Thank you
and good luck.
سئو سایت پت شاپ
19 Oct 25 at 6:56 am
купить диплом в самаре [url=http://www.rudik-diplom13.ru]купить диплом в самаре[/url] .
Diplomi_zvon
19 Oct 25 at 6:57 am
купить диплом математика [url=www.rudik-diplom8.ru]купить диплом математика[/url] .
Diplomi_hlMt
19 Oct 25 at 6:57 am
купить диплом в сарапуле [url=https://rudik-diplom4.ru]купить диплом в сарапуле[/url] .
Diplomi_joOr
19 Oct 25 at 6:58 am
Great blog you have got here.. It’s hard
to find high quality writing like yours these days.
I honestly appreciate individuals like you! Take care!!
เบ็ตฟลิก 68
19 Oct 25 at 7:01 am
Лечение алкоголизма на дому в владимире – это удобный и эффективный способ борьбы с зависимостью. Терапия зависимости от алкоголя включает в себя очистку организма, которая помогает организму избавиться от токсинов. Наркологические услуги в владимире предлагают вывод из запоя и медицинское сопровождение при алкоголизме, включая методы кодирования. Ключевым моментом является обращение к наркологу, который проведет оценку состояния пациента и разработает индивидуальный план терапии. Эмоциональная поддержка также играет ключевую роль в процессе реабилитации. Процесс реабилитации включает различные программы лечения на дому, которые помогают предотвратить рецидивы. Советы по отказу от алкоголя могут стать ценными дополнениями к главной терапии. Посетив vivod-iz-zapoya-vladimir026.ru, вы узнаете о доступных услугах и советах по предотвращению рецидивов. Помните, что квалифицированная помощь – залог успешной борьбы с алкоголизмом.
narkologiyavladimirNeT
19 Oct 25 at 7:01 am
cialis generico: acquistare Cialis online Italia – compresse per disfunzione erettile
JosephPseus
19 Oct 25 at 7:03 am
купить диплом техникум официальный [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_yvea
19 Oct 25 at 7:04 am
An outstanding share! I have just forwarded this onto a friend
who had been conducting a little research on this.
And he in fact ordered me breakfast because I stumbled upon it for him…
lol. So let me reword this…. Thank YOU for the meal!!
But yeah, thanks for spending the time to talk about this matter here on your website.
Канады
19 Oct 25 at 7:05 am
купить диплом фитнес инструктора [url=https://rudik-diplom13.ru/]купить диплом фитнес инструктора[/url] .
Diplomi_bgon
19 Oct 25 at 7:05 am
Капельница от запоя в Нижнем Новгороде — процедура, направленная на детоксикацию организма и восстановление нормального самочувствия. Она включает в себя введение препаратов, способствующих выведению токсинов и восстановлению функций органов.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]вывод из запоя вызов город[/url]
JustinAxots
19 Oct 25 at 7:05 am
mel bet [url=https://melbetbonusy.ru/]mel bet[/url] .
melbet_yaOi
19 Oct 25 at 7:06 am
купить диплом в нальчике [url=rudik-diplom10.ru]купить диплом в нальчике[/url] .
Diplomi_srSa
19 Oct 25 at 7:07 am
проект на перепланировку квартиры заказать [url=http://proekt-pereplanirovki-kvartiry17.ru]http://proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_qgml
19 Oct 25 at 7:08 am
купить диплом в димитровграде [url=https://www.rudik-diplom4.ru]купить диплом в димитровграде[/url] .
Diplomi_reOr
19 Oct 25 at 7:09 am
купить проведенный диплом кого [url=http://frei-diplom6.ru]купить проведенный диплом кого[/url] .
Diplomi_goOl
19 Oct 25 at 7:09 am
купить свидетельство о браке [url=https://www.rudik-diplom5.ru]купить свидетельство о браке[/url] .
Diplomi_xnma
19 Oct 25 at 7:09 am
где купить диплом [url=www.rudik-diplom8.ru]где купить диплом[/url] .
Diplomi_knMt
19 Oct 25 at 7:11 am
tadalafilo sin receta [url=https://tadalafiloexpress.com/#]cialis precio[/url] farmacia online fiable en España
GeorgeHot
19 Oct 25 at 7:13 am
купить диплом гознак [url=http://www.rudik-diplom1.ru]купить диплом гознак[/url] .
Diplomi_oser
19 Oct 25 at 7:14 am
купить диплом в шахтах [url=https://www.rudik-diplom3.ru]https://www.rudik-diplom3.ru[/url] .
Diplomi_lcei
19 Oct 25 at 7:16 am
купить диплом в губкине [url=http://www.rudik-diplom4.ru]http://www.rudik-diplom4.ru[/url] .
Diplomi_zzOr
19 Oct 25 at 7:17 am
This is really fascinating, You are a very skilled blogger.
I have joined your rss feed and look forward to in the hunt for extra
of your magnificent post. Additionally, I have shared your site in my social networks
mm99
19 Oct 25 at 7:17 am
купить дипломы о высшем с занесением [url=http://rudik-diplom8.ru/]купить дипломы о высшем с занесением[/url] .
Diplomi_ifMt
19 Oct 25 at 7:19 am
купить диплом в балашихе [url=http://rudik-diplom5.ru/]купить диплом в балашихе[/url] .
Diplomi_wsma
19 Oct 25 at 7:19 am
Excited for Minotaurus presale’s deals. $MTAUR’s zones special. Engagement high.
minotaurus ico
WilliamPargy
19 Oct 25 at 7:19 am
купить диплом с проведением [url=https://frei-diplom6.ru/]купить диплом с проведением[/url] .
Diplomi_uxOl
19 Oct 25 at 7:20 am
What i don’t realize is in truth how you are not actually much more neatly-appreciated than you might be
now. You’re so intelligent. You realize therefore considerably relating to this matter,
produced me individually imagine it from numerous various angles.
Its like women and men are not interested until it is something to accomplish with Woman gaga!
Your individual stuffs outstanding. All the time take care of it up!
5mb.com
19 Oct 25 at 7:20 am
Usually I do not read post on blogs, however I
wish to say that this write-up very compelled me to try and do so!
Your writing style has been surprised me. Thanks, very great
article.
สล็อตวอเลท
19 Oct 25 at 7:25 am
сделать проект квартиры для перепланировки [url=https://www.proekt-pereplanirovki-kvartiry17.ru]https://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_himl
19 Oct 25 at 7:25 am
купить диплом в братске [url=www.rudik-diplom4.ru/]купить диплом в братске[/url] .
Diplomi_orOr
19 Oct 25 at 7:25 am
Code promo pour 1xBet : beneficiez un bonus de 100% pour l’inscription jusqu’a 130€. Augmentez le solde de vos fonds simplement en placant des paris avec un wager de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Pour activer ce code, rechargez votre compte a partir de 1€. Vous pouvez trouver le code promo 1xbet sur ce lien — http://www.tiroavolobologna.it/media/pgs/le-code-promo-1xbet_bonus.html.
ManuelPooke
19 Oct 25 at 7:27 am
купить медицинский диплом медсестры [url=www.frei-diplom13.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_rkkt
19 Oct 25 at 7:29 am
купить диплом в петрозаводске [url=rudik-diplom8.ru]купить диплом в петрозаводске[/url] .
Diplomi_ipMt
19 Oct 25 at 7:29 am
купить диплом инженера механика [url=https://www.rudik-diplom1.ru]купить диплом инженера механика[/url] .
Diplomi_luer
19 Oct 25 at 7:30 am
PotenzVital [url=http://potenzvital.com/#]Cialis generika günstig kaufen[/url] cialis kaufen ohne rezept
GeorgeHot
19 Oct 25 at 7:36 am