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://transformatornye-podstancii-kupit2.ru]https://transformatornye-podstancii-kupit2.ru[/url] .
transformatornie podstancii kypit_ijoi
21 Aug 25 at 5:14 pm
диплом реестр купить [url=http://arus-diplom35.ru]диплом реестр купить[/url] .
Priobresti diplom o visshem obrazovanii!_tuot
21 Aug 25 at 5:16 pm
https://bio.site/kehecehuboc
Eugeneimatt
21 Aug 25 at 5:17 pm
buy amoxicillin over the counter uk: amoxicillin from canada – amoxicillin price canada
JerryLinee
21 Aug 25 at 5:17 pm
It’s in fact very difficult in this full of activity
life to listen news on Television, so I just use web for
that purpose, and obtain the hottest news.
Titanium Shield Holdings
21 Aug 25 at 5:20 pm
Thanks for the auspicious writeup. It in fact was once a entertainment account
it. Glance advanced to more added agreeable
from you! By the way, how can we communicate?
FB68.COM
21 Aug 25 at 5:27 pm
buy amoxicillin online uk: amoxicillin buy online canada – TrustedMeds Direct
WayneViemo
21 Aug 25 at 5:29 pm
купить трансформаторные подстанции [url=www.transformatornye-podstancii-kupit2.ru]www.transformatornye-podstancii-kupit2.ru[/url] .
transformatornie podstancii kypit_fdoi
21 Aug 25 at 5:29 pm
купить аттестат 11 класс спб [url=http://www.arus-diplom24.ru]купить аттестат 11 класс спб[/url] .
Diplomi_xosa
21 Aug 25 at 5:32 pm
I will immediately seize your rss as I can’t to find your e-mail subscription link or newsletter service.
Do you have any? Kindly permit me know in order that I may subscribe.
Thanks.
link
21 Aug 25 at 5:35 pm
https://say.la/read-blog/126797
Eugeneimatt
21 Aug 25 at 5:38 pm
I’m truly enjoying the design and layout of your website.
It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme?
Excellent work!
58win
21 Aug 25 at 5:38 pm
ктп киосковая трансформаторная подстанция [url=www.transformatornye-podstancii-kupit2.ru/]www.transformatornye-podstancii-kupit2.ru/[/url] .
transformatornie podstancii kypit_lfoi
21 Aug 25 at 5:39 pm
Умные цитаты про любовь. Красивые слова о жизни. Лучшие цитаты о жизни. Цитата это. Лучшие цитаты твиттера. Позитивный человек цитаты. Цитаты счастье. Краткие цитаты великих людей.
citaty-top-938
21 Aug 25 at 5:39 pm
купить аттестат за 11 класс рязань [url=http://www.arus-diplom24.ru]http://www.arus-diplom24.ru[/url] .
Diplomi_atsa
21 Aug 25 at 5:40 pm
NewEra Protect is gaining attention as a supplement that supports immune strength and overall well-being.
With its natural ingredients, it’s designed to help the body
fight off everyday challenges, reduce tiredness, and promote vitality.
Many people appreciate it as an easy, reliable way to stay
healthy and energized year-round.
NewEra Protect
21 Aug 25 at 5:41 pm
купить диплом с занесением в реестр [url=www.arus-diplom33.ru]купить диплом с занесением в реестр[/url] .
Diplomi_oxSa
21 Aug 25 at 5:46 pm
SushiSwap is a decentralized unpleasantness (DEX) and DeFi ecosystem contribution permissionless cosmetic swaps, takings agriculture, liquidity seemly loophole, staking,
and governance — all powered career the SUSHI token.
With in preferably of over with a dozen blockchains and advanced features like
SushiXSwap and BentoBox, SushiSwap continues to incite the
boundaries of decentralized finance.
sushi swap crypto
21 Aug 25 at 5:47 pm
how to get clomid without rx: FertiCare Online – FertiCare Online
JerryLinee
21 Aug 25 at 5:48 pm
buy ivermectin tablets: how to buy stromectol – IverGrove
FrankCax
21 Aug 25 at 5:50 pm
Academypoker.ru исключительно информационный
ресурс.
покердом зеркало
21 Aug 25 at 5:58 pm
https://hub.docker.com/u/rgelywulecypafo
Eugeneimatt
21 Aug 25 at 5:59 pm
Затяжной запой опасен для жизни. Врачи наркологической клиники в Санкт-Петербурге проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-sankt-peterburge.ru/]вывод из запоя на дому недорого санкт-петербург[/url]
DavidVow
21 Aug 25 at 6:01 pm
комплектные трансформаторные подстанции купить [url=http://www.transformatornye-podstancii-kupit1.ru]http://www.transformatornye-podstancii-kupit1.ru[/url] .
transformatornie podstancii kypit_kfor
21 Aug 25 at 6:02 pm
Посетитель сам решает нужен ему бонус или нет
и в любое время может отказаться от поощрения.
мостбет вход официальный сайт
21 Aug 25 at 6:04 pm
Nice post. I was checking continuously this blog and
I am impressed! Extremely helpful information specially the
last part 🙂 I care for such info a lot. I was looking for this particular information for a very long time.
Thank you and best of luck.
casino online stranieri
21 Aug 25 at 6:06 pm
AquaSculpt is a breakthrough solution designed to activate
the body’s natural fat-burning process by mimicking the effects of cold exposure—without the need for ice baths
or strict crash diets. It helps boost metabolism,
support weight management, and improve energy levels.
Many people like it because it offers a simple, convenient, and non-invasive way to reach their fitness goals.
AquaSculpt
21 Aug 25 at 6:07 pm
как купить легально диплом о высшем образовании [url=http://arus-diplom34.ru/]как купить легально диплом о высшем образовании[/url] .
Diplomi_nier
21 Aug 25 at 6:10 pm
Ищете быструю доставку свежих цветов Минску, Беларуси и миру? Посетите сайт https://sendflowers.by/ и вы найдете самый широкий ассортимент свежих цветов с доставкой на дом. Ознакомьтесь с нашим огромным каталогом, и вы обязательно найдете те цветы, которые вы захотите подарить! Также у нас вы можете заказать доставку роз и букетов в любую точку мира, а букеты составляют только самые опытные флористы! Подробнее на сайте.
SonersLar
21 Aug 25 at 6:11 pm
Диагностика включает общий и биохимический анализ крови, оценку работы печени и почек, электрокардиографию и психологическое тестирование для выявления уровня мотивации.
Изучить вопрос глубже – https://kodirovanie-ot-alkogolizma-pushkino4.ru/kodirovanie-ot-alkogolizma-ceny-v-pushkino
SteveKnody
21 Aug 25 at 6:12 pm
трансформаторные подстанции купить [url=https://www.transformatornye-podstancii-kupit1.ru]https://www.transformatornye-podstancii-kupit1.ru[/url] .
transformatornie podstancii kypit_qqor
21 Aug 25 at 6:12 pm
купить аттестаты за 11 вечерней школе 1992 2002 п яр или глазов [url=https://www.arus-diplom25.ru]купить аттестаты за 11 вечерней школе 1992 2002 п яр или глазов[/url] .
Diplomi_pcot
21 Aug 25 at 6:15 pm
купить аттестат 11 классов москва [url=http://arus-diplom24.ru]http://arus-diplom24.ru[/url] .
Diplomi_zzsa
21 Aug 25 at 6:17 pm
I seriously love your site.. Pleasant colors & theme. Did you develop this site yourself?
Please reply back as I’m hoping to create my own personal blog and would like to learn where you got this from or exactly what the theme is named.
Thank you!
ok365
21 Aug 25 at 6:18 pm
Чем выше активность геймера в Он-Икс Казино, тем больше преимуществ он имеет.
он икс казино зеркало
21 Aug 25 at 6:19 pm
ставки прогнозы [url=stavki-prognozy-one.ru]stavki-prognozy-one.ru[/url] .
stavki prognozi_mtsr
21 Aug 25 at 6:20 pm
https://say.la/read-blog/126375
JamesWek
21 Aug 25 at 6:21 pm
Thank you for the good writeup. It in reality was once a amusement
account it. Look complex to far delivered agreeable from
you! However, how could we keep in touch?
roofers near me
21 Aug 25 at 6:22 pm
Luxury1288 Merupakan Sebuah Link
Situs Slot Gacor Online Yang Sangat Banyak Peminatnya Dikarenakan Permainan Yang Tersedia Sangat Lengkap.
Luxury1288
21 Aug 25 at 6:29 pm
Way cool! Some very valid points! I appreciate you writing this post and the rest of the website is very good.
Kalevantrex
21 Aug 25 at 6:31 pm
ставки прогнозы [url=www.stavki-prognozy-one.ru]www.stavki-prognozy-one.ru[/url] .
stavki prognozi_hysr
21 Aug 25 at 6:32 pm
Everyone loves what you guys are up too. Such clever work and coverage!
Keep up the wonderful works guys I’ve incorporated you guys to my personal blogroll.
water remediation near me
21 Aug 25 at 6:34 pm
наружная трансформаторная подстанция купить [url=http://transformatornye-podstancii-kupit1.ru/]http://transformatornye-podstancii-kupit1.ru/[/url] .
transformatornie podstancii kypit_vyor
21 Aug 25 at 6:38 pm
купить аттестат за 11 класс отзывы [url=http://arus-diplom24.ru/]купить аттестат за 11 класс отзывы[/url] .
Diplomi_lasa
21 Aug 25 at 6:40 pm
купить аттестат за 11 класс в сыктывкаре [url=arus-diplom24.ru]купить аттестат за 11 класс в сыктывкаре[/url] .
Diplomi_uxKn
21 Aug 25 at 6:41 pm
https://git.project-hobbit.eu/aicabygab
JamesWek
21 Aug 25 at 6:42 pm
I always used to study post in news papers but now as I am a user of net therefore from now I am using net for posts, thanks to web.
My web blog :: OnebetAsia Prediksi SGP
OnebetAsia Prediksi SGP
21 Aug 25 at 6:44 pm
Stavki Prognozy [url=https://stavki-prognozy-one.ru/]https://stavki-prognozy-one.ru/[/url] .
stavki prognozi_kpsr
21 Aug 25 at 6:44 pm
Cabinet IQ Austin
2419 Ꮪ Bell Blvd, Cedar Park,
TX 78613, Unitwd Ⴝtates
+12543183528
Bookmarks
Bookmarks
21 Aug 25 at 6:46 pm
This is a topic that is close to my heart… Take care!
Where are your contact details though?
Pink Salt Quick Recipe
21 Aug 25 at 6:48 pm