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=http://zaimy-16.ru/]http://zaimy-16.ru/[/url] .
zaimi_sxMi
19 Sep 25 at 1:40 pm
buy steroids in the us
References:
steroids build muscle (https://output.Jsbin.com/)
https://output.Jsbin.com/
19 Sep 25 at 1:44 pm
Hi everyone, it’s my first pay a visit at this website, and article is genuinely fruitful in support of me, keep up posting these content.
My page … http://www.Lottoup
www.Lottoup
19 Sep 25 at 1:47 pm
https://xn--krken23-bn4c.com
Howardreomo
19 Sep 25 at 1:49 pm
накрутка подписчиков телеграм бесплатно
GustavoRiz
19 Sep 25 at 1:50 pm
http://lifestyle.suratkhabar.com/news/new-analysis-reveals-the-complex-forces-driving-the-great-human-reshuffle/0522013/
Charlesicock
19 Sep 25 at 1:51 pm
Digital life demands accuracy. Engineers, researchers, students, and professionals rely on precise numbers and flawless documents. Yet the tools they need are often scattered across multiple apps, hidden behind subscriptions, or limited in scope. OneConverter addresses this challenge by consolidating advanced unit conversion calculators and PDF document utilities into a single, accessible platform.
Comprehensive Unit Conversions
The strength of OneConverter lies in its range. With more than 50,000 unit converters, it covers virtually every field of science, technology, and daily life.
Core Measurements: conversions for length, weight, speed, temperature, area, volume, time, and energy. These fundamental tools support everyday requirements such as travel, shopping, and cooking.
Engineering & Physics: advanced calculators for torque, density, angular velocity, acceleration, and moment of inertia, enabling precision in both academic study and professional design.
Heat & Thermodynamics: tools for thermal conductivity, resistance, entropy, and enthalpy, providing clarity for scientific research and industrial applications.
Radiology: units such as absorbed dose, equivalent dose, and radiation exposure, essential for healthcare professionals and medical physicists.
Fluid Mechanics: viscosity, pressure, flow rate, and surface tension, all indispensable in laboratory and engineering environments.
Electricity & Magnetism: extensive coverage including voltage, current, resistance, inductance, capacitance, flux, and charge density, supporting fields from electronics to energy.
Chemistry: molarity, concentration, and molecular weight calculators, saving valuable time in laboratories and classrooms.
Astronomy: astronomical units, parsecs, and light years, serving both researchers and students exploring the cosmos.
Practical Applications: everyday conversions for recipes, fuel efficiency, and international clothing sizes.
By combining breadth and accuracy, OneConverter ensures that calculations are reliable, consistent, and instantly available.
oneconverter.com
IsmaelNek
19 Sep 25 at 1:55 pm
https://www.grepmed.com/vmigybefahy
HarryPaync
19 Sep 25 at 1:59 pm
Thank you for another informative web site.
Where else may I am getting that kind of info written in such a perfect means?
I have a challenge that I am just now working on, and
I’ve been at the look out for such information.
macau888
19 Sep 25 at 1:59 pm
cialis generic: EverTrustMeds – Cheap Cialis
Dennisted
19 Sep 25 at 1:59 pm
купить диплом в челябинске [url=https://rudik-diplom7.ru/]купить диплом в челябинске[/url] .
Diplomi_oiPl
19 Sep 25 at 2:00 pm
купить диплом в краснодаре [url=http://rudik-diplom10.ru/]купить диплом в краснодаре[/url] .
Diplomi_gcSa
19 Sep 25 at 2:00 pm
What’s up to every single one, it’s truly a good for me to pay a visit this site, it contains useful Information.
buy allopurinol near me
19 Sep 25 at 2:00 pm
все микрозаймы онлайн [url=http://zaimy-16.ru/]все микрозаймы онлайн[/url] .
zaimi_hdMi
19 Sep 25 at 2:02 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut Official
Jamesner
19 Sep 25 at 2:05 pm
http://business.starkvilledailynews.com/starkvilledailynews/article/prlog-2025-9-16-new-analysis-reveals-the-complex-forces-driving-the-great-human-reshuffle
Charlesicock
19 Sep 25 at 2:09 pm
pure cocaine in prague plug in prague
prague-drugs-970
19 Sep 25 at 2:09 pm
банит ли телеграм за накрутку подписчиков
JohnnyPhido
19 Sep 25 at 2:10 pm
Southeast Financial Nashville
131 Belle Forest Cir #210,
Nashville, TN 37221, United Ѕtates
18669008949
Bookmarks
Bookmarks
19 Sep 25 at 2:10 pm
This is the right site for anybody who would like to understand
this topic. You know so much its almost tough to argue with you (not that I personally would want to…HaHa).
You certainly put a brand new spin on a subject that’s been discussed
for many years. Excellent stuff, just wonderful!
Meteor Profit Review
19 Sep 25 at 2:11 pm
Thank you a bunch for sharing this with all of us you really recognize what you’re speaking approximately!
Bookmarked. Please additionally consult with my site =).
We will have a hyperlink trade agreement among us
pharmeasy
19 Sep 25 at 2:13 pm
микрозаймы все [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_pgMi
19 Sep 25 at 2:13 pm
Thanks for finally writing about > PHP hook, building hooks in your application – Sjoerd Maessen blog at
Sjoerd Maessen blog < Loved it!
سایت پیش بینی فوتبال
19 Sep 25 at 2:15 pm
Clear Meds Hub: ClearMedsHub – Clear Meds Hub
DerekStops
19 Sep 25 at 2:15 pm
hackmd.io
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
hackmd.io
19 Sep 25 at 2:16 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 2:18 pm
кракен ссылка kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
19 Sep 25 at 2:20 pm
Thanks a bunch for sharing this with all people
you actually know what you’re speaking approximately!
Bookmarked. Kindly also visit my website =).
We could have a link change agreement among us
what is feetfinder
19 Sep 25 at 2:21 pm
https://coloradodesk.com/conews/10305025
Charlesicock
19 Sep 25 at 2:21 pm
https://imageevent.com/hoangdungyek/ptonw
HarryPaync
19 Sep 25 at 2:24 pm
I am sure this article has touched all the internet viewers,
its really really pleasant post on building up new web site.
정품 시알리스
19 Sep 25 at 2:27 pm
взо [url=http://zaimy-16.ru]взо[/url] .
zaimi_nqMi
19 Sep 25 at 2:35 pm
Казино Mostbet
Davidfes
19 Sep 25 at 2:42 pm
Добро пожаловать в Клубника Казино, где каждый игрок найдет для себя идеальные условия для выигрыша и наслаждения игрой.
Мы предлагаем широкий выбор игр, включая классические слоты, рулетку, блэкджек и
уникальные игры с живыми дилерами.
В Клубника Казино мы гарантируем полную безопасность и прозрачность всех процессов,
чтобы ваши данные и средства были в
надежных руках.
Почему стоит играть именно в casino klubnika?
В нашем казино каждый игрок может рассчитывать на
щедрые бонусы, бесплатные спины и эксклюзивные предложения.
Кроме того, мы обеспечиваем
быстрые выводы средств и круглосуточную поддержку, чтобы вы могли сосредоточиться
на игре.
Когда стоит начать играть в
Клубника Казино? Не теряйте времени – начните свою игровую карьеру прямо сейчас
и получите щедрые бонусы на первый депозит.
Вот что вас ждет:
Воспользуйтесь щедрыми бонусами и бесплатными спинами, чтобы начать
игру с преимуществом.
Примите участие в наших турнирах и промо-акциях, чтобы получить шанс выиграть крупные денежные призы.
Каждый месяц мы обновляем наш ассортимент игр, добавляя
новые интересные слоты и настольные игры.
Клубника Казино – это идеальное
место для тех, кто хочет играть
и выигрывать.
Клубника программа вознаграждений
19 Sep 25 at 2:42 pm
I’ve been exploring [url=https://ataspanking.site]spanking video[/url] and I have to say, it’s amazing! From adult spanking stories to engaging videos, the community here is super active. If you enjoy immersive spanking content and want to share your experiences, this is the place to be!
Jameskef
19 Sep 25 at 2:45 pm
avanafil for ed
ongoing erectile dysfunction stress
19 Sep 25 at 2:48 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 2:49 pm
https://www.brownbook.net/business/54257306/приложение-купить-наркотики/
HarryPaync
19 Sep 25 at 2:49 pm
https://xn--krken23-bn4c.com
Howardreomo
19 Sep 25 at 2:50 pm
cocaine in prague pure cocaine in prague
prague-drugs-802
19 Sep 25 at 2:51 pm
Wonderful beat ! I would like to apprentice at the same time as you amend your
website, how can i subscribe for a blog site? The account helped me
a appropriate deal. I had been a little bit familiar of
this your broadcast provided vibrant clear idea
foot fetish
19 Sep 25 at 2:51 pm
Заказать диплом любого ВУЗа можем помочь. Купить диплом специалиста в Новокузнецке – [url=http://diplomybox.com/kupit-diplom-spetsialista-v-novokuznetske/]diplomybox.com/kupit-diplom-spetsialista-v-novokuznetske[/url]
Cazrulj
19 Sep 25 at 2:52 pm
Link exchange is nothing else however it is just placing the
other person’s webpage link on your page
at suitable place and other person will also do similar
in favor of you.
seriöses online casino deutschland
19 Sep 25 at 2:54 pm
Chance Machine 5 Dice играть в 1хслотс
JoshuaStism
19 Sep 25 at 2:55 pm
Greetings! Very helpful advice within this post! It is the little changes which
will make the most significant changes. Thanks a lot
for sharing!
best crypto casino
19 Sep 25 at 2:56 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 2:56 pm
Каждый этап проводится под контролем специалистов, что снижает риск осложнений и повышает эффективность лечения.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-ulan-ude00.ru/]нарколог на дом вывод из запоя улан-удэ[/url]
GoodiniIcock
19 Sep 25 at 2:58 pm
Философия «БайкалМедЦентра» — сочетать медицинскую строгость и человеческое участие. Пациент получает помощь там, где ему психологически безопасно — дома, в привычной обстановке, без очередей и лишних контактов. При этом соблюдается полный конфиденциальный режим: бригада приезжает без опознавательных знаков, а документы оформляются в нейтральных формулировках. Если состояние требует госпитализации, клиника организует транспортировку в стационар без потери времени и с непрерывностью терапии.
Подробнее тут – [url=https://vyvod-iz-zapoya-ulan-ude0.ru/]вывод из запоя в улан-удэ[/url]
SimonTon
19 Sep 25 at 2:59 pm
Процесс оказания срочной помощи нарколога на дому в Мариуполе построен по отлаженной схеме, которая включает несколько ключевых этапов, направленных на быстрое и безопасное восстановление здоровья пациента.
Получить больше информации – [url=https://narcolog-na-dom-mariupol00.ru/]платный нарколог на дом мариуполь[/url]
Rodneydig
19 Sep 25 at 2:59 pm
http://business.newportvermontdailyexpress.com/newportvermontdailyexpress/article/prlog-2025-9-2-new-scientific-study-reveals-why-humans-are-attracted-to-bad-smells
Charlesicock
19 Sep 25 at 3:00 pm