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://www.narkologicheskaya-klinika-27.ru]наркологический диспансер москва[/url] .
narkologicheskaya klinika_vcpl
27 Oct 25 at 10:23 pm
ремонт в подвале [url=https://gidroizolyaciya-podvala-cena.ru/]https://gidroizolyaciya-podvala-cena.ru/[/url] .
gidroizolyaciya podvala cena_amKt
27 Oct 25 at 10:23 pm
кракен онион
kraken android
Henryamerb
27 Oct 25 at 10:24 pm
наркологические клиники в москве [url=http://narkologicheskaya-klinika-25.ru]наркологические клиники в москве[/url] .
narkologicheskaya klinika_htPl
27 Oct 25 at 10:27 pm
обмазочная гидроизоляция цена за работу м2 [url=https://gidroizolyaciya-cena-7.ru/]gidroizolyaciya-cena-7.ru[/url] .
gidroizolyaciya cena_ejSi
27 Oct 25 at 10:29 pm
Offre promotionnelle 1xBet pour 2026 : profitez d’un bonus de bienvenue de 100% jusqu’a 130€ en vous inscrivant des maintenant. Une opportunite exceptionnelle pour les amateurs de paris sportifs, avec la possibilite de placer des paris gratuits. Rejoignez 1xBet avant le 31 decembre 2026. Vous pouvez retrouver le code promo 1xBet sur ce lien — https://www.atrium-patrimoine.com/wp-content/artcls/?code_promo_196.html.
Charlescex
27 Oct 25 at 10:30 pm
психолог нарколог в москве [url=http://narkologicheskaya-klinika-25.ru]http://narkologicheskaya-klinika-25.ru[/url] .
narkologicheskaya klinika_cfPl
27 Oct 25 at 10:31 pm
кракен 2025
kraken официальный
Henryamerb
27 Oct 25 at 10:31 pm
Клиника предлагает широкий спектр услуг, охватывающий весь цикл лечения зависимости — от экстренной помощи до длительной реабилитации. Комплексная программа включает медицинскую, психологическую и социальную составляющие, что позволяет добиться устойчивого результата. Все процедуры проводятся под контролем врачей, что обеспечивает безопасность и эффективность терапии.
Подробнее – [url=https://narkologicheskaya-klinika-v-samare16.ru/]частная наркологическая клиника в самаре[/url]
RobertDab
27 Oct 25 at 10:32 pm
Вывод из запоя в клинике в Санкт-Петербурге осуществляется под круглосуточным медицинским контролем с применением современных методов инфузионной терапии, препаратов для восстановления обменных процессов и купирования синдрома отмены. Главной задачей врачей является восстановление баланса между физическим и психическим состоянием, предотвращение осложнений и стабилизация основных жизненных функций.
Изучить вопрос глубже – [url=https://narkologicheskaya-klinika-v-spb16.ru/]наркологическая клиника в санкт-петербурге[/url]
Brianvat
27 Oct 25 at 10:33 pm
Такой комплексный подход позволяет не только купировать острые состояния, но и устранить внутренние факторы, провоцирующие развитие зависимости. После стабилизации состояния пациент переходит к этапу психотерапевтической коррекции, направленной на предотвращение рецидивов.
Получить дополнительные сведения – [url=https://narkologicheskaya-klinika-v-ekb16.ru/]вывод наркологическая клиника екатеринбург[/url]
ErnestAccug
27 Oct 25 at 10:33 pm
купить диплом в новокузнецке [url=http://rudik-diplom1.ru]купить диплом в новокузнецке[/url] .
Diplomi_uzer
27 Oct 25 at 10:33 pm
Terrific article! This is the type of info that are meant to be shared across the internet.
Disgrace on the seek engines for now not positioning this
publish higher! Come on over and seek advice from my website .
Thanks =)
private desert safari dubai
27 Oct 25 at 10:34 pm
Hey there are using WordPress for your blog platform? I’m new to the blog
world but I’m trying to get started and set up my own. Do you require any coding knowledge to make your own blog?
Any help would be really appreciated!
Dravixen
27 Oct 25 at 10:34 pm
Ich habe einen Narren gefressen an Cat Spins Casino, es entfuhrt in eine Welt voller Spa?. Die Auswahl ist einfach unschlagbar, mit Live-Sportwetten. Mit schnellen Einzahlungen. Der Service ist immer zuverlassig. Die Zahlungen sind sicher und sofortig, trotzdem ein paar zusatzliche Freispiele waren klasse. Insgesamt, Cat Spins Casino garantiert langanhaltenden Spa?. Hinzu kommt die Oberflache ist glatt und benutzerfreundlich, eine Note von Eleganz hinzufugt. Ein gro?artiges Bonus die haufigen Turniere fur mehr Spa?, exklusive Boni bieten.
Details prГјfen|
SolarRiderik3zef
27 Oct 25 at 10:36 pm
What’s up to every body, it’s my first visit of this web
site; this weblog contains awesome and really excellent data for readers.
requiring no technical skills—just select your suffix and generate. It prioritizes security with local key creation and offline support
27 Oct 25 at 10:36 pm
[url=https://elektrokarnizy-dlya-shtor-moskva.ru/]карниз с электроприводом прокарниз[/url] позволяют управлять шторами с помощью одного нажатия кнопки, обеспечивая удобство и комфорт в вашем доме.
Пульт дистанционного управления позволяет легко управлять такими карнизами.
электрокарниз для тяжелых штор Prokarniz
27 Oct 25 at 10:37 pm
Profitez du code promo 1xbet 2026 : recevez un bonus de 100% sur votre premier depot, jusqu’a 130 €. Jouez et placez vos paris facilement grace aux fonds bonus. Apres l’inscription, il est important de recharger votre compte. Si votre compte est verifie, vous pourrez retirer toutes les sommes d’argent, y compris les bonus. Vous pouvez trouver le code promo 1xbet sur ce lien : Code Promo 1xbet Togo.Le code promo 1xBet sans depot est valable pour les nouveaux utilisateurs en Afrique du Sud, au Gabon et en RDC. Ce code promotionnel 1xBet offre des bonus gratuits 1xBet et des tours gratuits 1xBet aujourd’hui. Utilisez le meilleur code promo pour 1xBet et recevez votre bonus d’inscription 1xBet en quelques clics.
Charlescex
27 Oct 25 at 10:37 pm
клиника наркологии москва [url=https://narkologicheskaya-klinika-28.ru/]клиника наркологии москва[/url] .
narkologicheskaya klinika_yxMa
27 Oct 25 at 10:38 pm
kraken market
kraken marketplace
Henryamerb
27 Oct 25 at 10:39 pm
Ich bin absolut begeistert von Cat Spins Casino, es verspricht pure Spannung. Das Angebot an Titeln ist riesig, mit aufregenden Live-Casino-Erlebnissen. Er sorgt fur einen starken Einstieg. Der Kundensupport ist erstklassig. Der Prozess ist transparent und schnell, trotzdem gro?ere Boni waren ideal. Abschlie?end, Cat Spins Casino ist ein Ort fur pure Unterhaltung. Hinzu kommt ist das Design modern und einladend, eine Note von Eleganz hinzufugt. Ein bemerkenswertes Extra sind die zuverlassigen Krypto-Zahlungen, reibungslose Transaktionen sichern.
https://catspinsbonus.com/|
AlphaNerdis9zef
27 Oct 25 at 10:40 pm
кракен маркетплейс
kraken официальный
Henryamerb
27 Oct 25 at 10:40 pm
купить диплом в березниках [url=http://www.rudik-diplom1.ru]купить диплом в березниках[/url] .
Diplomi_tler
27 Oct 25 at 10:41 pm
Howdy! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked
hard on. Any tips?
DIO
27 Oct 25 at 10:42 pm
наркологическая клиника трезвый выбор [url=narkologicheskaya-klinika-25.ru]narkologicheskaya-klinika-25.ru[/url] .
narkologicheskaya klinika_bkPl
27 Oct 25 at 10:42 pm
сырость в подвале многоквартирного дома [url=http://www.gidroizolyaciya-cena-8.ru]http://www.gidroizolyaciya-cena-8.ru[/url] .
gidroizolyaciya cena_xzKn
27 Oct 25 at 10:42 pm
купить диплом учителя [url=https://www.rudik-diplom9.ru]купить диплом учителя[/url] .
Diplomi_cmei
27 Oct 25 at 10:43 pm
Автоматические выключатели
JulioGer
27 Oct 25 at 10:44 pm
кракен вход
кракен ios
Henryamerb
27 Oct 25 at 10:45 pm
Ich bin total angetan von Cat Spins Casino, es schafft eine aufregende Atmosphare. Es gibt unzahlige packende Spiele, mit Spielen, die Krypto unterstutzen. Mit einfachen Einzahlungen. Erreichbar rund um die Uhr. Auszahlungen sind blitzschnell, manchmal regelma?igere Promos wurden das Spiel aufwerten. Insgesamt, Cat Spins Casino ist ein Muss fur Spieler. Daruber hinaus die Oberflache ist glatt und benutzerfreundlich, eine Prise Stil hinzufugt. Ein klasse Bonus die spannenden Community-Aktionen, regelma?ige Boni bieten.
http://www.catspins-de.de|
omegaqueenan2zef
27 Oct 25 at 10:45 pm
Increíble artículo sobre los juegos más populares de Pin-Up Casino
en México. Es impresionante cómo juegos como Gates of Olympus, Sweet Bonanza y Book of Dead continúan siendo los preferidos.
La información sobre los multiplicadores, rondas
de bonificación y pagos en cascada fue muy
útil.
Recomiendo leer el artículo completo si quieres descubrir
qué juegos están marcando tendencia en Pin Up Casino.
Muy completo, ideal para quienes quieren probar tanto slots clásicos como opciones innovadoras.
Te recomiendo visitar el post original para conocer las tragamonedas más populares de
2025 en Pin-Up Casino.
information
27 Oct 25 at 10:47 pm
гидроизоляция подвала снаружи цена [url=www.gidroizolyaciya-podvala-cena.ru]www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_buKt
27 Oct 25 at 10:47 pm
Usually I don’t learn post on blogs, but I wish to say that this write-up very pressured me
to try and do so! Your writing taste has been amazed me.
Thank you, quite great article.
Quantum Flowbit
27 Oct 25 at 10:47 pm
купить диплом в твери [url=www.rudik-diplom12.ru]купить диплом в твери[/url] .
Diplomi_flPi
27 Oct 25 at 10:47 pm
частная клиника наркологическая [url=https://narkologicheskaya-klinika-28.ru/]частная клиника наркологическая[/url] .
narkologicheskaya klinika_fjMa
27 Oct 25 at 10:49 pm
частные наркологические клиники в москве [url=https://narkologicheskaya-klinika-25.ru]частные наркологические клиники в москве[/url] .
narkologicheskaya klinika_goPl
27 Oct 25 at 10:50 pm
What’s up colleagues, its enormous piece of writing about educationand fully
defined, keep it up all the time.
visa for turkey from australia
27 Oct 25 at 10:50 pm
Сочетание медицинских и психотерапевтических мер создаёт устойчивую систему поддержки. Пациенты получают возможность постепенно восстановить утраченное здоровье и психологическую стабильность.
Узнать больше – http://narkologicheskaya-klinika-v-kazani16.ru
BernardGodeN
27 Oct 25 at 10:51 pm
If some one desires to be updated with latest technologies
then he must be go to see this website and be up
to date daily.
viagra
27 Oct 25 at 10:52 pm
кракен даркнет
kraken официальный
Henryamerb
27 Oct 25 at 10:52 pm
wooziewear – Enjoyed reading these posts, ideas are simple yet very useful.
Mohamed Babb
27 Oct 25 at 10:54 pm
kamagra: Kamagra sans ordonnance – Kamagra oral jelly France
RichardImmon
27 Oct 25 at 10:56 pm
гидроизоляция подвала снаружи цена [url=https://gidroizolyaciya-cena-7.ru/]https://gidroizolyaciya-cena-7.ru/[/url] .
gidroizolyaciya cena_cbSi
27 Oct 25 at 10:57 pm
В городе и пригороде организован круглосуточный приём с возможностью выезда на дом. Координатор уточняет только клинически значимые данные: регулярные препараты и дозировки, аллергии, недавние эпизоды судорог/психозов, доступ к розетке, возможность обеспечить «тихое окно» на 2–3 часа. Если в квартире многолюдно или идёт ремонт, предложим «тихий» стационар с отдельным входом и тем же ведущим врачом; после стабилизации зеркально перенесём маршрут обратно домой, чтобы не терять темп и доверие.
Детальнее – [url=https://narkologicheskaya-klinika-v-nizhnem-novgorode16.ru/]частная наркологическая клиника в нижнем новгороде[/url]
Prestonned
27 Oct 25 at 10:57 pm
expandyourhorizon – The layout is clean and user-friendly, making navigation effortless.
Jasper Pietzsch
27 Oct 25 at 10:59 pm
частная клиника наркологическая [url=http://narkologicheskaya-klinika-25.ru]http://narkologicheskaya-klinika-25.ru[/url] .
narkologicheskaya klinika_jfPl
27 Oct 25 at 11:00 pm
кракен ссылка
kraken сайт
Henryamerb
27 Oct 25 at 11:00 pm
difyd2c.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Qiana Tierman
27 Oct 25 at 11:00 pm
кракен ios
kraken официальный
Henryamerb
27 Oct 25 at 11:01 pm
inkorswimtattoocruise – Excellent resource, practical guides make home projects feel stress-free always.
Nidia Venturini
27 Oct 25 at 11:01 pm