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 РФ
кракен даркнет
JamesDaync
22 Oct 25 at 10:12 am
Snagged some $MTAUR during stage 1; the price hike to next phase motivates quick action. Loving the hyper-casual vibe with blockchain perks. Early adopters win here.
minotaurus coin
WilliamPargy
22 Oct 25 at 10:12 am
1xBet промокод 2025 узнайте, какие акции и специальные предложения доступны в новом сезоне
Aaronawads
22 Oct 25 at 10:13 am
купить диплом в кирове [url=https://rudik-diplom1.ru/]купить диплом в кирове[/url] .
Diplomi_kker
22 Oct 25 at 10:14 am
В обзорной статье вы найдете собрание важных фактов и аналитики по самым разнообразным темам. Мы рассматриваем как современные исследования, так и исторические контексты, чтобы вы могли получить полное представление о предмете. Погрузитесь в мир знаний и сделайте шаг к пониманию!
Практические советы ждут тебя – https://jabirjalali.com/think-positive
GeorgePonry
22 Oct 25 at 10:15 am
купить диплом с занесением в реестр челябинск [url=www.frei-diplom3.ru]купить диплом с занесением в реестр челябинск[/url] .
Diplomi_ihKt
22 Oct 25 at 10:15 am
технический перевод в машиностроении [url=www.dzen.ru/a/aPFFa3ZMdGVq1wVQ]www.dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_ciml
22 Oct 25 at 10:15 am
топ сео компаний [url=http://top-10-seo-prodvizhenie.ru]топ сео компаний[/url] .
top 10 seo prodvijenie_fmKa
22 Oct 25 at 10:16 am
Пользователи Мотор Казино получают
надежную защиту данных, быстрые выплаты и круглосуточную поддержку.
мотор
22 Oct 25 at 10:16 am
Где купить Кокс в Советске?Обратите внимание – сайт https://ankortrip.ru
. Цены порадовали, доставку обещают. Кто-нибудь пробовал у них? Как с качеством?
Stevenref
22 Oct 25 at 10:18 am
научно технический перевод [url=teletype.in/@alexd78/HN462R01hzy]teletype.in/@alexd78/HN462R01hzy[/url] .
Vidi perevodov v buro Perevod i Pravo_gcst
22 Oct 25 at 10:18 am
seo продвижение сайта компании москва [url=www.seo-prodvizhenie-reiting-kompanij.ru]www.seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_jest
22 Oct 25 at 10:19 am
топ сео компаний [url=https://top-10-seo-prodvizhenie.ru/]топ сео компаний[/url] .
top 10 seo prodvijenie_nsKa
22 Oct 25 at 10:20 am
e9pt4e
📁 🎁 Bitcoin Offer - 0.25 BTC reserved. Get now > https://graph.org/Get-your-BTC-09-04?hs=7255fc1a3bb72291f146f9661674a5a8& 📁
22 Oct 25 at 10:20 am
купить диплом в белово [url=https://www.rudik-diplom8.ru]https://www.rudik-diplom8.ru[/url] .
Diplomi_gbMt
22 Oct 25 at 10:22 am
easyprt.xyz – Already bookmarked it, definitely a site I’ll be visiting again soon.
Lillian Henjes
22 Oct 25 at 10:22 am
kraken vk4
kraken vk5
JamesDaync
22 Oct 25 at 10:23 am
купить диплом о высшем образовании с занесением в реестр владивосток [url=frei-diplom3.ru]frei-diplom3.ru[/url] .
Diplomi_faKt
22 Oct 25 at 10:25 am
https://sdelaydom-sam.ru/wp-content/articles/kak_podgotovity_vloghenie_dlya_adaptacii_cherdaka.html
Robertoxync
22 Oct 25 at 10:25 am
Valuable information. Fortunate me I discovered your web site by chance, and I’m shocked
why this coincidence didn’t came about in advance! I bookmarked it.
https://gacoor.slot.sbs/
Betting News
22 Oct 25 at 10:26 am
сео оптимизация москва [url=https://seo-prodvizhenie-reiting-kompanij.ru/]https://seo-prodvizhenie-reiting-kompanij.ru/[/url] .
seo prodvijenie reiting kompanii_wast
22 Oct 25 at 10:26 am
научно технический перевод английский [url=teletype.in/@alexd78/HN462R01hzy]teletype.in/@alexd78/HN462R01hzy[/url] .
Vidi perevodov v buro Perevod i Pravo_inst
22 Oct 25 at 10:28 am
Основу выварить не удалось, после вручения посыля,забыл убрать с глаз, торопился, дома было объявлено военное положение .
https://dokuchaevskrm.ru
Ребят вообще на высоте!!!)Удачи вам всех благ!!! ВСЕХ С ПРАЗДНИКОМ!!!Всего самого самого наилучшего!)
Donaldmoire
22 Oct 25 at 10:29 am
Thanks for your marvelous posting! I genuinely enjoyed reading
it, you will be a great author.I will be sure to bookmark your blog and definitely will come back
very soon. I want to encourage that you continue your great work, have a nice holiday weekend!
ローター
22 Oct 25 at 10:30 am
profesionales seo [url=http://top-10-seo-prodvizhenie.ru/]profesionales seo[/url] .
top 10 seo prodvijenie_iuKa
22 Oct 25 at 10:30 am
кракен android
кракен 2025
JamesDaync
22 Oct 25 at 10:32 am
Saya sangat menikmati artikel ini! Pembahasan tentang KUBET, Situs Judi Bola Terlengkap, dan Situs Mix Parlay sangat informatif dan penuh wawasan. Selain itu, topik seperti Situs Parlay Gacor dan Situs Parlay Resmi juga dibahas dengan cara yang
menarik. Tambahan seperti kubet login, toto macau, dan situs parlay membuat tulisan ini semakin komprehensif dan mudah dicerna.
site
22 Oct 25 at 10:36 am
купить диплом в ессентуках [url=https://rudik-diplom2.ru/]купить диплом в ессентуках[/url] .
Diplomi_ospi
22 Oct 25 at 10:37 am
https://www.bcpost.com/newsr/15801
Jamiecat
22 Oct 25 at 10:37 am
Le code promo est supprime : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, a utiliser dans les paris sportifs. Vous pouvez vous inscrire sur le site 1xBet ou via l’application mobile. Apres votre premier depot, vous activerez le code bonus. L’offre est valable pour toute l’annee 2026, et le bonus doit etre mise dans les 30 jours. Decouvrez plus d’informations sur le code promo via ce lien — https://www.lamarinda.it/wp-content/pgs/tufli_oseny_2015.html.
Marvinspaft
22 Oct 25 at 10:38 am
купить диплом о среднем специальном образовании цена [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_rnea
22 Oct 25 at 10:38 am
купить проведенный диплом моих [url=http://www.frei-diplom1.ru]купить проведенный диплом моих[/url] .
Diplomi_zzOi
22 Oct 25 at 10:39 am
старые дипломы купить [url=http://rudik-diplom8.ru]старые дипломы купить[/url] .
Diplomi_ipMt
22 Oct 25 at 10:40 am
медицинский перевод на английский [url=http://www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16]http://www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .
Medicinskii perevod_hkEr
22 Oct 25 at 10:40 am
Just swapped some ETH for $MTAUR in the presale; the process was seamless on multiple chains. The in-game currency conversion gives real edge in play. This could rival Subway Surfers with crypto flair.
mtaur coin
WilliamPargy
22 Oct 25 at 10:41 am
kraken darknet
кракен маркетплейс
JamesDaync
22 Oct 25 at 10:41 am
top seo expert [url=https://www.top-10-seo-prodvizhenie.ru]https://www.top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_hcKa
22 Oct 25 at 10:41 am
технический перевод требования [url=dzen.ru/a/aPFFa3ZMdGVq1wVQ]dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_vmml
22 Oct 25 at 10:43 am
где купить диплом с занесением реестр [url=http://frei-diplom3.ru]где купить диплом с занесением реестр[/url] .
Diplomi_fvKt
22 Oct 25 at 10:43 am
купить диплом физика [url=rudik-diplom12.ru]купить диплом физика[/url] .
Diplomi_oiPi
22 Oct 25 at 10:43 am
Wonderful post but I was wanting to know if you could write a litte more on this
topic? I’d be very grateful if you could elaborate a little
bit further. Cheers!
adameve promo
22 Oct 25 at 10:44 am
Для вывода свыше 1000 долларов необходимо представить отсканированный документ, подтверждающий личность.
азино 777 рабочее зеркало
22 Oct 25 at 10:44 am
заказать сео москва [url=http://seo-prodvizhenie-reiting-kompanij.ru]http://seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_fust
22 Oct 25 at 10:44 am
rodarodaku.xyz – Overall impression is very positive, blog feels genuine and well built.
Adrian Philips
22 Oct 25 at 10:44 am
диплом о высшем образовании купить с занесением в реестр [url=http://www.frei-diplom1.ru]диплом о высшем образовании купить с занесением в реестр[/url] .
Diplomi_hxOi
22 Oct 25 at 10:47 am
Je trouve absolument brulant VBet Casino, c’est un casino en ligne qui jaillit comme un volcan en furie. Le repertoire du casino est un magma de divertissement, comprenant des jeux de casino adaptes aux cryptomonnaies. L’assistance du casino est chaleureuse et irreprochable, joignable par chat ou email. Les transactions du casino sont simples comme une braise, parfois plus de tours gratuits au casino ce serait volcanique. Pour resumer, VBet Casino est une pepite pour les fans de casino pour les passionnes de casinos en ligne ! De surcroit le site du casino est une merveille graphique ardente, ajoute une touche de feu au casino.
vbet retrait instantanГ©|
fizzyglitterlemur9zef
22 Oct 25 at 10:47 am
Отличный сервис, которым теперь пользуюсь постоянно. DRINKIO всегда доставляет вовремя, без ошибок и задержек. Курьеры приятные, общение вежливое. Ассортимент хороший, можно найти всё, что нужно. Удобно, что доставка доступна 24 часа в сутки. Круглосуточная доставка алкоголя в Москве: https://drinkio105.ru/
Arthurtok
22 Oct 25 at 10:48 am
Ich liebe die unbandige Kraft von Lowen Play Casino, es ist ein Online-Casino, das wie ein Lowe brullt. Der Katalog des Casinos ist ein Dschungel voller Nervenkitzel, inklusive stilvoller Casino-Tischspiele. Der Casino-Service ist zuverlassig und machtig, sorgt fur sofortigen Casino-Support, der beeindruckt. Der Casino-Prozess ist klar und ohne Fallen, manchmal wurde ich mir mehr Casino-Promos wunschen, die wie ein Feuer lodern. Alles in allem ist Lowen Play Casino eine Casino-Erfahrung, die wie ein Lowe glanzt fur Spieler, die auf wilde Casino-Kicks stehen! Nebenbei die Casino-Navigation ist kinderleicht wie eine Fahrte, Lust macht, immer wieder ins Casino zuruckzukehren.
lГ¶wen play casino no deposit bonus|
zappysquirrel3zef
22 Oct 25 at 10:49 am
где найти промокод для 1xBet узнайте надёжные источники получения действующих кодов и предложений
Aaronawads
22 Oct 25 at 10:49 am
Как купить Кокс в Верхняя Тойме?Всем привет, ищу проверенный магазин – присмотрел https://uzzpopk82.ru
. Цены нормальные, доставляют. Кто-нибудь пользовался их услугами? Насколько хороший товар?
Stevenref
22 Oct 25 at 10:50 am