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!
Excellent post. I was checking constantly this blog and I’m inspired!
Very helpful information specially the ultimate part 🙂 I care for such
information much. I was looking for this particular information for
a very long time. Thanks and good luck.
سامانه جامع آموزش الکترونیک دانشگاه پیام نور edu.pnu.ac.ir
31 Jul 25 at 1:44 am
https://mexicarerxhub.shop/# mexican border pharmacies shipping to usa
Jessegap
31 Jul 25 at 1:45 am
Hello! I could have sworn I’ve been to this site before but after reading
through some of the post I realized it’s new to me. Anyways, I’m
definitely happy I found it and I’ll be bookmarking and
checking back frequently! https://www.yourknownjobs.com/profile/chantecrumpton
шлюхи пермь
31 Jul 25 at 1:47 am
canadian medications [url=https://canadrxnexus.shop/#]CanadRx Nexus[/url] canadian drugs pharmacy
JamesCoaby
31 Jul 25 at 1:48 am
Надёжная капельница от запоя в стационаре в клинике Частный Медик?24 (Коломна) — полный курс лечения, узнайте больше.
Получить больше информации – [url=https://kapelnica-ot-zapoya-kolomna15.ru/]капельница от запоя в коломне[/url]
MatthewNouff
31 Jul 25 at 1:49 am
прогнозы экспертов на хоккей [url=www.luchshie-prognozy-na-khokkej6.ru]www.luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_mjMi
31 Jul 25 at 1:53 am
В Балашихе клиника Частный Медик 24 предлагает эффективный вывод из запоя в стационаре — подробности на сайте клиники.
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha13.ru/]вывод из запоя капельница город балашиха[/url]
DonaldGueni
31 Jul 25 at 1:57 am
IndiGenix Pharmacy: indian pharmacy paypal – legitimate online pharmacies india
Richardquaxy
31 Jul 25 at 1:57 am
Good day I am so excited I found your web site, I really found you by mistake, while I was researching on Digg for something else,
Nonetheless I am here now and would just like to say thanks for a
fantastic post and a all round exciting blog (I also love the theme/design),
I don’t have time to look over it all at the minute but I have bookmarked it and also added in your RSS feeds,
so when I have time I will be back to read a lot more, Please do keep up the superb b.
Also visit my blog :: goedkoopste internet Hongarije expats
goedkoopste internet Hongarije expats
31 Jul 25 at 1:58 am
кайт лагерь Страховка в кайтсерфинге: как избежать травм
Kennethvut
31 Jul 25 at 1:59 am
Mega darknet
RichardPep
31 Jul 25 at 1:59 am
I love what you guys are up too. This type of clever work and coverage!
Keep up the amazing works guys I’ve included you guys to blogroll.
Look into my homepage no contract internet Hungary
no contract internet Hungary
31 Jul 25 at 2:01 am
прогнозы на тоталы в хоккее [url=https://www.luchshie-prognozy-na-khokkej6.ru]https://www.luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_uxMi
31 Jul 25 at 2:02 am
прогнозы хоккей [url=www.luchshie-prognozy-na-khokkej6.ru/]www.luchshie-prognozy-na-khokkej6.ru/[/url] .
lychshie prognozi na hokkei_ncMi
31 Jul 25 at 2:05 am
What’s up to every one, the contents present at this site are in fact awesome for people experience, well, keep up the nice work
fellows.
Best Private University
31 Jul 25 at 2:05 am
1хБет промокод при регистрации используя промокод, вы получите бонус в размере 100% до 32500 рублей для ставок на спорт, а также бонус в казино 1500€ и 150 фриспинов. Обратите внимание, что это единственный действующий промокод на данный момент. Также, если вам интересны другие промокоды для 1xBet, вы можете ознакомиться со списком рабочих промокодов на 2025 год. https://monument-stone.ru/wp-includes/articles/promokod_309.html/
1xBet предлагает различные бонусные программы для своих игроков. Среди них есть бонус за регистрацию, бонус за первый депозит, бонус за повторный депозит, бонус за покупку билетов, бонус за пополнение счета, бонус за приглашение друзей и многое другое. Кроме того, игроки могут получать бонусы за активное участие в акциях и конкурсах, которые проводит букмекерская контора. Также игроки имеют возможность получать бонусы за достижение новых уровней в программе лояльности.
JohnnyWaf
31 Jul 25 at 2:05 am
Современные методы лечения при выводе из запоя включают как медикаментозную детоксикацию, так и психологическую реабилитацию. В Уфе наркологи используют капельничное введение лекарственных средств, которые помогают быстро вывести токсины, нормализовать обмен веществ и стабилизировать работу внутренних органов. Одновременно с этим проводится психологическая поддержка для снижения эмоционального стресса, связанного с запоем.
Получить дополнительную информацию – http://
Williamtathy
31 Jul 25 at 2:07 am
خلاصه کتاب کمدی الهی دوزخ اثر دانته آلیگیری، شاهکاری ادبی و فلسفی است که سفر
خیالی شاعر را به دوزخ روایت می کند.
این اثر سترگ، بخشی از کمدی الهی، به عنوان یکی از بزرگ
ترین آثار ادبیات جهان شناخته می شود و نمادی از سلوک
روحانی انسان در مواجهه با گناه و مجازات است.
دانته آلیگیری در این سفر، با همراهی
ویرژیل، راهنمای خود، از طبقات مختلف دوزخ عبور کرده
و گناهکاران و مجازات هایشان را مشاهده می کند، که هر یک درس هایی عمیق درباره اخلاقیات و عدالت الهی ارائه می دهند.
https://econbiz.ir/
https://econbiz.ir/
31 Jul 25 at 2:07 am
Wonderful beat ! I wish to apprentice even as you amend
your website, how could i subscribe for a blog website? The account helped me a
acceptable deal. I had been tiny bit familiar of this your broadcast provided brilliant clear idea
CorpaGenesis
31 Jul 25 at 2:11 am
услуги транспортировки автомобилей [url=www.avtovoz-av8.ru/]www.avtovoz-av8.ru/[/url] .
avtovoz_yfKt
31 Jul 25 at 2:12 am
обучение кайтсёрфингу Кайтсёрфинг – это вызов, который стоит принять.
Kennethvut
31 Jul 25 at 2:16 am
He uso marketingme.wiki desde hace meses y el
servicio es muy positiva. La oferta de juegos que tiene, tanto relacionadas al deporte como de casino, es variada, y el portal en todo
momento ofrece actualizaciones con buenas cuotas. Me gusta especialmente la opción de apuestas directas, que permite
apostar en tiempo real. También, la aplicación de Doradobet es ágil
y rápida, perfecta para acceder desde cualquier lugar.
El soporte también responde de forma útil cuando hay alguna duda.
En conclusión, aconsejo Doradobet a quienes desean un sitio seguro y completo para disfrutar del juego digital.
XO
31 Jul 25 at 2:18 am
В Ростове-На-Дону решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Раскрыть тему полностью – [url=https://vyvod-iz-zapoya-rostov11.ru/]вывод из запоя на дому[/url]
Gregorysunda
31 Jul 25 at 2:20 am
Pretty nice post. I just stumbled upon your blog and wished
to say that I’ve truly enjoyed surfing around your weblog posts.
After all I’ll be subscribing on your feed and I’m hoping you
write again soon!
schedule 35 mushrooms
31 Jul 25 at 2:22 am
прогнозы на спорт хоккей [url=www.luchshie-prognozy-na-khokkej6.ru]www.luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_zwMi
31 Jul 25 at 2:24 am
Воспользуйтесь капельницей от запоя в стационаре в Частном Медике?24 (Коломна) — подробнее по ссылке.
Подробнее тут – [url=https://kapelnica-ot-zapoya-kolomna11.ru/]капельница от запоя анонимно коломна[/url]
WallaceHot
31 Jul 25 at 2:26 am
кайт Разнообразие стилей кайтсёрфинга позволяет каждому найти что-то для себя. Фристайл, фрирайд, вейврайдинг – выберите то, что вам больше нравится, и совершенствуйте свои навыки.
Kennethvut
31 Jul 25 at 2:27 am
автоперевозка автомобилей по россии [url=http://avtovoz-av8.ru/]http://avtovoz-av8.ru/[/url] .
avtovoz_icKt
31 Jul 25 at 2:28 am
After testing several casino guides, I discovered the best review of Netbet Greece, highlighting why it’s truly the ultimate Greek online casino.
Check out this insightful analysis on Netbet Casino via the following link:
http://uzz.c1d.myftpupload.com/2025/07/casino-netbet-700/
Taheskix
31 Jul 25 at 2:30 am
Алкогольный запой — это не просто последствие длительного употребления спиртного, а состояние, которое может привести к необратимым последствиям без своевременного медицинского вмешательства. Длительная интоксикация вызывает нарушения в работе печени, сердца, почек, приводит к обезвоживанию, сбою электролитного баланса, а также провоцирует серьёзные психоэмоциональные изменения. Самостоятельный отказ от алкоголя может стать причиной опасных осложнений: судорог, гипертонических кризов, панических атак и даже алкогольного психоза.
Углубиться в тему – [url=https://vyvod-iz-zapoya-arkhangelsk6.ru/]наркология вывод из запоя в архангельске[/url]
CharlesRam
31 Jul 25 at 2:36 am
В таких случаях своевременное обращение за помощью позволяет быстро стабилизировать состояние и предотвратить развитие серьезных осложнений.
Ознакомиться с деталями – http://narcolog-na-dom-voronezh0.ru
ArthurVes
31 Jul 25 at 2:38 am
generic drugs mexican pharmacy: buy cialis from mexico – MexiCare Rx Hub
Richardbog
31 Jul 25 at 2:42 am
Wow, amazing weblog format! How long have you been blogging for?
you made blogging glance easy. The overall look of your website
is magnificent, let alone the content!
my web-site; internetdiensten in Hongarije
internetdiensten in Hongarije
31 Jul 25 at 2:43 am
MexiCare Rx Hub [url=https://mexicarerxhub.shop/#]modafinil mexico online[/url] MexiCare Rx Hub
JamesCoaby
31 Jul 25 at 2:44 am
Magnificent site. Lots of helpful information here.
I am sending it to a few pals ans also sharing in delicious.
And naturally, thank you in your effort!
My site Hungary internet providers
Hungary internet providers
31 Jul 25 at 2:44 am
прогнозы на хоккей с высокой проходимостью [url=www.luchshie-prognozy-na-khokkej6.ru/]www.luchshie-prognozy-na-khokkej6.ru/[/url] .
lychshie prognozi na hokkei_nkMi
31 Jul 25 at 2:48 am
I’m really enjoying the theme/design of your weblog.
Do you ever run into any internet browser compatibility issues?
A few of my blog visitors have complained about my website not working correctly in Explorer but looks great
in Chrome. Do you have any ideas to help fix this problem?
Feel free to surf to my blog … best Dutch-style internet Hungary
best Dutch-style internet Hungary
31 Jul 25 at 2:50 am
купить диплом с занесением в реестр челябинск [url=https://arus-diplom32.ru]купить диплом с занесением в реестр челябинск[/url] .
Diplomi_kcpi
31 Jul 25 at 2:56 am
кайт школа Уход за кайтом: как продлить срок службы
Kennethvut
31 Jul 25 at 2:58 am
Близкий человек в запое? Не ждите ухудшения. Обратитесь в клинику — здесь проведут профессиональный вывод из запоя с последующим восстановлением организма.
Дополнительно читайте здесь – [url=https://vyvod-iz-zapoya-rostov15.ru/]вывод из запоя анонимно город ростов-на-дону[/url]
NormanOpeft
31 Jul 25 at 3:02 am
Затяжной запой опасен для жизни. Врачи наркологической клиники в Ростове-На-Дону проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Изучите внимательнее – [url=https://vyvod-iz-zapoya-rostov12.ru/]вывод из запоя в стационаре[/url]
GeraldNuh
31 Jul 25 at 3:02 am
Every weekend i used to go to see this site, as i wish for
enjoyment, for the reason that this this web site conations really fastidious funny stuff
too.
jitawin login
31 Jul 25 at 3:06 am
Клиника в Балашихе — Частный Медик 24: стационарный вывод из запоя с комфортом и медицинским сопровождением.
Посмотреть подробности – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha11.ru/]балашиха.[/url]
RichardBut
31 Jul 25 at 3:09 am
кайт школа Кайт лагерь: что включено в стоимость и выбор лагеря
Kennethvut
31 Jul 25 at 3:12 am
Hey! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your blog posts.
Can you recommend any other blogs/websites/forums that deal
with the same topics? Thanks a ton!
دفترچه راهنمای ثبت نام استعدادهای برتر ملّی در دانشگاه فرهنگیان ۱۴۰۵-۱۴۰۴
31 Jul 25 at 3:17 am
Затяжной запой опасен для жизни. Врачи наркологической клиники в Ростове-На-Дону проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Как это работает — подробно – [url=https://vyvod-iz-zapoya-rostov16.ru/]вывод из запоя цена город ростов-на-дону[/url]
KeithJab
31 Jul 25 at 3:24 am
Узнайте про выведение из запоя в стационаре в Частном Медике 24 (Балашиха) по ссылке.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha12.ru/]вывод из запоя на дому цена в балашихе[/url]
ElbertCox
31 Jul 25 at 3:25 am
Врачи клиники «ВитаЛайн» для снятия интоксикации и облегчения состояния пациента применяют исключительно качественные и проверенные лекарственные препараты, подбирая их в зависимости от особенностей ситуации и состояния здоровья пациента:
Подробнее – [url=https://narcolog-na-dom-novosibirsk0.ru/]выезд нарколога на дом[/url]
Jameshit
31 Jul 25 at 3:26 am
Клиника «НаркоЩит» предоставляет возможность безопасного вывода из запоя на дому в Нижнем Новгороде и Нижегородской области с помощью установки капельницы. Наши опытные специалисты оперативно приезжают для проведения детоксикации, снятия симптомов алкогольной интоксикации и стабилизации состояния пациента. Мы гарантируем круглосуточный выезд, соблюдение конфиденциальности и высокий уровень профессионального обслуживания.
Углубиться в тему – http://
RobertTIX
31 Jul 25 at 3:28 am
кайт школа “Лестница мастерства”: обучение, как “алхимия преображения”
Kennethvut
31 Jul 25 at 3:37 am