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!
1xbet mobi [url=www.1xbet-10.com/]www.1xbet-10.com/[/url] .
1xbet_xkea
26 Oct 25 at 1:30 pm
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra42cc.net]kra37 cc[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-41at.net]kra37 сс[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
[url=https://kra–42–cc.ru]kra37[/url]
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
[url=https://kra42-cc.net]kra36 cc[/url]
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra38 сс
https://kra-42—at.ru
Ronniefluem
26 Oct 25 at 1:32 pm
Navigating the bridge between traditional finance and the digital asset world has always been a complex challenge for many in the GSA community.
The endless delays and lack of integration between fiat and crypto platforms can severely hinder operational efficiency.
This is precisely why the Paybis fintech platform is a game-changer.
They aren’t just another crypto exchange; they’ve built a truly unified gateway that effortlessly handles both fiat and cryptocurrency banking.
Imagine executing trades across USD, EUR, and a
vast selection of major digital assets—all from a single, secure dashboard.
Their focus on robust security measures means you can transact
with confidence. A brief comment can’t possibly do justice to the
full scope of their feature set, especially their advanced
tools for corporate accounts. To get a complete picture of how Paybis is
streamlining this hybrid financial landscape,
you absolutely need to read the detailed analysis in the full article.
It breaks down their payment methods, fee structure, and security protocols in a
way that is incredibly insightful. I highly recommend check out the piece to see if
their platform aligns with your specific use-case. It’s a fantastic
deep-dive for anyone in our field looking to optimize their financial stack.
The link is in the main post—you won’t regret it.
full review
26 Oct 25 at 1:33 pm
купить диплом медсестры [url=www.frei-diplom15.ru]купить диплом медсестры[/url] .
Diplomi_groi
26 Oct 25 at 1:34 pm
медоборудование [url=https://medicinskoe–oborudovanie.ru/]медоборудование[/url] .
medicinskoe oborydovanie_tuei
26 Oct 25 at 1:35 pm
Hi there! This post could not be written much better!
Looking at this post reminds me of my previous roommate!
He always kept preaching about this. I most certainly will
forward this information to him. Pretty sure he
will have a very good read. Thank you for sharing!
Data Hongkong Lotto
26 Oct 25 at 1:35 pm
farmacia con entrega rápida: farmacia confiable en España – Confia Farmacia
RandySkync
26 Oct 25 at 1:36 pm
1x bet giri? [url=https://1xbet-13.com/]1xbet-13.com[/url] .
1xbet_bzKa
26 Oct 25 at 1:36 pm
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra-41–cc.ru]kra40 cc[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-42–at.ru]kra42 at[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra35 сс
https://kra-41—cc.ru
Jamessew
26 Oct 25 at 1:36 pm
mostbet официальный сайт вход [url=https://www.mostbet12031.ru]mostbet официальный сайт вход[/url]
mostbet_kg_kqMa
26 Oct 25 at 1:37 pm
Плесень ушла после санитарная обработка, спасибо!
уничтожение тараканов на кухне
KennethceM
26 Oct 25 at 1:38 pm
1xbet tr giri? [url=http://1xbet-14.com/]http://1xbet-14.com/[/url] .
1xbet_kzet
26 Oct 25 at 1:39 pm
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra–42—cc.ru]kra36 сс[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-42cc.net]kra37 сс[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra35 сс
https://kra–41—cc.ru
Jamessew
26 Oct 25 at 1:40 pm
1 xbet [url=1xbet-17.com]1 xbet[/url] .
1xbet_ykpl
26 Oct 25 at 1:40 pm
ставки на мостбет [url=https://mostbet12031.ru]https://mostbet12031.ru[/url]
mostbet_kg_anMa
26 Oct 25 at 1:41 pm
кракен зеркало
кракен ссылка
JamesDaync
26 Oct 25 at 1:41 pm
Как купить План в Когалыме?Люди, помогите с магазином – есть вариант https://people-law.ru
. Цены вроде ок, доставку обещают. Кто-то сталкивался с ними? Как у них с качеством?
Stevenref
26 Oct 25 at 1:43 pm
1xbet turkiye [url=www.1xbet-10.com/]www.1xbet-10.com/[/url] .
1xbet_wlea
26 Oct 25 at 1:43 pm
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra—42–at.ru]kra40[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-41-cc.com]kra42 cc[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra37 сс
https://kra41-cc.net
Kennethtip
26 Oct 25 at 1:44 pm
мостьет [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_jmmt
26 Oct 25 at 1:47 pm
1xbet com giri? [url=1xbet-13.com]1xbet-13.com[/url] .
1xbet_noKa
26 Oct 25 at 1:47 pm
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra-42at.net]kra41 сс[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-41-at.net]kra41 cc[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra35 at
https://kra41c.cc
Kennethtip
26 Oct 25 at 1:48 pm
Oh my goodness! Awesome article dude! Many thanks, However I am going through difficulties with your RSS.
I don’t understand the reason why I am unable to join it. Is there anybody else having similar RSS issues?
Anyone that knows the solution will you kindly respond?
Thanx!!
homemade dog food service
26 Oct 25 at 1:49 pm
медицинская техника [url=https://medicinskaya-tehnika.ru/]медицинская техника[/url] .
medicinskaya tehnika_xrEi
26 Oct 25 at 1:51 pm
Ищу обработка от блох в доме с выездом в область.
уничтожение рыжих тараканов
KennethceM
26 Oct 25 at 1:51 pm
1xbet tr [url=https://1xbet-17.com]1xbet tr[/url] .
1xbet_scpl
26 Oct 25 at 1:53 pm
мостбет скачать [url=http://mostbet12031.ru]http://mostbet12031.ru[/url]
mostbet_kg_vdMa
26 Oct 25 at 1:55 pm
1xbet giri? 2025 [url=http://1xbet-10.com]http://1xbet-10.com[/url] .
1xbet_luea
26 Oct 25 at 1:56 pm
1xbet giri? g?ncel [url=http://www.1xbet-13.com]1xbet giri? g?ncel[/url] .
1xbet_qpKa
26 Oct 25 at 1:56 pm
Фабрика VERESK превращает дворы и дома в пространства активного детства: шведские стенки, уличные комплексы со скалодромами, «качели-гнездо» и маты — всё продумано инженерами и проверено временем. Современное производство в Курске, быстрая отгрузка по России и индивидуальные решения по ротационному формованию делают выбор очевидным. Загляните на https://rdk.ru/ — в каталоге «хиты продаж» и новинки с усиленными горками Roto Mold. Безопасность, прочность и вдохновляющий дизайн здесь идут рука об руку.
gipowydat
26 Oct 25 at 1:58 pm
скачать mostbet [url=www.mostbet12031.ru]www.mostbet12031.ru[/url]
mostbet_kg_wuMa
26 Oct 25 at 1:58 pm
кракен android
кракен вход
JamesDaync
26 Oct 25 at 1:58 pm
ordinare Viagra generico in modo sicuro [url=https://mediuomo.com/#]Viagra generico con pagamento sicuro[/url] Medi Uomo
Davidduese
26 Oct 25 at 1:58 pm
brightnightpdx – A suggestion: check domain age and whether the SSL certificate is up to date to ensure it’s safe.
Isabelle Alber
26 Oct 25 at 1:58 pm
1xbet tr giri? [url=www.1xbet-14.com/]www.1xbet-14.com/[/url] .
1xbet_qyet
26 Oct 25 at 1:59 pm
Nice blog! Is your theme custom made or did you
download it from somewhere? A theme like yours with a few simple adjustements would really make my blog
shine. Please let me know where you got your design.
Kudos
WIN678
26 Oct 25 at 1:59 pm
kraken 2025
kraken СПб
JamesDaync
26 Oct 25 at 1:59 pm
1xbet yeni giri? adresi [url=https://1xbet-10.com/]1xbet-10.com[/url] .
1xbet_yeea
26 Oct 25 at 2:02 pm
Your way of telling the whole thing in this piece
of writing is truly pleasant, all can simply know it, Thanks a lot.
kra41 at
26 Oct 25 at 2:02 pm
Hi there! This post couldn’t be written any better!
Reading through this post reminds me of my good old room mate!
He always kept chatting about this. I will forward this page to him.
Fairly certain he will have a good read. Thank you for sharing!
джойказино приложение
26 Oct 25 at 2:03 pm
1xbet giri? yapam?yorum [url=http://www.1xbet-13.com]http://www.1xbet-13.com[/url] .
1xbet_rjKa
26 Oct 25 at 2:04 pm
теннесси бк скачать [url=https://www.mostbet12032.ru]https://www.mostbet12032.ru[/url]
mostbet_kg_ohmt
26 Oct 25 at 2:06 pm
1xbet tr giri? [url=https://1xbet-13.com/]https://1xbet-13.com/[/url] .
1xbet_qkKa
26 Oct 25 at 2:06 pm
поставщик медоборудования [url=https://www.medoborudovanie-postavka.ru]https://www.medoborudovanie-postavka.ru[/url] .
postavka medicinskogo oborydovaniya_qxsn
26 Oct 25 at 2:07 pm
please click the up coming article
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
please click the up coming article
26 Oct 25 at 2:07 pm
Вызывали дезинфекция квартиры после умершего ночью, приехали быстро!
вывести тараканов
KennethceM
26 Oct 25 at 2:09 pm
1xbet t?rkiye [url=http://1xbet-17.com]1xbet t?rkiye[/url] .
1xbet_ybpl
26 Oct 25 at 2:10 pm
Сколько времени занимает уничтожение клопов холодным туманом?
дезинфекция медицинских учреждений
KennethceM
26 Oct 25 at 2:10 pm
dearsparrows – Some articles feel very specialized, which is a plus if you’re looking for detailed content.
Ismael Sarnowski
26 Oct 25 at 2:11 pm
поставка медоборудования [url=medoborudovanie-postavka.ru]medoborudovanie-postavka.ru[/url] .
postavka medicinskogo oborydovaniya_snsn
26 Oct 25 at 2:11 pm