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://www.rudik-diplom4.ru]купить диплом психолога[/url] .
Diplomi_zmOr
21 Oct 25 at 9:38 am
лучшие сервисы виртуальных номеров
Jaredvaf
21 Oct 25 at 9:39 am
http://rysowanie.phorum.pl/viewtopic.php?p=454254#454254
http://rysowanie.phorum.pl/viewtopic.php?p=454254#454254
21 Oct 25 at 9:39 am
Прием СМС
Jaredvaf
21 Oct 25 at 9:41 am
http://www.bonte-design.com/bbs/board.php?bo_table=free&wr_id=1513969
http://www.bonte-design.com/bbs/board.php?bo_table=free&wr_id=1513969
21 Oct 25 at 9:43 am
топ диджитал агентств россии [url=https://luchshie-digital-agencstva.ru/]топ диджитал агентств россии[/url] .
lychshie digital agentstva_mdoi
21 Oct 25 at 9:43 am
компания по продвижению сайтов [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_unKt
21 Oct 25 at 9:43 am
kraken marketplace
кракен маркетплейс
JamesDaync
21 Oct 25 at 9:43 am
диплом педагогического колледжа купить [url=www.frei-diplom12.ru]www.frei-diplom12.ru[/url] .
Diplomi_mhPt
21 Oct 25 at 9:44 am
виртуальный номер для подтверждения аккаунта
Antoniooscig
21 Oct 25 at 9:44 am
куплю диплом цена [url=https://www.rudik-diplom10.ru]куплю диплом цена[/url] .
Diplomi_pbSa
21 Oct 25 at 9:45 am
виртуальный номер для Facebook
Antoniomerty
21 Oct 25 at 9:46 am
топ сео компаний [url=www.reiting-seo-kompaniy.ru]топ сео компаний[/url] .
reiting seo kompanii_cqon
21 Oct 25 at 9:46 am
виртуальный номер для двухфакторной аутентификации
Antoniooscig
21 Oct 25 at 9:46 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Ознакомиться с полной информацией – https://www.kanoonsadat.ir/1398/10/14/chalesh-javanan-shahidsolimani
PeterDrell
21 Oct 25 at 9:48 am
pin up yuklash android [url=https://www.pinup5007.ru]https://www.pinup5007.ru[/url]
pin_up_uz_dtsr
21 Oct 25 at 9:48 am
купить диплом с реестром киев [url=http://www.frei-diplom4.ru]http://www.frei-diplom4.ru[/url] .
Diplomi_xyOl
21 Oct 25 at 9:48 am
купить диплом техникума или вуза [url=www.frei-diplom10.ru]купить диплом техникума или вуза[/url] .
Diplomi_ddEa
21 Oct 25 at 9:49 am
купить диплом в кузнецке [url=www.rudik-diplom3.ru]www.rudik-diplom3.ru[/url] .
Diplomi_ygei
21 Oct 25 at 9:49 am
Hello there! This is my first visit to your blog!
We are a team of volunteers and starting a new project
in a community in the same niche. Your blog provided us useful information to work on. You have done a wonderful job!
бестчендж
21 Oct 25 at 9:50 am
Промокод 1xBet на сегодня. Промокод на 2026-2026. На официальном сайте букмекерской конторы 1xBet появилась опция, которая позволяет “бесплатно” ознакомиться с функционалом сайта и при удачном стечении обстоятельств еще и выиграть некую сумму денежных средств. Теперь это стало доступно по специальному промокоду 1хБет. Он дает возможность получить до 32500? (100$). Актуальные промокоды 1xBet на сегодня. Рабочие промокоды 1xBet в 2026 Все промокоды для 1хБет бесплатно: при регистрации, на ставку (купон), на бонус, на сегодня. 1xBet — одна из самых известных компаний в сфере беттинга. Свою популярность контора заработала во многом благодаря большому количеству специальных предложений. Так, к примеру, каждый пользователь может воспользоваться одним из действующих промокодов 1xBet на сегодня бесплатно. Ознакомиться с их полным перечнем можно в данной статье.
Stanleyvonna
21 Oct 25 at 9:50 am
kraken tor
кракен vk2
JamesDaync
21 Oct 25 at 9:51 am
seo agencies list [url=http://www.reiting-seo-kompaniy.ru]http://www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_wron
21 Oct 25 at 9:51 am
https://coub.com/e14a00518396ebf696b0
VictorChash
21 Oct 25 at 9:53 am
аренда виртуального номера
Jaredvaf
21 Oct 25 at 9:54 am
раскрутка сайтов москва [url=https://reiting-seo-agentstv-moskvy.ru/]раскрутка сайтов москва[/url] .
reiting seo agentstv moskvi_euMl
21 Oct 25 at 9:54 am
Profitez d’une offre 1xBet : beneficiez un bonus de 100% pour l’inscription jusqu’a 130€. Renforcez votre solde facilement en placant des paris avec un multiplicateur de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Pour activer ce code, rechargez votre compte a partir de 1€. Decouvrez cette offre exclusive sur ce lien — 1xbet Code Bonus Sans Depot. Le code promo 1xBet aujourd’hui est disponible pour les joueurs du Cameroun, du Senegal et de la Cote d’Ivoire. Avec le 1xBet code promo bonus, obtenez jusqu’a 130€ de bonus promotionnel du code 1xBet. Ne manquez pas le dernier code promo 1xBet 2026 pour les paris sportifs et les jeux de casino.
Marvinspaft
21 Oct 25 at 9:55 am
I was suggested this website by my cousin. I am not
sure whether this post is written by him as nobody else know such detailed about my problem.
You are wonderful! Thanks!
geek bar vs lost vape
21 Oct 25 at 9:56 am
seo раскрутка продвижение [url=https://reiting-runeta-seo.ru/]seo раскрутка продвижение[/url] .
reiting ryneta seo_ajma
21 Oct 25 at 9:56 am
https://bresdel.com/blogs/1239663/1xBet-Bangladesh-Free-Bet-Promo-Code-2026-100-13000
https://bresdel.com/blogs/1239663/1xBet-Bangladesh-Free-Bet-Promo-Code-2026-100-13000
21 Oct 25 at 9:56 am
купить диплом в невинномысске [url=http://rudik-diplom10.ru/]купить диплом в невинномысске[/url] .
Diplomi_bmSa
21 Oct 25 at 9:57 am
pin up mobil ilova [url=https://www.pinup5007.ru]https://www.pinup5007.ru[/url]
pin_up_uz_pjsr
21 Oct 25 at 9:57 am
The Supreme Court agreed Monday to decide if the federal government may bar certain drug users from owning guns or if the law violates the Second Amendment, taking up a second significant guns case of its current term.
[url=https://kra-42cc.net]kra42[/url]
The appeal represents a rare circumstance in which the Trump administration is defending a gun prohibition, which it described in briefing at the Supreme Court as a “narrow” limitation on one of “Americans’ most cherished freedoms.”
[url=https://kra—42–at.ru]kra42 at[/url]
The case centers on Ali Danial Hemani, a dual citizen of the United States and Pakistan, who was indicted in 2023 on a single count of violating the guns-and-drugs law after the FBI found a 9mm pistol, 60 grams of marijuana, and 4.7 grams of cocaine at his family home. This prosecution, the government told the high court, rested Hemani’s habitual use of marijuana.
The court will likely hear arguments in the Hemani case next year and hand down a decision by the end of June.
kra42 сс
https://kra-42—at.ru
A federal district court dismissed the charge, noting a landmark decision from the Supreme Court in 2022 that made it easier for Americans to carry handguns in public and also required similar gun prohibitions to have a connection to history.
But just how closely analogous prosecutors must come to a historic law has been a matter of debate. Last year, for instance, the Supreme Court upheld a federal law that bars guns for Americans who are the subject of certain domestic abuse restraining orders, rejecting an argument pressed by gun rights groups that the prohibition violated the Second Amendment.
The conservative 5th US Circuit Court of Appeals upheld that decision, holding in a brief decision that the historical record points only to laws that barred guns for Americans who are actively intoxicated or under the influence of drugs at the time of their arrest. The government, the court ruled, could not target habitual users.
The Trump administration appealed that decision.
KevinWal
21 Oct 25 at 9:57 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Интересует подробная информация – https://www.luke-hardisty.co.uk/blog_4-2
JamesHipsy
21 Oct 25 at 9:57 am
аренда виртуального номера
Timothydrart
21 Oct 25 at 9:58 am
Hi, Neat post. There is a problem together with your
website in web explorer, could test this? IE
still is the market chief and a huge section of folks will
leave out your great writing because of this problem.
https://11uu.ru.com/
21 Oct 25 at 9:58 am
купить диплом в курске [url=http://www.rudik-diplom11.ru]купить диплом в курске[/url] .
Diplomi_plMi
21 Oct 25 at 9:59 am
я купил диплом с проводкой [url=frei-diplom5.ru]я купил диплом с проводкой[/url] .
Diplomi_vyPa
21 Oct 25 at 9:59 am
купить виртуальный номер для СМС
Antoniooscig
21 Oct 25 at 9:59 am
купить диплом с занесением в реестр челябинск [url=www.frei-diplom4.ru]купить диплом с занесением в реестр челябинск[/url] .
Diplomi_ssOl
21 Oct 25 at 9:59 am
кракен сайт
kraken vpn
JamesDaync
21 Oct 25 at 10:00 am
купить диплом в белово [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .
Diplomi_vkei
21 Oct 25 at 10:01 am
купить диплом техникум [url=http://frei-diplom10.ru]купить диплом техникум[/url] .
Diplomi_uuEa
21 Oct 25 at 10:01 am
виртуальный номер для Instagram
Antoniomerty
21 Oct 25 at 10:02 am
медсестра которая купила диплом врача [url=http://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_uykt
21 Oct 25 at 10:03 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Есть чему поучиться – https://iyashinosato.cm/?page_id=17
Jesusheigh
21 Oct 25 at 10:03 am
Бесплатные промокоды. Давайте сразу начну с того, что перечислю несколько актуальных Промокодов 1xBet на сегодня. Смело вводите промокод в соответствующее поле и получайте прикольные «плюшки» в подарок от щедрого букмекера! Букмекерская контора 1xBet отличается от конкурентов наличием широкой программы лояльности. Важной ее частью является предоставление клиентам бонусов при вводе промокода. 1xbet casino промокод. В системе действует программа приветственных бонусов, благодаря которой каждый новичок получает определённую сумму за регистрацию на сайте. Такие акции действуют для казино и букмекерской конторы. Чтобы принять участие в приветственной программе, достаточно активировать при регистрации любой рабочий промокод.
Stanleyvonna
21 Oct 25 at 10:04 am
Offre promotionnelle 1xBet pour 2026 : profitez d’un bonus de bienvenue de 100% jusqu’a 130€ en vous inscrivant des maintenant. Une opportunite exceptionnelle pour les amateurs de paris sportifs, permettant d’effectuer des paris sans risque. Inscrivez-vous avant la fin de l’annee 2026. Le lien ci-dessous vous menera vers le code promo officiel 1xBet — Code Promo 1xbet Pour L’inscription. 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.
Marvinspaft
21 Oct 25 at 10:05 am
Бонусы также отличаются по формату. Некоторые из них предоставляются новичкам. При регистрации на 1xBet, введите промокод и заберите 100% приветственный бонус до 32500 рублей.Компания 1xBet даёт возможность пользователям ставить и выигрывать с использованием акционных предложений. Это увеличивает вовлечённость к игровому процессу и гарантирует надежность игры.Актуальный промокод можно получить по этой ссылке — http://www.medtronik.ru/images/pages/1hbet_2021_promokod_pri_registracii.html.
Jasonbrado
21 Oct 25 at 10:06 am
кракен маркетплейс
кракен маркетплейс
JamesDaync
21 Oct 25 at 10:06 am