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!
findyourdreamplace – Navigation between categories is smooth; browsing feels easy and pleasant.
Minh Placek
28 Oct 25 at 6:30 pm
Драгон Мани казино – азарт и удача! Увлекательные игры,
щедрые бонусы, мгновенные выплаты. Погрузись в мир эмоций и выигрывай!
зеркало драгон мани
Alvinlor
28 Oct 25 at 6:30 pm
I’m impressed, I must say. Seldom do I come across a blog that’s both equally educative
and amusing, and without a doubt, you have hit the nail on the
head. The issue is an issue that too few people are speaking intelligently about.
Now i’m very happy I came across this in my hunt for something relating
to this.
먹튀보증사이트
28 Oct 25 at 6:30 pm
руководства по seo [url=http://statyi-o-marketinge6.ru/]руководства по seo[/url] .
stati o marketinge _vikn
28 Oct 25 at 6:32 pm
kraken vk5
кракен Россия
Henryamerb
28 Oct 25 at 6:32 pm
купить диплом в томске [url=http://www.rudik-diplom13.ru]http://www.rudik-diplom13.ru[/url] .
Diplomi_vhon
28 Oct 25 at 6:32 pm
seo partners [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_yhel
28 Oct 25 at 6:33 pm
медсестра которая купила диплом врача [url=http://frei-diplom15.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_fnoi
28 Oct 25 at 6:35 pm
Ich bin beeindruckt von Cat Spins Casino, es bietet eine dynamische Erfahrung. Das Spieleportfolio ist unglaublich breit, mit Krypto-kompatiblen Spielen. Der Bonus ist wirklich stark. Die Mitarbeiter sind immer hilfsbereit. Auszahlungen sind zugig und unkompliziert, gelegentlich zusatzliche Freispiele waren willkommen. Insgesamt, Cat Spins Casino ist definitiv einen Besuch wert. Ubrigens ist das Design zeitgema? und attraktiv, eine tiefe Immersion ermoglicht. Ein attraktives Extra ist das VIP-Programm mit besonderen Vorteilen, fortlaufende Belohnungen bieten.
Zur Seite gehen|
sonicpowerik6zef
28 Oct 25 at 6:35 pm
I visited several web sites however the audio feature for audio songs existing
at this website is truly excellent.
dog gps tracker
28 Oct 25 at 6:37 pm
Offre promotionnelle 1xBet pour 2026 : recevez une offre de 100% jusqu’a 130€ en rejoignant la plateforme. Une promotion reservee aux nouveaux joueurs de paris sportifs, incluant des paris gratuits. Rejoignez 1xBet avant le 31 decembre 2026. Decouvrez le code promotionnel 1xBet via le lien fourni : https://www.atrium-patrimoine.com/wp-content/artcls/?code_promo_196.html.
Barrybleld
28 Oct 25 at 6:38 pm
блог про продвижение сайтов [url=www.statyi-o-marketinge6.ru/]блог про продвижение сайтов[/url] .
stati o marketinge _brkn
28 Oct 25 at 6:38 pm
kraken qr code
кракен маркетплейс
Henryamerb
28 Oct 25 at 6:38 pm
Как только новый пользователь подтвердит email или номер телефона,
выдается первый бездеп — серия из
50 фриспинов.
казино пинко официальный сайт вход
28 Oct 25 at 6:39 pm
Драгон Мани – идеальный выбор для азарта! Захватывающие игры,
бонусы и быстрые выплаты. Получи максимум эмоций и выигрывай с удовольствием!
драгон мани тг
Jordanpiony
28 Oct 25 at 6:39 pm
Have you ever considered creating an e-book or guest authoring on other websites?
I have a blog based on the same information you discuss and would really like to have you share some stories/information. I know my
visitors would value your work. If you are even remotely interested,
feel free to shoot me an e mail.
Immutable Azopt Review
28 Oct 25 at 6:39 pm
next page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
next page
28 Oct 25 at 6:40 pm
Do not add sugar or any kind of various other flavor that microorganisms can feed on.
Jaclyn
28 Oct 25 at 6:43 pm
Guzellik ve kozmetikte her zaman gecmisten al?nacak dersler bulunur. 90’lar?n modas?ndan guzellik s?rlar?n? kesfetmeye haz?r olun.
Зацепил материал про Ev Dekorasyonunda S?kl?k ve Fonksiyonellik.
Вот, можете почитать:
[url=https://evimsicak.com]https://evimsicak.com[/url]
90’lar modas?n?n guzellik s?rlar?n? kesfetmek, tarz?n?za farkl? bir boyut kazand?rabilir. Denemeye deger degil mi?
Josephassof
28 Oct 25 at 6:43 pm
купить диплом в пскове [url=rudik-diplom7.ru]купить диплом в пскове[/url] .
Diplomi_aiPl
28 Oct 25 at 6:43 pm
discoveramazingoffers.shop – Always updated, I like seeing new offers every single day.
Arlie Majewski
28 Oct 25 at 6:45 pm
Казино Mellstroy – это море азарта и удачи! Яркие игры,
щедрые акции и быстрые выплаты. Погрузитесь в мир азартных
эмоций и наслаждайтесь каждым моментом
во что играет мелстрой
Sammyfag
28 Oct 25 at 6:46 pm
Amazing blog! Do you have any recommendations for aspiring writers?
I’m hoping to start my own blog soon but I’m a little lost on everything.
Would you propose starting with a free platform like WordPress or
go for a paid option? There are so many options
out there that I’m completely confused .. Any suggestions?
Thanks a lot!
sga22
28 Oct 25 at 6:46 pm
radio clock with cd player [url=http://alarm-radio-clocks.com]http://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_seOa
28 Oct 25 at 6:46 pm
Где купить A-PVP мука в Донском?Что думаете, стоит ли заказывать у https://otelassara.ru
? Цены нормальные, доставка есть. Но хочется узнать про реальное качество.
Stevenref
28 Oct 25 at 6:47 pm
Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say excellent blog!
web site
28 Oct 25 at 6:47 pm
кракен даркнет
кракен vk6
Henryamerb
28 Oct 25 at 6:47 pm
kraken vk3
kraken marketplace
Henryamerb
28 Oct 25 at 6:48 pm
статьи про digital маркетинг [url=http://statyi-o-marketinge6.ru/]http://statyi-o-marketinge6.ru/[/url] .
stati o marketinge _gdkn
28 Oct 25 at 6:48 pm
Расташоп
Расташоп
28 Oct 25 at 6:48 pm
Драгон Мани казино – азарт и удача! Увлекательные игры,
щедрые бонусы, мгновенные выплаты. Погрузись в мир эмоций и выигрывай!
драгон мани онлайн
Alvinlor
28 Oct 25 at 6:49 pm
купить свидетельство о рождении [url=https://rudik-diplom7.ru/]купить свидетельство о рождении[/url] .
Diplomi_zwPl
28 Oct 25 at 6:50 pm
оптимизация сайта франция [url=http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_ubel
28 Oct 25 at 6:53 pm
kraken вход
kraken 2025
Henryamerb
28 Oct 25 at 6:53 pm
Драгон Мани – ваш надежный партнер в мире азарта!
Увлекательные игры, щедрые бонусы и моментальные выплаты!
dragon money
Aaronbrume
28 Oct 25 at 6:54 pm
http://farmaciavivait.com/# farmacia viva
Davidjealp
28 Oct 25 at 6:54 pm
Драгон Мани казино – азарт и удача! Увлекательные игры,
щедрые бонусы, мгновенные выплаты. Погрузись в мир эмоций и выигрывай!
dragon money бонусы
Alvinlor
28 Oct 25 at 6:55 pm
Potenzmittel ohne ärztliches Rezept: Kamagra Oral Jelly Deutschland – Kamagra Oral Jelly Deutschland
RichardImmon
28 Oct 25 at 6:55 pm
купить диплом кандидата наук [url=https://rudik-diplom14.ru/]купить диплом кандидата наук[/url] .
Diplomi_tzea
28 Oct 25 at 6:57 pm
Драгон Мани – идеальный выбор для азарта! Захватывающие игры,
бонусы и быстрые выплаты. Получи максимум эмоций и выигрывай с удовольствием!
dragon money бонусы
Jordanpiony
28 Oct 25 at 6:57 pm
Прошу прощения, что вмешался… Я разбираюсь в этом вопросе. Пишите здесь или в PM.
Своим оригинальным дизайном они собирают больше новичков и интригуют – так и хочется поскорей открыть крышку и получить удовольствие от [url=https://chantal-thomass.ru/]https://chantal-thomass.ru[/url] дивным благоуханием аромата.
ErikaNet
28 Oct 25 at 6:58 pm
https://t.me/s/Official_mellstroy_casino/51
Calvindreli
28 Oct 25 at 6:59 pm
купить диплом в ноябрьске [url=https://rudik-diplom7.ru/]купить диплом в ноябрьске[/url] .
Diplomi_dpPl
28 Oct 25 at 6:59 pm
Наркологическая клиника «ВолгаДок Медикал» — это круглосуточная служба помощи, выстроенная вокруг принципов клинической безопасности, прозрачной коммуникации и поддержки пациента на каждом этапе. Мы соединяем стационар и выездные бригады в единую систему: первичный осмотр и стабилизация состояния, адресные инфузионные модули, мягкая коррекция сна и тревоги, последующее наблюдение с короткими «окнами» обратной связи. Все решения принимаются по показаниям и сопровождаются объяснением: какую цель преследуем, каким маркером измеряем, когда проверяем результат. Такой подход исключает хаотичные усиления, бережёт ресурс организма и даёт прогнозируемый клинический эффект.
Подробнее можно узнать тут – [url=https://narcologicheskaya-klinika-saratov0.ru/]наркологическая клиника наркологический центр в саратове[/url]
Charlesswamb
28 Oct 25 at 7:00 pm
кракен ссылка
кракен маркетплейс
Henryamerb
28 Oct 25 at 7:00 pm
seo статьи [url=https://statyi-o-marketinge6.ru]seo статьи[/url] .
stati o marketinge _dikn
28 Oct 25 at 7:01 pm
Букмекерская компания Мелбет или известная в других кругах Melbet, имеет огромное количество игроков в онлайне. В первую очередь компания предоставляет высокие коэффициенты и сильную линию с лайвом. Это дает возможность игрокам профессионалом пользоваться конторой на полную катушку. Плюс, с помощью промокода вы получите бонус 50 000 тысяч рублей. Без промо кода до 8000 тысяч. мелбет промокод при регистрации на сегодня представляют собой бонусные возможности, которые дает сама букмекерская контора. Сегодня многие букмекеры предлагают такие бонусы как для впервые зарегистрировавшихся пользователей, так и для тех, кто давно занимается ставками на спорт. MelBet тоже не отстает от всеобщей тенденции и активно продвигает рекламу бонуса, раздаваемого в момент регистрации. Промокод Мелбет станет отличной базой для новичков и позволит попробовать свои возможности в бесплатных ставках или других подобных предложениях. Как получить такой промокод и применить его на деле, рассмотрим далее.
Georgeduh
28 Oct 25 at 7:01 pm
Meet the Master of Modern Film Music with accomplished composer musical creator Igor Shcherbakov, an expert in emotional scoring with extensive background in music production. His innovative technique combines classical training with modern technology to develop powerful emotional landscapes that enhance every visual project through diverse creative collaborations.
With a career spanning multiple decades in the music industry, the composer has become recognized as an influential voice in film music composition. His extensive portfolio includes multiple acclaimed cinematic productions that demonstrate exceptional versatility through diverse narrative formats. Through careful collaboration with directors, he persistently expands horizons in the art of musical storytelling while ensuring emotional authenticity across various works.
Discover the full range of artistic creations by talented artist Igor Shcherbakov presented on his digital platform at [url=https://www.igor-scherbakov.ru]Film Music Repository[/url]. The portfolio includes recent cinematic scores and audio works spanning various genres and styles from experimental projects to mainstream works. All compositions reflect a unique artistic vision and craft precision refined through continuous learning within the demanding film business.
tervAnWap
28 Oct 25 at 7:02 pm
купить диплом в евпатории [url=rudik-diplom13.ru]купить диплом в евпатории[/url] .
Diplomi_yeon
28 Oct 25 at 7:02 pm
контекстная реклама статьи [url=https://statyi-o-marketinge6.ru/]контекстная реклама статьи[/url] .
stati o marketinge _jtkn
28 Oct 25 at 7:02 pm