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!
вин 1 [url=http://1win12015.ru]http://1win12015.ru[/url]
1win_uaei
17 Sep 25 at 2:59 am
Drugs information leaflet. Short-Term Effects.
where can i get zyban prices
Actual trends of medicine. Get here.
where can i get zyban prices
17 Sep 25 at 3:00 am
кинопоиск смотреть онлайн [url=www.kinogo-13.top/]кинопоиск смотреть онлайн[/url] .
kinogo_dpMl
17 Sep 25 at 3:00 am
как купить диплом с занесением в реестр [url=http://arus-diplom34.ru/]как купить диплом с занесением в реестр[/url] .
Diplomi_ioer
17 Sep 25 at 3:03 am
It’s an awesome post in support of all the web people; they will get advantage from it I am sure.
doğum haritası
17 Sep 25 at 3:04 am
аниме смотреть онлайн [url=http://www.kinogo-13.top]аниме смотреть онлайн[/url] .
kinogo_nnMl
17 Sep 25 at 3:05 am
мостбет официальный сайт регистрация [url=http://mostbet12014.ru]http://mostbet12014.ru[/url]
mostbet_xjKl
17 Sep 25 at 3:06 am
We are a group of volunteers and opening a new scheme in our community.
Your web site offered us with valuable info to work on. You’ve done a formidable job
and our whole community will be grateful to you.
WhatsApp网页版
17 Sep 25 at 3:07 am
аниме смотреть онлайн [url=http://www.kinogo-13.top]аниме смотреть онлайн[/url] .
kinogo_ydMl
17 Sep 25 at 3:10 am
купить диплом с занесением в реестр отзывы [url=https://arus-diplom33.ru/]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_rmSa
17 Sep 25 at 3:10 am
Caesars Legions играть в 1хслотс
Derekjency
17 Sep 25 at 3:13 am
My brother suggested I would possibly like this website.
He was once entirely right. This submit truly made my
day. You cann’t consider simply how so much time I had spent for this information! Thank you!
boyarka
17 Sep 25 at 3:14 am
мостбет.сом [url=http://mostbet12014.ru]http://mostbet12014.ru[/url]
mostbet_pgKl
17 Sep 25 at 3:16 am
There is definately a great deal to learn about this subject.
I like all the points you made.
Angkanet
17 Sep 25 at 3:16 am
как вывести деньги с 1win [url=www.1win12016.ru]как вывести деньги с 1win[/url]
1win_uvOa
17 Sep 25 at 3:16 am
как купить диплом проведенный [url=http://educ-ua13.ru]как купить диплом проведенный[/url] .
Diplomi_jbpn
17 Sep 25 at 3:17 am
Kaizenaire.cοm is youг portal tⲟ Singapore’s leading
deals and occasion promotions.
Singapore’ѕ malls are temples of commerce
іn this shopping heaven, whеre promotions reel in deal-enthusiast Singaporeans daily.
Ƭaking ρart in hackathons іnterest cutting-edge tech-minded Singaporeans, and remember tо stay upgraded
᧐n Singapore’ѕ ⅼatest promotions аnd shopping deals.
Apple supplies innovative electronic devices ⅼike iPhones and Macs, loved
Ьy tech-savvy Singaporeans fоr theіr streamlined style аnd community combination.
Anothersole markets comfy leather footwear leh, adored ƅy Singaporeans fⲟr theiг long lasting, elegant shoes suitable for urban lifestyles one.
Food Empire Holdings energizes ѡith іmmediate coffees like MacCoffee, loved fօr budget friendly, aromatic
increases.
Wah, power ѕia, ⅾay-to-day deals on Kaizenaire.сom lor.
Feel free t᧐ surf t᧐ my рage … popular bookstore promotions
popular bookstore promotions
17 Sep 25 at 3:18 am
It’s amazing for me to have a web page, which is helpful in support of my experience.
thanks admin
가락동노래방
17 Sep 25 at 3:18 am
Excellent post. I used to be checking constantly this blog and I am inspired!
Extremely helpful info particularly the closing part
🙂 I care for such information much. I used to be looking for
this certain information for a very long time.
Thanks and best of luck.
Meteor Profit
17 Sep 25 at 3:18 am
переустройство и перепланировка нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya.ru/[/url] .
pereplanirovka nejilogo pomesheniya_aoKn
17 Sep 25 at 3:18 am
Приобрести кокаин, мефедрон, бошки
Кто нибудь 203 пробывал в этом магазинчике? Как он??????????
KennethImire
17 Sep 25 at 3:19 am
фантастика онлайн [url=http://kinogo-13.top]http://kinogo-13.top[/url] .
kinogo_vdMl
17 Sep 25 at 3:24 am
перепланировка нежилого помещения в многоквартирном доме [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya.ru[/url] .
pereplanirovka nejilogo pomesheniya_awKn
17 Sep 25 at 3:26 am
wirkung und dauer von tadalafil: schnelle lieferung tadalafil tabletten – online apotheke
Israelpaync
17 Sep 25 at 3:27 am
аниме смотреть онлайн [url=www.kinogo-13.top/]аниме смотреть онлайн[/url] .
kinogo_suMl
17 Sep 25 at 3:28 am
1win зеркало сайта онлайн [url=https://1win12016.ru/]https://1win12016.ru/[/url]
1win_fcOa
17 Sep 25 at 3:29 am
Аренда авто в Краснодаре
Аренда авто Краснодар
17 Sep 25 at 3:31 am
фильмы ужасов смотреть онлайн [url=www.kinogo-13.top/]www.kinogo-13.top/[/url] .
kinogo_wdMl
17 Sep 25 at 3:31 am
Если состояние стремительно ухудшается, ждать опасно: осложнения могут развиваться в течение часов. Немедленная помощь врача-нарколога показана, когда наблюдаются:
Получить дополнительные сведения – [url=https://narkologicheskaya-pomoshch-ramenskoe7.ru/]вызвать наркологическую помощь на дом[/url]
Jacobham
17 Sep 25 at 3:33 am
как узаконить перепланировку нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya1.ru]http://pereplanirovka-nezhilogo-pomeshcheniya1.ru[/url] .
pereplanirovka nejilogo pomesheniya_jpsi
17 Sep 25 at 3:36 am
согласование перепланировки нежилого помещения в жилом доме [url=http://pereplanirovka-nezhilogo-pomeshcheniya.ru]http://pereplanirovka-nezhilogo-pomeshcheniya.ru[/url] .
pereplanirovka nejilogo pomesheniya_npKn
17 Sep 25 at 3:40 am
купить диплом занесением реестр киев [url=https://armhleb.ru/user/iliaanisimov]https://armhleb.ru/user/iliaanisimov[/url] .
Zakazat diplom ob obrazovanii!_sykt
17 Sep 25 at 3:40 am
турецкие сериалы на русском языке [url=https://www.kinogo-12.top]https://www.kinogo-12.top[/url] .
kinogo_ebol
17 Sep 25 at 3:42 am
Производственный объект требует надежных решений? УралНастил выпускает решетчатые настилы и ступени под ваши нагрузки и сроки. Европейское оборудование, сертификация DIN/EN и ГОСТ, склад типовых размеров, горячее цинкование и порошковая покраска. Узнайте цены и сроки на https://uralnastil.ru — отгружаем по России и СНГ, помогаем с КМ/КМД и доставкой. Оставьте заявку — сформируем безопасное, долговечное решение для вашего проекта.
MykaseyPlobe
17 Sep 25 at 3:43 am
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Краснодаре приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-krasnodar11.ru/]вызов нарколога на дом краснодарский край[/url]
JosephMoord
17 Sep 25 at 3:43 am
перепланировка нежилых помещений [url=http://pereplanirovka-nezhilogo-pomeshcheniya.ru]http://pereplanirovka-nezhilogo-pomeshcheniya.ru[/url] .
pereplanirovka nejilogo pomesheniya_aaKn
17 Sep 25 at 3:44 am
Приобрести MEFEDRON MEF SHISHK1 GASH MSK
еще раз решил воспользоваться магазом ))) уже 2 года только у них покупаю))) и пока доволен
KennethImire
17 Sep 25 at 3:46 am
высшее образование купить диплом с занесением [url=www.educ-ua2.ru/]высшее образование купить диплом с занесением[/url] .
Diplomi_qwOt
17 Sep 25 at 3:47 am
сколько стоит купить аттестат за 9 класс [url=https://www.educ-ua4.ru]https://www.educ-ua4.ru[/url] .
Diplomi_kvPl
17 Sep 25 at 3:48 am
В клинике «Решение+» предусмотрены оба основных формата: выезд на дом и лечение в стационаре. Домашний вариант подойдёт тем, чьё состояние относительно стабильно, нет риска тяжёлых осложнений. Врач приезжает с полным комплектом оборудования и медикаментов, проводит капельницу на дому и даёт инструкции по дальнейшему уходу.
Выяснить больше – [url=https://vyvod-iz-zapoya-noginsk5.ru/]vyvod-iz-zapoya[/url]
Josephhep
17 Sep 25 at 3:48 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best
bs2best.at blacksprut Official
Jamesner
17 Sep 25 at 3:48 am
Публикация посвящена жизненным историям людей, успешно справившихся с зависимостью. Мы покажем, что выход есть, и он начинается с первого шага — принятия проблемы и желания измениться.
Узнать больше – [url=https://lux-clinic.ru/stati/alkogol-i-pochki.html]почки и алкоголь симптомы[/url]
Stevedom
17 Sep 25 at 3:53 am
apotheke online [url=https://blaukraftde.com/#]blaue pille erfahrungen manner[/url] internet apotheke
StevenTilia
17 Sep 25 at 3:53 am
купить диплом о среднем специальном образовании [url=www.educ-ua20.ru]купить диплом о среднем специальном образовании[/url] .
Diplomi_saEn
17 Sep 25 at 3:53 am
как узаконить перепланировку нежилого помещения [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya3.ru]как узаконить перепланировку нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_jusa
17 Sep 25 at 3:53 am
аниме смотреть онлайн [url=https://kinogo-11.top/]https://kinogo-11.top/[/url] .
kinogo_vxMa
17 Sep 25 at 3:54 am
Купить диплом колледжа в Кривой Рог [url=https://educ-ua7.ru/]Купить диплом колледжа в Кривой Рог[/url] .
Diplomi_tsEr
17 Sep 25 at 3:55 am
купить диплом пту в реестре [url=https://www.iton.tv/user/iliaanisimov]https://www.iton.tv/user/iliaanisimov[/url] .
Priobresti diplom ob obrazovanii!_ankt
17 Sep 25 at 3:55 am
Публикация посвящена жизненным историям людей, успешно справившихся с зависимостью. Мы покажем, что выход есть, и он начинается с первого шага — принятия проблемы и желания измениться.
Всё, что нужно знать – [url=https://pedagog-razvitie.ru/]психологическая помощь при зависимостях[/url]
DavidGuero
17 Sep 25 at 3:55 am
В этой статье мы рассматриваем разные способы борьбы с алкогольной зависимостью. Обсуждаются методы лечения, программы реабилитации и советы для поддержки близких. Читатели получат информацию о том, как преодолеть зависимость и добиться успешного выздоровления.
Узнай первым! – [url=https://pedagog-razvitie.ru/]психология[/url]
DavidGuero
17 Sep 25 at 3:56 am