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 darknet
kraken android
Henryamerb
27 Oct 25 at 12:11 am
Hi there to every body, it’s my first go to see of this weblog;
this weblog carries amazing and actually fine material designed for readers.
Here is my webpage – zinnat02
zinnat02
27 Oct 25 at 12:12 am
xbet giri? [url=www.1xbet-17.com/]xbet giri?[/url] .
1xbet_fnpl
27 Oct 25 at 12:12 am
Вызвать дезинфекция школы на дом, кто знает номер?
уничтожение тараканов с гарантией
KennethceM
27 Oct 25 at 12:15 am
оборудование медицинское [url=http://medicinskoe–oborudovanie.ru]оборудование медицинское[/url] .
medicinskoe oborydovanie_vmei
27 Oct 25 at 12:16 am
кракен android
кракен vk4
Henryamerb
27 Oct 25 at 12:17 am
клиника наркология [url=www.narkologicheskaya-klinika-23.ru/]www.narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_pket
27 Oct 25 at 12:17 am
Hi! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
tekun777
27 Oct 25 at 12:17 am
Visit https://cryptomonitor.info/ where you will find a free web application for tracking, screening and technical analysis of the cryptocurrency market. Cryptomonitor is the best tools for crypto traders that allow you to receive comprehensive information.
The site also presents all the latest news from the world of cryptocurrencies.
lajidighop
27 Oct 25 at 12:17 am
медтехника [url=medicinskaya-tehnika.ru]medicinskaya-tehnika.ru[/url] .
medicinskaya tehnika_dtEi
27 Oct 25 at 12:18 am
Купить диплом любого ВУЗа можем помочь. Купить диплом бакалавра – [url=http://diplomybox.com/diplom-bakalavra/]diplomybox.com/diplom-bakalavra[/url]
Cazrilm
27 Oct 25 at 12:18 am
A fascinating discussion is definitely worth comment.
I believe that you ought to publish more on this topic, it might not be
a taboo matter but generally folks don’t discuss such issues.
To the next! Many thanks!!
ankara kürtaj
27 Oct 25 at 12:19 am
1xbet yeni adresi [url=1xbet-17.com]1xbet yeni adresi[/url] .
1xbet_oapl
27 Oct 25 at 12:20 am
кракен vk5
кракен android
Henryamerb
27 Oct 25 at 12:23 am
you can try businessdaily.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
you can try businessdaily.click
27 Oct 25 at 12:24 am
лечение зависимостей [url=https://narkologicheskaya-klinika-24.ru/]https://narkologicheskaya-klinika-24.ru/[/url] .
narkologicheskaya klinika_laSr
27 Oct 25 at 12:25 am
Срочно нужна дезинфекция после умерших, тараканы достали!
обработка от блох в доме
KennethceM
27 Oct 25 at 12:27 am
Hey there, I think your blog might be having browser compatibility issues. When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!
https://somersetent.co.uk/uncategorized/melbet-skachat-na-android-s-oficialnogo-sajta-2025/
Fobertsax
27 Oct 25 at 12:29 am
кракен ios
кракен 2025
Henryamerb
27 Oct 25 at 12:30 am
медицинская аппаратура [url=medicinskoe–oborudovanie.ru]медицинская аппаратура[/url] .
medicinskoe oborydovanie_fhei
27 Oct 25 at 12:31 am
https://www.affilorama.com/member/kalmelakna
StevenAdalo
27 Oct 25 at 12:31 am
kraken зеркало
kraken client
Henryamerb
27 Oct 25 at 12:31 am
1xbet giri? 2025 [url=www.1xbet-17.com/]1xbet giri? 2025[/url] .
1xbet_tgpl
27 Oct 25 at 12:32 am
кракен даркнет
kraken darknet market
JamesDaync
27 Oct 25 at 12:35 am
Регистрация в 2026 году — подробно о бонусам и предложениям. Узнайте, как правильно активировать приветственные предложения, и в середине процесса обратите внимание на https://www.apelsin.su/wp-includes/articles/promokod_240.html как вариант получения дополнительного вознаграждения. Часто задаваемые вопросы помогут легко разобраться с верификацией и получением бонусов.
Rogerspous
27 Oct 25 at 12:35 am
наркологические клиники москва [url=www.narkologicheskaya-klinika-23.ru/]www.narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_vnet
27 Oct 25 at 12:41 am
купить диплом в новосибирске [url=https://www.rudik-diplom15.ru]купить диплом в новосибирске[/url] .
Diplomi_vfPi
27 Oct 25 at 12:41 am
медтехника [url=www.medicinskaya-tehnika.ru/]www.medicinskaya-tehnika.ru/[/url] .
medicinskaya tehnika_xkEi
27 Oct 25 at 12:41 am
кракен онион
кракен android
Henryamerb
27 Oct 25 at 12:41 am
Лучшая обработка офиса от тараканов в районе, мастера профи.
санитарная обработка
KennethceM
27 Oct 25 at 12:43 am
Цены на выведение тараканов выросли? Обсудим.
травля тараканов
KennethceM
27 Oct 25 at 12:44 am
наркологический центр москва [url=http://narkologicheskaya-klinika-23.ru/]http://narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_hlet
27 Oct 25 at 12:45 am
Code promo sur 1xBet est unique et permet a chaque nouveau joueur de beneficier jusqu’a 100€ de bonus sportif a hauteur de 100% en 2026. Ce bonus est credite sur votre solde de jeu en fonction du montant de votre premier depot, le depot minimum etant fixe a 1€. Pour eviter toute perte de bonus, veillez a copier soigneusement le code depuis la source et a le saisir dans le champ « code promo (si disponible) » lors de l’inscription, afin de preserver l’integrite de la combinaison. Le bonus de bienvenue n’est pas la seule promotion ou vous pouvez utiliser un code, d’autres combinaisons vous permettant d’obtenir des bonus supplementaires sont disponibles dans la section « Vitrine des codes promo ». Vous pouvez trouver le code promo 1xbet sur ce lien > https://www.atrium-patrimoine.com/wp-content/artcls/?code_promo_196.html.
ThomasChiff
27 Oct 25 at 12:45 am
1xbet mobil giri? [url=www.1xbet-17.com/]1xbet mobil giri?[/url] .
1xbet_fipl
27 Oct 25 at 12:46 am
оборудование медицинское [url=http://medicinskoe–oborudovanie.ru/]оборудование медицинское[/url] .
medicinskoe oborydovanie_fhei
27 Oct 25 at 12:46 am
ordinare Viagra generico in modo sicuro: trattamento ED online Italia – farmaci per potenza maschile
RandySkync
27 Oct 25 at 12:47 am
Marvelous, what a web site it is! This website gives valuable data to us, keep
it up.
buôn bán nội tạng
27 Oct 25 at 12:47 am
больница наркологическая [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_gvSr
27 Oct 25 at 12:48 am
кракен vk5
kraken 2025
Henryamerb
27 Oct 25 at 12:49 am
kraken market
кракен android
Henryamerb
27 Oct 25 at 12:50 am
Hi there! This is my first visit to your blog! We are a group
of volunteers and starting a new initiative in a community in the same
niche. Your blog provided us beneficial information to work on. You
have done a extraordinary job!
Modular Sectional
27 Oct 25 at 12:51 am
Code promo 1xBet pour 2026 : recevez une offre de 100% jusqu’a 130€ en vous inscrivant des maintenant. Une opportunite exceptionnelle pour les amateurs de paris sportifs, incluant des paris gratuits. N’attendez pas la fin de l’annee 2026 pour profiter de cette offre. Vous pouvez retrouver le code promo 1xBet sur ce lien > 1xbet Nouveau Code Promo. Le code promo 1xBet vous permet d’activer un bonus d’inscription 1xBet exclusif et de commencer a parier avec un avantage. Le code promotionnel 1xBet 2026 est valable pour les paris sportifs, le casino en ligne et les tours gratuits. Decouvrez des aujourd’hui le meilleur code promo 1xBet et profitez du bonus de bienvenue 1xBet sans depot initial.
ThomasChiff
27 Oct 25 at 12:52 am
наркологические диспансеры москвы [url=https://narkologicheskaya-klinika-23.ru/]narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_nmet
27 Oct 25 at 12:54 am
Ищу обработка участков от клещей с выездом в область.
дезинфекция помещений
KennethceM
27 Oct 25 at 12:54 am
кракен обмен
кракен vk3
Henryamerb
27 Oct 25 at 12:54 am
купить диплом в сарапуле [url=www.rudik-diplom15.ru/]купить диплом в сарапуле[/url] .
Diplomi_ibPi
27 Oct 25 at 12:55 am
Please let me know if you’re looking for a writer for your site.
You have some really good posts and I believe I would be a good asset.
If you ever want to take some of the load off, I’d really like to write some content for your blog in exchange for a link back to
mine. Please send me an email if interested.
Kudos!
webpage
27 Oct 25 at 12:56 am
бро а какая почта то ? купить кокаин, меф, бошки через телеграмм магазин хороший, спору нет, вот только уж оооочень он не расторопны. и ответ приходится ждать так же долго…
RichardDring
27 Oct 25 at 12:56 am
1xbet [url=http://www.1xbet-17.com]1xbet[/url] .
1xbet_gspl
27 Oct 25 at 12:57 am
кракен android
kraken android
Henryamerb
27 Oct 25 at 1:00 am