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.proekt-pereplanirovki-kvartiry11.ru]сколько стоит перепланировка квартиры[/url] .
proekt pereplanirovki kvartiri_wsot
20 Oct 25 at 12:27 pm
kraken vk2
кракен официальный сайт
JamesDaync
20 Oct 25 at 12:28 pm
Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog?
My blog is in the exact same niche as yours and my users would genuinely benefit from a
lot of the information you provide here. Please let me know if this alright with you.
Appreciate it!
j88slot
20 Oct 25 at 12:28 pm
диплом техникума купить екатеринбург [url=https://frei-diplom11.ru/]диплом техникума купить екатеринбург[/url] .
Diplomi_qwsa
20 Oct 25 at 12:30 pm
cialis generika [url=https://potenzvital.com/#]Cialis generika günstig kaufen[/url] Tadalafil 20mg Bestellung online
GeorgeHot
20 Oct 25 at 12:30 pm
купить аттестаты за 9 [url=www.rudik-diplom15.ru]купить аттестаты за 9[/url] .
Diplomi_owPi
20 Oct 25 at 12:32 pm
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Интересует подробная информация – http://capmeroccitanie.fr/facade-maritime-occitanie-patrimoine-a
Robertarelo
20 Oct 25 at 12:33 pm
wettbüro krefeld
Here is my webpage :: wettanbieter paypal (Bud)
Bud
20 Oct 25 at 12:34 pm
There is certainly a great deal to learn about this subject.
I love all of the points you have made.
website
20 Oct 25 at 12:34 pm
https://t.me/s/reiting_top10_casino/2
EdwardAdete
20 Oct 25 at 12:37 pm
https://diigo.com/0112692
KevinKinny
20 Oct 25 at 12:37 pm
https://t.me/s/reiting_top10_casino/4
EdwardAdete
20 Oct 25 at 12:38 pm
cd player with clock [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_zcOa
20 Oct 25 at 12:38 pm
Hey There. I found your blog using msn. This is a very well
written article. I’ll be sure to bookmark it
and come back to read more of your useful information. Thanks for the post.
I will certainly return.
https://www.akhuwat.web.pk/
20 Oct 25 at 12:39 pm
[url=https://rebatemyforex.com/]The RebateMyForex platform [/url]helps forex traders recover part of their trading costs through cash rebates. You can link your existing forex accounts to the platform with just a few clicks and immediately begin earning money back from your trades. Every executed order can bring you additional income. The concept is simple: the more you trade, the more you earn. Whether you’re a beginner or an expert trader, the system adapts to your needs. Users appreciate the fast payments, detailed statistics, and full transparency of their earnings. All transactions are clear, and you always see how much you’ve earned. You can choose from dozens of reputable forex brokers directly inside your account. RebateMyForex also provides useful educational content and trading analytics. Withdrawal methods are flexible and fast, supporting multiple currencies. Many traders call it an essential part of their trading toolkit. Support is always available to help users with registration or broker connection. If you’re serious about forex trading, you shouldn’t miss this opportunity. Its mission is to make forex trading more rewarding and accessible. Create your account and activate your cashback within minutes.
https://rebatemyforex.com/
Ralphchect
20 Oct 25 at 12:39 pm
Everything is very open with a very clear description of
the issues. It was truly informative. Your website is very useful.
Many thanks for sharing!
Outdoor lighting installation
20 Oct 25 at 12:42 pm
potenzmittel cialis [url=https://potenzvital.com/#]Tadalafil 20mg Bestellung online[/url] cialis kaufen
GeorgeHot
20 Oct 25 at 12:43 pm
купить диплом в новом уренгое [url=http://rudik-diplom14.ru/]http://rudik-diplom14.ru/[/url] .
Diplomi_pxea
20 Oct 25 at 12:44 pm
купить диплом в оренбурге [url=rudik-diplom2.ru]купить диплом в оренбурге[/url] .
Diplomi_gupi
20 Oct 25 at 12:44 pm
драгон мани казино
NormanmuP
20 Oct 25 at 12:45 pm
kraken 2025
kraken вход
JamesDaync
20 Oct 25 at 12:46 pm
купить диплом спб колледж [url=frei-diplom8.ru]frei-diplom8.ru[/url] .
Diplomi_xksr
20 Oct 25 at 12:47 pm
https://telegra.ph/Consejos-de-Hidrataci%C3%B3n-para-un-Examen-de-Orina-Exitoso-en-Chile-09-11
Detox para examen de miccion se ha transformado en una solucion cada vez mas conocida entre personas que requieren eliminar toxinas del sistema y superar pruebas de test de drogas. Estos formulas estan disenados para ayudar a los consumidores a purgar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el consumo de cannabis u otras drogas.
Uno buen detox para examen de pipi debe ofrecer resultados rapidos y visibles, en especial cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas opciones, pero no todas garantizan un proceso seguro o rapido.
?Como funciona un producto detox? En terminos simples, estos suplementos operan acelerando la expulsion de metabolitos y residuos a traves de la orina, reduciendo su nivel hasta quedar por debajo del limite de deteccion de los tests. Algunos trabajan en cuestion de horas y su efecto puede durar entre 4 a seis horas.
Resulta fundamental combinar estos productos con adecuada hidratacion. Beber al menos par litros de agua al dia antes y despues del ingesta del detox puede mejorar los resultados. Ademas, se sugiere evitar alimentos dificiles y bebidas acidas durante el proceso de preparacion.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de naturales, vitaminas del tipo B y minerales que respaldan el funcionamiento de los sistemas y la funcion hepatica. Entre las marcas mas vendidas, se encuentran aquellas que tienen certificaciones sanitarias y estudios de prueba.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con tiempos de accion largas o iniciar una preparacion previa. Mientras mas prolongada sea la abstinencia, mayor sera la potencia del producto. Por eso, combinar la organizacion con el uso correcto del detox es clave.
Un error comun es pensar que todos los detox actuan lo mismo. Existen diferencias en dosis, sabor, metodo de toma y duracion del resultado. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que agregan fases de preparacion o limpieza previa al dia del examen. Estos programas suelen sugerir abstinencia, buena alimentacion y descanso adecuado.
Por ultimo, es importante recalcar que todo detox garantiza 100% de exito. Siempre hay variables personales como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no relajarse.
JuniorShido
20 Oct 25 at 12:51 pm
I’ve been exploring for a little for any high-quality articles or
weblog posts on this kind of house . Exploring in Yahoo I at last stumbled upon this
site. Studying this info So i am glad to exhibit that I have a very good uncanny feeling I came upon exactly what I needed.
I most certainly will make sure to do not fail to
remember this website and provides it a look on a continuing basis.
bonus deposit tito88
20 Oct 25 at 12:52 pm
купить диплом в люберцах [url=http://rudik-diplom2.ru/]купить диплом в люберцах[/url] .
Diplomi_hzpi
20 Oct 25 at 12:54 pm
https://classifylistings.com/index.php?page=user&action=pub_profile&id=117957
Keithmug
20 Oct 25 at 12:55 pm
проект перепланировки квартиры москва [url=http://www.proekt-pereplanirovki-kvartiry11.ru]проект перепланировки квартиры москва[/url] .
proekt pereplanirovki kvartiri_xdot
20 Oct 25 at 12:56 pm
lying down after taking doxycycline
order generic doxycycline pill
20 Oct 25 at 12:58 pm
https://t.me/reiting_top10_casino/4
EdwardAdete
20 Oct 25 at 12:58 pm
cd player alarm clock radio [url=http://www.alarm-radio-clocks.com]http://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_lyOa
20 Oct 25 at 12:59 pm
перепланировка квартиры в москве [url=https://proekt-pereplanirovki-kvartiry11.ru/]перепланировка квартиры в москве[/url] .
proekt pereplanirovki kvartiri_swot
20 Oct 25 at 12:59 pm
https://t.me/s/reiting_top10_casino/7
EdwardAdete
20 Oct 25 at 12:59 pm
https://www.medtronik.ru/ узнайте, как получить приветственные бонусы и участвовать в акциях
Aaronawads
20 Oct 25 at 12:59 pm
диплом колледжа узбекистана купить [url=www.frei-diplom8.ru/]www.frei-diplom8.ru/[/url] .
Diplomi_jmsr
20 Oct 25 at 12:59 pm
https://www.pathumratjotun.com/forum/topic/97295/1xbet-promo-code-for-casino-games-in-bangladesh
Coreycip
20 Oct 25 at 12:59 pm
купить диплом в сосновом бору [url=https://rudik-diplom2.ru]https://rudik-diplom2.ru[/url] .
Diplomi_bcpi
20 Oct 25 at 1:00 pm
kraken официальный
kraken официальный
JamesDaync
20 Oct 25 at 1:04 pm
купить диплом техникума 1989 [url=frei-diplom11.ru]купить диплом техникума 1989[/url] .
Diplomi_ipsa
20 Oct 25 at 1:06 pm
Беттеру достаточно ввести размер транзакции
и подождать от нескольких минут до 48
часов.
1хбет официальный сайт
20 Oct 25 at 1:08 pm
Бесплатные промокоды 1xBet при регистрации 2026. Сегодня пользователям 1xBet-казино предлагаются халявные промокоды на первый депозит, которые активируются при первой регистрации. С их помощью можно увеличить сумму базового бонуса до 32500 рублей. получить промокод от 1xbet. Для получения реального выигрыша с возможностью вывода на карту, необходимо поставить всю бонусную сумму на экспресс-ставку с коэффициентом от 1,4. Если прогноз окажется правильным, система переведет деньги на основной счет. Не секрет, что у букмекерской конторы 1xBet помимо спортивных ставок есть и другие направления, включая онлайн-игры, гоночные события или политические состязания.
Stanleyvonna
20 Oct 25 at 1:08 pm
dragon money официальный сайт
NormanmuP
20 Oct 25 at 1:09 pm
купить свидетельство о рождении [url=www.rudik-diplom1.ru/]купить свидетельство о рождении[/url] .
Diplomi_kner
20 Oct 25 at 1:10 pm
clock radio with cd player [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_xoOa
20 Oct 25 at 1:11 pm
[url=https://lectnicametall.ru/]готовая лестница купить[/url]
Elmersoupt
20 Oct 25 at 1:12 pm
[url=https://rebatemyforex.com/]Forex rebate service RebateMyForex [/url]provides a transparent forex rebate system for traders worldwide. This service connects directly with top forex brokers so you can start receiving rebates without changing your trading strategy. Even losing trades return cashback to your account. It’s a straightforward way to make your trading more profitable. RebateMyForex works with both individual traders and professional investors. Users appreciate the fast payments, detailed statistics, and full transparency of their earnings. There are no extra commissions or complicated terms. The service supports popular brokers like IC Markets, Exness, and XM. RebateMyForex also provides useful educational content and trading analytics. Withdrawal methods are flexible and fast, supporting multiple currencies. By using RebateMyForex, traders increase their profitability without additional risk. The platform values reliability and client satisfaction above all. Start earning rebates today and make every trade work for you. RebateMyForex continues to expand its network and reward active clients. Create your account and activate your cashback within minutes.
https://rebatemyforex.com/
Ralphchect
20 Oct 25 at 1:12 pm
купить диплом в усолье-сибирском [url=www.rudik-diplom15.ru]купить диплом в усолье-сибирском[/url] .
Diplomi_xhPi
20 Oct 25 at 1:12 pm
проект для перепланировки квартиры стоимость [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_rvot
20 Oct 25 at 1:13 pm
Grabbed $MTAUR in stage 1 frenzy. Presale perks stack. Game beta hype high.
mtaur coin
WilliamPargy
20 Oct 25 at 1:14 pm
Добро пожаловать в удивительный мир природы России!
Хочу выделить материал про Изучение ООПТ России: парки, заповедники, водоемы.
Вот, делюсь ссылкой:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Вот такое у нас получилось погружение в мир природы.
fixRow
20 Oct 25 at 1:14 pm
https://muckrack.com/person-27477743
Anthonycam
20 Oct 25 at 1:14 pm