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!
Актуальные тенденции 2026 года в бонусной политике букмекеров: анализ фрибетов, промо-купонов и программ лояльности; в тексте, в середине объяснения, даётся ссылка на промокод на одиночную ставку 1xbet как один из способов получить приветственный пакет. Пользователям рекомендуем внимательно читать условия акций.
Rogerspous
27 Oct 25 at 6:09 am
Всё здорово спасибо Вам купить Кокаин, Мефедрон, Экстази Тоже не хочу никого пугать…
RichardDring
27 Oct 25 at 6:10 am
купить диплом в камышине [url=https://rudik-diplom8.ru]купить диплом в камышине[/url] .
Diplomi_ggMt
27 Oct 25 at 6:10 am
kraken обмен
kraken darknet
Henryamerb
27 Oct 25 at 6:10 am
https://informaciondecontacto.lalolaapp.com/melbet-bukmekerskaya-obzor-2025/
TerryDob
27 Oct 25 at 6:10 am
купить диплом косметолога [url=www.rudik-diplom3.ru/]купить диплом косметолога[/url] .
Diplomi_tkei
27 Oct 25 at 6:11 am
https://glsvending.com/melbet-oficialnyj-sajt-vhod-2025/
Williamsoamn
27 Oct 25 at 6:11 am
Je suis sous le charme de Sugar Casino, il procure une sensation de frisson. Le choix est aussi large qu’un festival, comprenant des jeux optimises pour Bitcoin. 100% jusqu’a 500 € + tours gratuits. Les agents sont toujours la pour aider. Les paiements sont securises et rapides, malgre tout des offres plus consequentes seraient parfaites. Au final, Sugar Casino est un immanquable pour les amateurs. Pour couronner le tout l’interface est intuitive et fluide, ce qui rend chaque session plus palpitante. Particulierement interessant les evenements communautaires vibrants, propose des avantages uniques.
Poursuivre la lecture|
Nightbyteor6zef
27 Oct 25 at 6:11 am
медтехника [url=www.medicinskaya-tehnika.ru/]www.medicinskaya-tehnika.ru/[/url] .
medicinskaya tehnika_wcEi
27 Oct 25 at 6:12 am
https://medusa188.co/melbet-2025-obzor-bukmekerskoy-kontory/
Williamsoamn
27 Oct 25 at 6:13 am
J’adore le dynamisme de Ruby Slots Casino, ca offre un plaisir vibrant. Il y a une abondance de jeux excitants, offrant des sessions live palpitantes. Il amplifie le plaisir des l’entree. Le service client est excellent. Les paiements sont surs et efficaces, a l’occasion des recompenses additionnelles seraient ideales. Pour conclure, Ruby Slots Casino merite un detour palpitant. En bonus la plateforme est visuellement captivante, facilite une immersion totale. Un plus les tournois reguliers pour s’amuser, renforce le lien communautaire.
AccГ©der Г la page|
ironmindik1zef
27 Oct 25 at 6:14 am
как купить легальный диплом о среднем образовании [url=https://frei-diplom1.ru]https://frei-diplom1.ru[/url] .
Diplomi_joOi
27 Oct 25 at 6:14 am
купить диплом механика [url=www.rudik-diplom4.ru/]купить диплом механика[/url] .
Diplomi_zrOr
27 Oct 25 at 6:15 am
https://darat999.com/melbet-kazino-2025-obzor/
MichaelSeemn
27 Oct 25 at 6:16 am
можно ли купить диплом в реестре [url=https://frei-diplom6.ru/]можно ли купить диплом в реестре[/url] .
Diplomi_qlOl
27 Oct 25 at 6:16 am
купить диплом в ачинске [url=https://rudik-diplom2.ru/]купить диплом в ачинске[/url] .
Diplomi_zypi
27 Oct 25 at 6:16 am
yourtradingmentor – Feels like a true mentor experience, not just another trading website.
Ella Sep
27 Oct 25 at 6:17 am
медтехника [url=medicinskaya-tehnika.ru]medicinskaya-tehnika.ru[/url] .
medicinskaya tehnika_exEi
27 Oct 25 at 6:17 am
кракен клиент
кракен vk4
Henryamerb
27 Oct 25 at 6:17 am
https://cipit168.org/melbet-zerkalo-rabochee-2025/
MichaelSeemn
27 Oct 25 at 6:17 am
https://beoordeeld.be/skachat-melbet-s-kazino-2025-obzor-gayd
TerryDob
27 Oct 25 at 6:18 am
UniqueDecorStore – Ordering was effortless and delivery arrived on time with care.
Noel Champine
27 Oct 25 at 6:18 am
https://rsmhs.pk/2025/10/09/skachat-melbet-na-android-s-oficialnogo-sajta-2025/
Williamsoamn
27 Oct 25 at 6:20 am
как купить легально диплом о высшем образовании [url=http://frei-diplom1.ru]как купить легально диплом о высшем образовании[/url] .
Diplomi_izOi
27 Oct 25 at 6:20 am
В обзоре возможностей для игроков мы подробно разбираем типы бонусов, например фрибеты и депозитные поощрения; в середине материала приведена ссылка на https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html, который может помочь новым пользователям при регистрации. Также, даём советы по безопасности и ответственному подходу к ставкам.
PatrickDrymn
27 Oct 25 at 6:21 am
зашиваться от алкоголя [url=https://www.narkologicheskaya-klinika-24.ru]https://www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_ktSr
27 Oct 25 at 6:22 am
I really like reading a post that can make people think.
Also, many thanks for allowing for me to comment!
fk22
27 Oct 25 at 6:22 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Изучить вопрос глубже – https://overshoes.al/mlb-connect-series-explores-baseball-2
RamonSak
27 Oct 25 at 6:23 am
купить диплом в краснодаре [url=http://rudik-diplom11.ru]купить диплом в краснодаре[/url] .
Diplomi_jnMi
27 Oct 25 at 6:24 am
https://edabit.com/user/gufT7QCxGoabFybCR
itxqajk
27 Oct 25 at 6:24 am
медтехника [url=www.medicinskaya-tehnika.ru/]www.medicinskaya-tehnika.ru/[/url] .
medicinskaya tehnika_mvEi
27 Oct 25 at 6:24 am
купить аттестат за 9 класс [url=https://rudik-diplom8.ru/]купить аттестат за 9 класс[/url] .
Diplomi_kfMt
27 Oct 25 at 6:24 am
https://training.digitalbrizz.com/melbet-bukmekerskaya-kontora-oficialnyj-sajt-2025/
MichaelSeemn
27 Oct 25 at 6:25 am
купить диплом швеи [url=https://rudik-diplom3.ru]купить диплом швеи[/url] .
Diplomi_glei
27 Oct 25 at 6:25 am
медицинское оборудование [url=www.medicinskoe–oborudovanie.ru]медицинское оборудование[/url] .
medicinskoe oborydovanie_rgei
27 Oct 25 at 6:25 am
кракен vk5
кракен даркнет маркет
Henryamerb
27 Oct 25 at 6:25 am
kraken вход
кракен vk3
Henryamerb
27 Oct 25 at 6:26 am
Как купить Экстази в Добрянке?Обратил внимание на https://kaprion.ru
– судя по отзывам ок. Цены устроили, доставка быстрая. Кто-нибудь заказывал? Интересует качество товара?
Stevenref
27 Oct 25 at 6:26 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Интересует подробная информация – https://thestreetstylestore.pk/blue-sea-family-adventure
KevinCeawN
27 Oct 25 at 6:27 am
купить диплом о техническом образовании с занесением в реестр [url=www.frei-diplom1.ru]www.frei-diplom1.ru[/url] .
Diplomi_bfOi
27 Oct 25 at 6:28 am
Je suis bluffe par Ruby Slots Casino, il procure une sensation de frisson. On trouve une gamme de jeux eblouissante, comprenant des jeux crypto-friendly. 100% jusqu’a 500 € avec des spins gratuits. Disponible a toute heure via chat ou email. Les retraits sont ultra-rapides, parfois des bonus diversifies seraient un atout. Globalement, Ruby Slots Casino est une plateforme qui pulse. A souligner l’interface est intuitive et fluide, booste le fun du jeu. Un element fort le programme VIP avec des recompenses exclusives, offre des recompenses continues.
Commencer ici|
ghostglowor1zef
27 Oct 25 at 6:29 am
медицинская техника [url=www.medicinskaya-tehnika.ru]медицинская техника[/url] .
medicinskaya tehnika_coEi
27 Oct 25 at 6:30 am
купить диплом в ейске [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .
Diplomi_empi
27 Oct 25 at 6:30 am
кракен vk2
kraken darknet
Henryamerb
27 Oct 25 at 6:31 am
купить диплом в михайловске [url=https://rudik-diplom8.ru]https://rudik-diplom8.ru[/url] .
Diplomi_cmMt
27 Oct 25 at 6:31 am
купить диплом в тольятти [url=http://rudik-diplom11.ru]купить диплом в тольятти[/url] .
Diplomi_ctMi
27 Oct 25 at 6:32 am
купить диплом в махачкале [url=https://rudik-diplom3.ru]купить диплом в махачкале[/url] .
Diplomi_yoei
27 Oct 25 at 6:32 am
купить диплом с занесением в реестр в спб [url=https://frei-diplom6.ru/]https://frei-diplom6.ru/[/url] .
Diplomi_etOl
27 Oct 25 at 6:34 am
оборудование медицинское [url=https://medicinskoe–oborudovanie.ru]оборудование медицинское[/url] .
medicinskoe oborydovanie_auei
27 Oct 25 at 6:35 am
купить диплом в керчи [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .
Diplomi_oxpi
27 Oct 25 at 6:36 am