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!
1вин скачать приложение [url=1win5509.ru]1win5509.ru[/url]
1win_uz_kwKt
20 Oct 25 at 1:49 am
наркологический анонимный центр [url=www.narkologicheskaya-klinika-20.ru/]www.narkologicheskaya-klinika-20.ru/[/url] .
narkologicheskaya klinika _qrPr
20 Oct 25 at 1:51 am
кракен vk4
kraken vk4
JamesDaync
20 Oct 25 at 1:52 am
купить диплом в рубцовске [url=http://rudik-diplom8.ru]http://rudik-diplom8.ru[/url] .
Diplomi_tjMt
20 Oct 25 at 1:53 am
заказать перепланировку [url=https://proekt-pereplanirovki-kvartiry11.ru]заказать перепланировку[/url] .
proekt pereplanirovki kvartiri_zyot
20 Oct 25 at 1:53 am
Your mode of telling the whole thing in this piece of writing is
actually fastidious, all can effortlessly understand it, Thanks a
lot.
pool renovation
20 Oct 25 at 1:54 am
купить диплом фельдшера [url=www.rudik-diplom7.ru]купить диплом фельдшера[/url] .
Diplomi_yyPl
20 Oct 25 at 1:54 am
https://tech37270.ampedpages.com/una-revisiГіn-de-detox-examen-de-orina-64717793
Purificacion para examen de muestra se ha transformado en una opcion cada vez mas popular entre personas que requieren eliminar toxinas del cuerpo y superar pruebas de analisis de drogas. Estos productos estan disenados para ayudar a los consumidores a depurar su cuerpo de componentes no deseadas, especialmente las relacionadas con el uso de cannabis u otras sustancias ilicitas.
Un buen detox para examen de pipi debe proporcionar resultados rapidos y visibles, en gran cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas alternativas, pero no todas aseguran un proceso seguro o rapido.
Que funciona un producto detox? En terminos basicos, estos suplementos operan acelerando la depuracion de metabolitos y residuos a traves de la orina, reduciendo su nivel hasta quedar por debajo del umbral de deteccion de ciertos tests. Algunos funcionan en cuestion de horas y su accion puede durar entre 4 a seis horas.
Es fundamental combinar estos productos con correcta hidratacion. Beber al menos dos litros de agua por jornada antes y despues del uso del detox puede mejorar los resultados. Ademas, se aconseja evitar alimentos dificiles y bebidas acidas durante el proceso de desintoxicacion.
Los mejores productos de detox para orina incluyen ingredientes como extractos de hierbas, vitaminas del grupo B y minerales que apoyan el funcionamiento de los organos y la funcion hepatica. Entre las marcas mas destacadas, se encuentran aquellas que presentan certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con ventanas de accion largas o iniciar una preparacion anticipada. Mientras mas extendida sea la abstinencia, mayor sera la eficacia del producto. Por eso, combinar la organizacion con el uso correcto del detox es clave.
Un error comun es creer que todos los detox actuan igual. Existen diferencias en contenido, sabor, metodo de uso y duracion del impacto. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que incluyen fases de preparacion o purga previa al dia del examen. Estos programas suelen instruir abstinencia, buena alimentacion y descanso previo.
Por ultimo, es importante recalcar que ningun detox garantiza 100% de exito. Siempre hay variables individuales como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no confiarse.
JuniorShido
20 Oct 25 at 1:55 am
вывод из запоя на дому москва круглосуточно [url=https://www.vyvod-iz-zapoya-9.ru]https://www.vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_vlEl
20 Oct 25 at 1:56 am
как купить диплом проведенный [url=http://frei-diplom2.ru]как купить диплом проведенный[/url] .
Diplomi_rmEa
20 Oct 25 at 1:57 am
лечение зависимости на дому [url=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_gikt
20 Oct 25 at 1:58 am
https://potenzvital.com/# cialis generika
LarryArrix
20 Oct 25 at 1:58 am
услуги по устройству гидроизоляции [url=www.ustroystvo-gidroizolyacii.ru/]www.ustroystvo-gidroizolyacii.ru/[/url] .
ystroistvo gidroizolyacii_mlea
20 Oct 25 at 1:59 am
tadalafil senza ricetta: cialis generico – compresse per disfunzione erettile
JosephPseus
20 Oct 25 at 1:59 am
купить диплом в великих луках [url=http://rudik-diplom7.ru/]купить диплом в великих луках[/url] .
Diplomi_uoPl
20 Oct 25 at 2:00 am
best cd clock radio [url=http://alarm-radio-clocks.com]http://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_atOa
20 Oct 25 at 2:01 am
дешёвый нарколог на дом [url=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_mjkt
20 Oct 25 at 2:01 am
купить диплом инженера [url=http://rudik-diplom14.ru/]купить диплом инженера[/url] .
Diplomi_woea
20 Oct 25 at 2:02 am
где можно купить диплом медицинского колледжа [url=https://frei-diplom11.ru]https://frei-diplom11.ru[/url] .
Diplomi_rpsa
20 Oct 25 at 2:03 am
tadalafil senza ricetta: pillole verdi – PilloleVerdi
RaymondNit
20 Oct 25 at 2:05 am
Profitez d’un code promo unique sur 1xBet permettant a chaque nouveau joueur de beneficier jusqu’a 100€ de bonus sportif a hauteur de 100% en 2026. Ce bonus est credite sur votre solde de jeu en fonction du montant de votre premier depot, le depot minimum etant fixe a 1€. Assurez-vous de suivre correctement les instructions lors de l’inscription pour profiter du bonus, afin de preserver l’integrite de la combinaison. D’autres promotions existent en plus du bonus de bienvenue, vous pouvez trouver d’autres offres dans la section « Vitrine des codes promo ». Consultez le lien pour plus d’informations sur les promotions disponibles — Code Promo De La Machine A Sous 1xbet. Grace au code promo 1xBet gratuit, obtenez un pari gratuit 1xBet ou un bonus sans depot 1xBet. Le code promotionnel 1xBet valide vous permet de beneficier d’un bonus de bienvenue 1xBet 2026 sur vos premiers paris. Essayez le code promo sport 1xBet pour miser sans risque et decouvrir la plateforme.
Marvinspaft
20 Oct 25 at 2:05 am
купить диплом техникума в рязани [url=www.frei-diplom8.ru]купить диплом техникума в рязани[/url] .
Diplomi_tpsr
20 Oct 25 at 2:07 am
kraken client
кракен Россия
JamesDaync
20 Oct 25 at 2:09 am
устройство гидроизоляции пола [url=ustroystvo-gidroizolyacii.ru]ustroystvo-gidroizolyacii.ru[/url] .
ystroistvo gidroizolyacii_djea
20 Oct 25 at 2:10 am
Клиника «Похмельная служба» в Нижнем Новгороде предлагает капельницу от запоя с выездом на дом. Наши специалисты обеспечат вам комфортное и безопасное лечение в привычной обстановке.
Углубиться в тему – [url=https://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]вывод из запоя с выездом в нижний новгороде[/url]
JustinAxots
20 Oct 25 at 2:10 am
проект перепланировки квартиры сро [url=https://www.proekt-pereplanirovki-kvartiry11.ru]проект перепланировки квартиры сро[/url] .
proekt pereplanirovki kvartiri_jwot
20 Oct 25 at 2:12 am
купить диплом во владимире [url=http://rudik-diplom11.ru/]купить диплом во владимире[/url] .
Diplomi_nmMi
20 Oct 25 at 2:12 am
диплом техникум колледж купить [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_lkea
20 Oct 25 at 2:15 am
наркологическое отделение наркологии [url=http://narkologicheskaya-klinika-20.ru]http://narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _onPr
20 Oct 25 at 2:17 am
купить диплом о средне специальном образовании реестр [url=https://frei-diplom2.ru/]купить диплом о средне специальном образовании реестр[/url] .
Diplomi_smEa
20 Oct 25 at 2:19 am
купить диплом техникума тюмень [url=https://frei-diplom8.ru/]купить диплом техникума тюмень[/url] .
Diplomi_xisr
20 Oct 25 at 2:22 am
Hello Dear, are you genuinely visiting this site on a regular basis,
if so after that you will without doubt get good knowledge.
mirror site
20 Oct 25 at 2:24 am
1вин мобильная версия [url=https://www.1win5510.ru]1вин мобильная версия[/url]
1win_uz_mcsi
20 Oct 25 at 2:25 am
лечение зависимости на дому [url=https://narkolog-na-dom-1.ru]https://narkolog-na-dom-1.ru[/url] .
narkolog na dom_qjkt
20 Oct 25 at 2:25 am
kraken ссылка
кракен vk5
JamesDaync
20 Oct 25 at 2:26 am
купить диплом в димитровграде [url=https://rudik-diplom7.ru/]купить диплом в димитровграде[/url] .
Diplomi_xrPl
20 Oct 25 at 2:26 am
Tremendous issues here. I’m very happy to see
your article. Thank you a lot and I am having a look ahead
to contact you. Will you kindly drop me a e-mail?
Visit
20 Oct 25 at 2:27 am
купить диплом в новомосковске [url=http://rudik-diplom6.ru]купить диплом в новомосковске[/url] .
Diplomi_izKr
20 Oct 25 at 2:27 am
You ought to take part in a contest for one of the highest quality blogs on the web.
I am going to highly recommend this site!
هزینه طراحی سایت پزشکی ۱۴۰۴
20 Oct 25 at 2:28 am
купить диплом с реестром спб [url=https://frei-diplom2.ru/]купить диплом с реестром спб[/url] .
Diplomi_uwEa
20 Oct 25 at 2:28 am
Exceptional post however I was wanting to know if you could write a litte
more on this topic? I’d be very grateful if you could
elaborate a little bit further. Thank you!
betflik 199
20 Oct 25 at 2:29 am
buying cheap feldene
where to get cheap feldene
20 Oct 25 at 2:29 am
прогнозы и ставки на хоккей [url=https://luchshie-prognozy-na-khokkej8.ru/]luchshie-prognozy-na-khokkej8.ru[/url] .
lychshie prognozi na hokkei_ibEi
20 Oct 25 at 2:30 am
I have been surfing online more than 3 hours today, yet I never found any interesting article
like yours. It is pretty worth enough for me. Personally, if all webmasters and
bloggers made good content as you did, the internet will be a lot more useful than ever before.
medical grade wellness
20 Oct 25 at 2:30 am
Наркологическая помощь в Саратове 24/7 — быстрый выезд врача, помощь при запое и зависимостях, лечение анонимно. Подробнее на Damki.biz Разобраться лучше – http://adalat.borda.ru/?1-4-0-00000513-000-0-0-1756815530
Crystaldum
20 Oct 25 at 2:30 am
Sou viciado em BETesporte Casino, e uma plataforma que pulsa com emocao atletica. A selecao de jogos e fenomenal, com slots modernos e tematicos. Com uma oferta inicial para impulsionar. O servico esta disponivel 24/7, sempre pronto para o jogo. Os saques sao rapidos como um sprint, contudo ofertas mais generosas dariam um toque especial. Em resumo, BETesporte Casino e indispensavel para apostadores para fas de cassino online ! Adicionalmente o site e veloz e envolvente, adiciona um toque de estrategia. Igualmente impressionante os pagamentos seguros em cripto, assegura transacoes confiaveis.
Verificar isso|
FutebolFogoM4zef
20 Oct 25 at 2:31 am
сколько стоит проект перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry11.ru/]сколько стоит проект перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_odot
20 Oct 25 at 2:31 am
доставка алкоголя на дом москва круглосуточно [url=https://alcoygoloc.ru/]https://alcoygoloc.ru/[/url] .
dostavka alkogolya_cwki
20 Oct 25 at 2:31 am
Joined $MTAUR coin rush—bonuses galore. ICO’s whitepaper thorough. Endless fun ahead.
minotaurus token
WilliamPargy
20 Oct 25 at 2:32 am
диплом колледжа купить в [url=http://www.frei-diplom9.ru]http://www.frei-diplom9.ru[/url] .
Diplomi_okea
20 Oct 25 at 2:32 am