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!
кракен даркнет маркет
kraken обмен
Henryamerb
27 Oct 25 at 2:18 am
купить диплом в прокопьевске [url=https://rudik-diplom8.ru/]купить диплом в прокопьевске[/url] .
Diplomi_viMt
27 Oct 25 at 2:19 am
The platform supports registration from laptops, and from various gadgets, therefore [url=https://rarar.com.bd/1xbet-casino-the-ultimate-gaming-experience-in-3/]https://rarar.com.bd/1xbet-casino-the-ultimate-gaming-experience-in-3/[/url] is easy mechanism, which will fit as for novices, so and with a view to enlightened users.
MarkMug
27 Oct 25 at 2:20 am
Viagra online kopen Nederland: Viagra online kopen Nederland – ED-medicatie zonder voorschrift
Jesuskax
27 Oct 25 at 2:20 am
наркологическая клиника город [url=http://www.narkologicheskaya-klinika-24.ru]http://www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_yrSr
27 Oct 25 at 2:21 am
диплом техникума колледжа купить пять плюс [url=https://frei-diplom11.ru]https://frei-diplom11.ru[/url] .
Diplomi_cisa
27 Oct 25 at 2:21 am
медицинское оборудование для больниц [url=http://medicinskoe–oborudovanie.ru]http://medicinskoe–oborudovanie.ru[/url] .
medicinskoe oborydovanie_psei
27 Oct 25 at 2:22 am
купить диплом в сызрани [url=http://rudik-diplom3.ru]купить диплом в сызрани[/url] .
Diplomi_lfei
27 Oct 25 at 2:22 am
медтехника [url=http://medicinskaya-tehnika.ru/]http://medicinskaya-tehnika.ru/[/url] .
medicinskaya tehnika_ykEi
27 Oct 25 at 2:22 am
нарколог психолог [url=narkologicheskaya-klinika-23.ru]narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_uiet
27 Oct 25 at 2:23 am
кракен ios
кракен тор
JamesDaync
27 Oct 25 at 2:23 am
диплом купить в реестре [url=www.frei-diplom1.ru/]диплом купить в реестре[/url] .
Diplomi_lpOi
27 Oct 25 at 2:23 am
купить диплом с проведением [url=http://www.frei-diplom6.ru]купить диплом с проведением[/url] .
Diplomi_ccOl
27 Oct 25 at 2:24 am
купить диплом в ангарске [url=https://rudik-diplom5.ru]купить диплом в ангарске[/url] .
Diplomi_pgma
27 Oct 25 at 2:25 am
купить диплом с реестром отзывы [url=www.frei-diplom5.ru/]купить диплом с реестром отзывы[/url] .
Diplomi_pvPa
27 Oct 25 at 2:25 am
купить диплом в ставрополе [url=www.rudik-diplom8.ru]купить диплом в ставрополе[/url] .
Diplomi_ueMt
27 Oct 25 at 2:25 am
Купить диплом техникума в Николаев [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_ucea
27 Oct 25 at 2:26 am
Нужна дератизация цена от вирусов, особенно сейчас.
дезинфекция цена
KennethceM
27 Oct 25 at 2:26 am
kraken
kraken официальный
Henryamerb
27 Oct 25 at 2:26 am
кракен vk3
кракен обмен
Henryamerb
27 Oct 25 at 2:27 am
купить диплом о среднем образовании [url=https://rudik-diplom11.ru/]купить диплом о среднем образовании[/url] .
Diplomi_wbMi
27 Oct 25 at 2:28 am
кракен vk5
kraken РФ
JamesDaync
27 Oct 25 at 2:28 am
купить диплом инженера [url=https://www.rudik-diplom4.ru]купить диплом инженера[/url] .
Diplomi_pfOr
27 Oct 25 at 2:28 am
купить диплом в дзержинске [url=www.rudik-diplom10.ru]купить диплом в дзержинске[/url] .
Diplomi_elSa
27 Oct 25 at 2:30 am
диплом проведенный купить [url=http://frei-diplom6.ru/]диплом проведенный купить[/url] .
Diplomi_ocOl
27 Oct 25 at 2:30 am
купить диплом сантехника [url=https://rudik-diplom2.ru]купить диплом сантехника[/url] .
Diplomi_bcpi
27 Oct 25 at 2:31 am
купить диплом ветеринара [url=http://rudik-diplom3.ru]купить диплом ветеринара[/url] .
Diplomi_kcei
27 Oct 25 at 2:31 am
Hey there! I just wanted to ask if you ever have any trouble with hackers?
My last blog (wordpress) was hacked and I ended up losing a few months of hard work due
to no data backup. Do you have any methods to protect against hackers?
seo class singapore
27 Oct 25 at 2:31 am
купить диплом в архангельске с занесением в реестр [url=www.frei-diplom5.ru]купить диплом в архангельске с занесением в реестр[/url] .
Diplomi_npPa
27 Oct 25 at 2:31 am
кракен вход
кракен vk2
Henryamerb
27 Oct 25 at 2:32 am
техникум диплом купить [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_cdea
27 Oct 25 at 2:32 am
Greetings from Ohio! I’m bored to tears at work so I decided to check out your website on my iphone during lunch break.
I really like the info you provide here and can’t wait to take a look when I get home.
I’m amazed at how fast your blog loaded on my phone ..
I’m not even using WIFI, just 3G .. Anyways, wonderful blog!
fast payout casinos online
27 Oct 25 at 2:32 am
лечение зависимостей в москве [url=http://narkologicheskaya-klinika-23.ru/]http://narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_ayet
27 Oct 25 at 2:33 am
купить диплом в ярославле [url=http://rudik-diplom8.ru/]купить диплом в ярославле[/url] .
Diplomi_jhMt
27 Oct 25 at 2:33 am
оборудование для больниц [url=http://medicinskoe–oborudovanie.ru/]http://medicinskoe–oborudovanie.ru/[/url] .
medicinskoe oborydovanie_zeei
27 Oct 25 at 2:33 am
купить диплом кандидата наук [url=www.rudik-diplom4.ru]купить диплом кандидата наук[/url] .
Diplomi_olOr
27 Oct 25 at 2:34 am
купить диплом техникума ссср в нурсултане [url=http://www.frei-diplom11.ru]купить диплом техникума ссср в нурсултане[/url] .
Diplomi_xbsa
27 Oct 25 at 2:35 am
Why visitors still use to read news papers when in this technological globe all is presented on net?
roller shutter
27 Oct 25 at 2:35 am
купить жд диплом техникума [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_msea
27 Oct 25 at 2:36 am
купить диплом в великом новгороде [url=http://www.rudik-diplom10.ru]купить диплом в великом новгороде[/url] .
Diplomi_tcSa
27 Oct 25 at 2:36 am
купить диплом внесенный в реестр [url=http://frei-diplom6.ru]купить диплом внесенный в реестр[/url] .
Diplomi_xuOl
27 Oct 25 at 2:37 am
kraken обмен
kraken vk6
Henryamerb
27 Oct 25 at 2:38 am
медоборудование [url=medicinskoe–oborudovanie.ru]медоборудование[/url] .
medicinskoe oborydovanie_fyei
27 Oct 25 at 2:39 am
куплю диплом младшей медсестры [url=https://frei-diplom15.ru/]https://frei-diplom15.ru/[/url] .
Diplomi_wfoi
27 Oct 25 at 2:40 am
Может быть, не отрицаю. Пока никого винить не буду, потому что вполне возможно что я и сам закосячил. Но вроде все правильно делал. При том я не один такой..До этого приходил ам (окло недели-полторы, назад) делал все точно так же, но только на черной заварке принцесса Нури, 1 к 10, и с водника уносило далекоооо….всех кто пробовал этот водник.. купить скорость, кокаин, мефедрон, гашиш Брал хоть и один раз, но все было отлично! Жду второго заказа)
RichardDring
27 Oct 25 at 2:40 am
медтехника [url=medicinskaya-tehnika.ru]medicinskaya-tehnika.ru[/url] .
medicinskaya tehnika_ehEi
27 Oct 25 at 2:40 am
купить диплом в йошкар-оле [url=www.rudik-diplom10.ru]купить диплом в йошкар-оле[/url] .
Diplomi_tdSa
27 Oct 25 at 2:41 am
купить диплом в каспийске [url=www.rudik-diplom2.ru]www.rudik-diplom2.ru[/url] .
Diplomi_ibpi
27 Oct 25 at 2:42 am
купить диплом в волгограде [url=https://rudik-diplom11.ru/]купить диплом в волгограде[/url] .
Diplomi_xhMi
27 Oct 25 at 2:42 am
Кто знает, сколько уничтожение тараканов стоит за м2?
уничтожение мышей
KennethceM
27 Oct 25 at 2:42 am