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!
Plongez dans l’ambiance rétro et laissez-vous inspirer
par notre sélection de robes de mariage des années 60, pour un style unique et inoubliable
lors de votre jour J.
non gamstop casinos
30 Aug 25 at 4:30 am
Very great post. I just stumbled upon your blog and wanted to say that
I have truly loved browsing your weblog posts.
In any case I’ll be subscribing for your feed and
I hope you write again soon!
teetalk.vn lừa đảo công an truy quét cấm người chơi tham gia
30 Aug 25 at 4:31 am
We are a group of volunteers and opening a new scheme
in our community. Your web site offered us with valuable information to work
on. You have done an impressive job and our entire community will be grateful to you.
Shari
30 Aug 25 at 4:37 am
Мы готовы предложить документы институтов, расположенных в любом регионе России. Купить диплом любого университета:
[url=http://inteam.maxbb.ru/viewtopic.php?f=1&t=2122/]купить аттестаты за 11 с егэ[/url]
Diplomi_pwPn
30 Aug 25 at 4:43 am
Купить кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
30 Aug 25 at 4:44 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-316
30 Aug 25 at 4:46 am
Описание
Ознакомиться с деталями – http://vyvod-iz-zapoya-sochi7.ru/vyvod-iz-zapoya-anonimno-v-sochi/
JimmyOmify
30 Aug 25 at 4:47 am
купить диплом о высшем образовании недорого [url=www.educ-ua2.ru]купить диплом о высшем образовании недорого[/url] .
Diplomi_gnOt
30 Aug 25 at 4:47 am
The Memory Wave seems like a fascinating approach to supporting brain health and mental clarity.
I like how it’s designed to help with focus, memory retention,
and overall cognitive performance. It feels like a helpful option for anyone wanting a natural boost in mental sharpness and long-term brain support.
The Memory Wave
30 Aug 25 at 4:55 am
Это мода с акцентом на женственность и повседневность.
Трикотаж обеспечивает комфорт на протяжении всего дня.
Полный образ легко собрать в одном месте.
Сайт ориентирован на комфорт и простоту покупки.
25 Union делает стиль доступным всегда.
http://play123.co.kr/bbs/board.php?bo_table=online&wr_id=102043
30 Aug 25 at 4:58 am
https://sensible-tiger-pxrc9x.mystrikingly.com
https://sensible-tiger-pxrc9x.mystrikingly.com
30 Aug 25 at 5:00 am
Приобрести MEF MEFEDRON GASH ALFA KOKAIN
DanielVeiff
30 Aug 25 at 5:06 am
This paragraph will help the internet users for
setting up new web site or even a weblog from start to end.
Zorovixia
30 Aug 25 at 5:09 am
Hi friends, its wonderful post regarding educationand fully explained, keep it up all the
time.
best crypto casinos
30 Aug 25 at 5:12 am
Currently it looks like Expression Engine is the best blogging platform out there right now.
(from what I’ve read) Is that what you are using on your blog?
Казино с минимальным выводом
30 Aug 25 at 5:12 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-393
30 Aug 25 at 5:13 am
SlimMe Detox Tea ist eine tolle Unterstützung für alle,
die ihrem Körper etwas Gutes tun möchten. Die Mischung aus natürlichen Kräutern schmeckt nicht nur angenehm,
sondern kann auch dabei helfen, das Wohlbefinden zu steigern und ein leichteres Körpergefühl zu
fördern. Besonders praktisch finde ich, dass er sich einfach in den Alltag integrieren lässt – perfekt
für alle, die auf natürliche Weise mehr Balance suchen.
SlimMe Detox Tea
30 Aug 25 at 5:14 am
Phalo Boost Supplement sounds really promising for anyone looking to naturally increase
energy and support overall vitality. I like that it focuses on enhancing stamina and daily performance without relying on harsh stimulants.
Definitely looks like a solid option for long-term wellness support.
Phalo Boost Supplement
30 Aug 25 at 5:22 am
Мы можем предложить документы институтов, которые находятся в любом регионе России. Приобрести диплом любого университета:
[url=http://mbableu.com/employer/ukrdiplom/]купить аттестат в челябинске за 11 класс[/url]
Diplomi_dbPn
30 Aug 25 at 5:27 am
Магазин тут! Отзывы, Качество. kokain gash mefedron alfa-pvp
DanielVeiff
30 Aug 25 at 5:29 am
Creative
If some one needs to be updated with newest technologies afterward he
must be pay a visit this web site and be up to date all the
time.
Emotions
30 Aug 25 at 5:31 am
Когда организм на пределе, важна срочная помощь в Самаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara14.ru/]вывод из запоя капельница на дому[/url]
Michaelplert
30 Aug 25 at 5:33 am
Cabinnet IQ
8305 Statе Hwy 71 #110, Austin,
TX 78735, United Stаtes
254-275-5536
Minimalist
Minimalist
30 Aug 25 at 5:33 am
mostbet qeydiyyat aviator [url=http://mostbet4138.ru/]mostbet qeydiyyat aviator[/url]
mostbet_blot
30 Aug 25 at 5:34 am
This post is actually a pleasant one it helps new net viewers, who are wishing for
blogging.
Hitomi Tanaka
30 Aug 25 at 5:39 am
Выбор банного комплекса влияет на комфорт и
пользу процедуры.
на сайте
30 Aug 25 at 5:41 am
В Самаре решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara17.ru/]срочный вывод из запоя в самаре[/url]
Justingof
30 Aug 25 at 5:42 am
billiards ball
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
billiards ball
30 Aug 25 at 5:43 am
Check for drug interactions when you bupropion pronunciation and save the money for other purchases. wellbutrin tinnitus
ErcsFlulk
30 Aug 25 at 5:45 am
купить диплом с проводкой моих [url=www.arus-diplom31.ru]купить диплом с проводкой моих[/url] .
Diplomi_gbpl
30 Aug 25 at 5:45 am
Igenics seems like a great option for supporting eye health and
protecting vision as we age. I like that it’s
made with natural ingredients aimed at reducing oxidative stress and keeping the eyes sharp.
Definitely feels like something worth trying if
you’re looking to maintain clear, healthy vision for the
long run.
iGenics
30 Aug 25 at 5:48 am
read this post from Calmlife
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
read this post from Calmlife
30 Aug 25 at 5:49 am
I am actually delighted to read this webpage posts which consists of plenty of valuable information, thanks for providing such statistics.
sandibet
30 Aug 25 at 5:50 am
WW88 chính thống 2025, thể thao phong phú, giấy
phép hợp pháp, tỷ lệ thưởng cao.
Trang chủ WW88
30 Aug 25 at 5:50 am
Hey! This post couldn’t be written any better! Reading through
this post reminds me of my good old room mate! He always kept talking about this.
I will forward this write-up to him. Pretty sure he will have a
good read. Thanks for sharing!
mi88 nhà cái trực tuyến
30 Aug 25 at 5:51 am
Магазин тут! Отзывы, Качество. kokain gash mefedron alfa-pvp
DanielVeiff
30 Aug 25 at 5:51 am
Instead of paying high prices locally for stromectol 3 mg price after comparing multiple offers stromectol ivermectin buy
NtcqFlulk
30 Aug 25 at 5:52 am
Мы готовы предложить документы учебных заведений, расположенных в любом регионе РФ. Купить диплом университета:
[url=http://skrivunder.net/492274/]аттестат за 11 классов купить в красноярске[/url]
Diplomi_waPn
30 Aug 25 at 5:52 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-747
30 Aug 25 at 5:59 am
Nice respond in return of this question with real arguments and describing
the whole thing regarding that.
eSEOspace
30 Aug 25 at 6:03 am
I have been surfing online more than 2 hours today, yet I never found any interesting article like yours.
It is pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did,
the net will be a lot more useful than ever before.
YOURmeds24
30 Aug 25 at 6:05 am
купить диплом внесенный в реестр [url=http://arus-diplom31.ru]купить диплом внесенный в реестр[/url] .
Diplomi_cxpl
30 Aug 25 at 6:08 am
Приобрести MEF MEFEDRON GASH ALFA KOKAIN
DanielVeiff
30 Aug 25 at 6:13 am
где можно купить аттестаты 11 класса в онеге [url=https://arus-diplom23.ru]где можно купить аттестаты 11 класса в онеге[/url] .
Diplomi_bfol
30 Aug 25 at 6:16 am
аттестат 11 класса купить [url=https://arus-diplom24.ru/]аттестат 11 класса купить[/url] .
Diplomi_tpsa
30 Aug 25 at 6:20 am
We’re a group of volunteers and opening a new scheme in our community.
Your website offered us with valuable information to work on. You’ve done a
formidable job and our whole community will be grateful to
you.
Roof Washing service
30 Aug 25 at 6:21 am
Мы готовы предложить документы университетов, расположенных на территории всей Российской Федерации. Заказать диплом о высшем образовании:
[url=http://buch.christophgerber.ch/index.php?title=Benutzer:LenoreKeartland/]купить аттестаты за 11 класс 2021 год[/url]
Diplomi_zkPn
30 Aug 25 at 6:22 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-919
30 Aug 25 at 6:25 am
youtube 6244
youtubeijb
30 Aug 25 at 6:28 am
https://amulet34.ru/
Georgebon
30 Aug 25 at 6:32 am