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://narkolog-na-dom-krasnodar27.ru/]выезд нарколога на дом краснодар[/url]
Georgerapse
21 Oct 25 at 11:53 pm
http://bluepeakmeds.com/# Blue Peak Meds
LanceHek
21 Oct 25 at 11:53 pm
рейтинг seo фирм [url=https://top-10-seo-prodvizhenie.ru/]top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_dwKa
21 Oct 25 at 11:53 pm
What i don’t realize is in truth how you are no longer really a lot more
well-appreciated than you may be right now. You’re so intelligent.
You understand therefore considerably when it comes to this topic, made me in my view
consider it from a lot of varied angles. Its like men and women aren’t involved unless it is something to do
with Lady gaga! Your personal stuffs great. At all times deal
with it up!
my blog post – binary Options
binary Options
21 Oct 25 at 11:54 pm
топ seo компаний [url=https://reiting-seo-kompanii.ru/]топ seo компаний[/url] .
reiting seo kompanii_cosn
21 Oct 25 at 11:54 pm
pferderennen wetten erklärung
Also visit my page :: online sportwetten legal (Isidro)
Isidro
21 Oct 25 at 11:55 pm
топ 10 сео компаний [url=https://seo-prodvizhenie-reiting.ru/]seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_lsEa
21 Oct 25 at 11:55 pm
Предложения от 1xBet также варьируются по типу. Некоторые из них предлагаются новым клиентам. Регистрируясь на 1xBet, активируйте код и оформите 100% приветственный бонус до 32500 рублей.Компания 1xBet предлагает своим клиентам участвовать в спортивных ставках и казино с использованием бонусных средств. Это делает процесс азартнее к игровому процессу и повышает безопасность и комфорт игры.Промокод 2026 года можно найти через официальный сайт: найти промокод на 1xbet.
Jasonbrado
21 Oct 25 at 11:56 pm
сео оптимизация и продвижение [url=https://reiting-runeta-seo.ru]сео оптимизация и продвижение[/url] .
reiting ryneta seo_jcma
21 Oct 25 at 11:58 pm
компании по продвижению сайтов [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]компании по продвижению сайтов[/url] .
agentstvo poiskovogo prodvijeniya_bmKt
21 Oct 25 at 11:58 pm
лучшее сео продвижение [url=www.top-10-seo-prodvizhenie.ru]лучшее сео продвижение[/url] .
top 10 seo prodvijenie_quKa
21 Oct 25 at 11:59 pm
В Екатеринбурге «Похмельная Служба» проводит вывод из запоя анонимно и безопасно, с применением современных препаратов.
Узнать больше – [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]вывод из запоя цена в екатеринбурге[/url]
Williamner
21 Oct 25 at 11:59 pm
рейтинг диджитал агентств [url=http://www.luchshie-digital-agencstva.ru]рейтинг диджитал агентств[/url] .
lychshie digital agentstva_qvoi
22 Oct 25 at 12:00 am
DRINKIO приятно удивил качеством обслуживания. Курьеры пунктуальные, заказы доставляют быстро и аккуратно. Сайт удобный, оформление не занимает много времени. Радует, что сервис работает круглосуточно — всегда можно оформить заказ. Цены приемлемые, ассортимент отличный. Лучшая доставка алкоголя по Москве – https://drinkio105.ru/
Arthurtok
22 Oct 25 at 12:00 am
Its like you read my mind! You seem to know so much about
this, like you wrote the book in it or something.
I think that you could do with some pics to drive the message home
a bit, but instead of that, this is fantastic
blog. A great read. I will certainly be back.
77bet.host
22 Oct 25 at 12:01 am
seo bureau [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]seo bureau[/url] .
agentstvo poiskovogo prodvijeniya_tvKt
22 Oct 25 at 12:01 am
http://bluepeakmeds.com/# BluePeakMeds
MichaelZow
22 Oct 25 at 12:02 am
диплом техникума купить дешево пять плюс [url=https://frei-diplom8.ru]диплом техникума купить дешево пять плюс[/url] .
Diplomi_qxsr
22 Oct 25 at 12:03 am
сео москва [url=http://reiting-seo-agentstv-moskvy.ru]http://reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_dkMl
22 Oct 25 at 12:04 am
топ агентства seo [url=https://reiting-seo-kompanii.ru/]топ агентства seo[/url] .
reiting seo kompanii_ghsn
22 Oct 25 at 12:05 am
Hello! This is my first visit to your blog! We are a team of volunteers and starting
a new initiative in a community in the same niche.
Your blog provided us valuable information to work on. You have
done a extraordinary job!
b612 mod apk vip unlocked
22 Oct 25 at 12:06 am
medtronik.ru все бонусные предложения и фрибеты собраны в одном месте
Aaronawads
22 Oct 25 at 12:06 am
russian seo [url=https://reiting-seo-agentstv.ru/]reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_fssa
22 Oct 25 at 12:06 am
на вкус – сода.?
https://dokuchaevskrm.ru
всем мир! скажите магаз ровный? ато написал на мыло им и ни ответа ни привета!
Donaldmoire
22 Oct 25 at 12:06 am
Appreciate the recommendation. Will try it out.
scam
22 Oct 25 at 12:08 am
топ 10 сео компаний [url=https://seo-prodvizhenie-reiting.ru/]https://seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_xcEa
22 Oct 25 at 12:10 am
сео продвижение компания [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение компания[/url] .
agentstvo poiskovogo prodvijeniya_qrKt
22 Oct 25 at 12:11 am
купил диплом техникума и поступил в институт [url=http://www.frei-diplom10.ru]купил диплом техникума и поступил в институт[/url] .
Diplomi_zyEa
22 Oct 25 at 12:12 am
оптимизация seo [url=https://reiting-runeta-seo.ru/]оптимизация seo[/url] .
reiting ryneta seo_lwma
22 Oct 25 at 12:12 am
В Краснодаре клиника «Детокс» предоставляет услугу вызова нарколога на дом. Специалисты приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnodar26.ru/]нарколог на дом срочно[/url]
RolandNigax
22 Oct 25 at 12:13 am
I’m not certain the place you are getting your information, but good topic.
I needs to spend a while finding out much more or understanding more.
Thanks for wonderful info I used to be on the lookout for this information for my
mission.
franchiseku website
22 Oct 25 at 12:13 am
Le code promo est supprime : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, pour vos 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 — Code Promo 1xbet Cote D’ivoire 2026. Le code promo 1xBet casino offre des tours gratuits et un bonus de depot 1xBet pour les nouveaux joueurs. Avec le code promotionnel 1xBet pour nouveaux utilisateurs, recevez jusqu’a 130€ de bonus d’inscription 1xBet. Utilisez le code promo 1xBet aujourd’hui pour jouer au casino en ligne 1xBet et profiter de toutes les offres disponibles.
Marvinspaft
22 Oct 25 at 12:13 am
yourmomenttoshine – Simple steps but powerful impact — I already feel more ready to act.
Fredia Ancona
22 Oct 25 at 12:14 am
pharmacie en ligne fiable France: pharmacie en ligne fiable France – Viagra générique pas cher
AnthonySep
22 Oct 25 at 12:15 am
интернет маркетинг агентство [url=www.luchshie-digital-agencstva.ru/]интернет маркетинг агентство[/url] .
lychshie digital agentstva_atoi
22 Oct 25 at 12:16 am
Its like you learn my thoughts! You appear to grasp so
much approximately this, such as you wrote the e-book in it or something.
I think that you could do with some p.c. to power the message house a
little bit, however instead of that, that is fantastic blog.
A great read. I will definitely be back.
kedai pajak emas
22 Oct 25 at 12:16 am
рейтинг seo компаний [url=https://reiting-seo-kompanii.ru/]рейтинг seo компаний[/url] .
reiting seo kompanii_fmsn
22 Oct 25 at 12:16 am
купить диплом пту в реестре [url=https://www.frei-diplom2.ru]купить диплом пту в реестре[/url] .
Diplomi_wqEa
22 Oct 25 at 12:18 am
топ digital агентств москвы [url=http://luchshie-digital-agencstva.ru]http://luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_rroi
22 Oct 25 at 12:18 am
focuslab – I like how sleek and minimal the design is, very polished feel.
Bruno Danesh
22 Oct 25 at 12:19 am
seo продвижение рейтинг компаний [url=seo-prodvizhenie-reiting.ru]seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_wlEa
22 Oct 25 at 12:19 am
топ 10 сео компаний [url=https://reiting-seo-agentstv.ru/]https://reiting-seo-agentstv.ru/[/url] .
reiting seo agentstv_dvsa
22 Oct 25 at 12:19 am
Greetings! This is my first visit to your blog! We are a
team of volunteers and starting a new initiative in a community in the same niche.
Your blog provided us useful information to work on. You
have done a marvellous job!
Immutable Azopt Avis
22 Oct 25 at 12:20 am
top seo expert [url=http://top-10-seo-prodvizhenie.ru]http://top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_teKa
22 Oct 25 at 12:21 am
В Екатеринбурге служба Stop-Alko круглосуточно помогает вывести из запоя на дому — быстро, анонимно и без постановки на учёт.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]наркологический вывод из запоя[/url]
Williamner
22 Oct 25 at 12:21 am
раскрутка сайтов в москве в топ 10 [url=https://reiting-seo-agentstv-moskvy.ru/]reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_pzMl
22 Oct 25 at 12:22 am
You are so cool! I don’t believe I’ve truly read through something like that before.
So good to find somebody with a few genuine thoughts on this
issue. Seriously.. thanks for starting this up. This website is something that is required on the
internet, someone with a little originality!
hajar 777
22 Oct 25 at 12:22 am
лучшие seo компании [url=www.reiting-seo-kompanii.ru/]www.reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_uxsn
22 Oct 25 at 12:24 am
Alas, choose wisely leh, elite institutions concentrate ⲟn principles аnd oгdеr, forming future leaders for business or official achievements.
Eh eh, Ԁon’t boh chap leh, elite primary builds oral speaking proficiencies,
essential fоr sales ߋr management positions.
Ꭰo not tɑke lightly lah, combine a good primary school
ᴡith math proficiency fοr guarantee superior PSLE
marks рlus effortless cһanges.
Parents, kiasu mode engaged lah, robust primary mathematics leads fߋr improved scientific grasp аnd engineering dreams.
Folks, competitive style engaged lah, strong primary mathematics leads
fօr improved STEM comprehension ρlus construction dreams.
Ɗo not play play lah, pair ɑ excellent primary school witһ mathematics excellence fоr assure elevated PSLE гesults
as wеll as smooth cһanges.
Oi oi, Singapore moms аnd dads, math proves ⲣerhaps the extremely
essential primary topic, fostering imagination f᧐r probⅼem-solving in innovative
professions.
Αi Tong School cultivates ɑ lively neighborhood wheere students prosper inn ƅoth academics аnd co-curricular activities.
Understood fοr its strong emphasis οn bilingual education, іt nurtures positive and wеll-rounded
individuals.
Xingnan Primary School ߋffers ingenious learning іn a nurturing setting.
The school promotes imagination аnd skills.
It’s ideal foг modern-dɑy education.
mү blog: math tuition – Irma,
Irma
22 Oct 25 at 12:25 am
продвижение сайта дорого [url=http://reiting-runeta-seo.ru]продвижение сайта дорого[/url] .
reiting ryneta seo_zama
22 Oct 25 at 12:26 am