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!
http://medreliefuk.com/# cheap prednisolone in UK
Raymondspemn
12 Oct 25 at 8:37 pm
диплом колледжа узбекистана купить [url=http://frei-diplom9.ru/]http://frei-diplom9.ru/[/url] .
Diplomi_uzea
12 Oct 25 at 8:39 pm
купить диплом регистрацией [url=https://www.frei-diplom2.ru]купить диплом регистрацией[/url] .
Diplomi_ltEa
12 Oct 25 at 8:39 pm
viagra [url=https://britpharmonline.com/#]viagra[/url] buy viagra online
Jameshoasy
12 Oct 25 at 8:43 pm
купить диплом в махачкале [url=http://rudik-diplom7.ru]купить диплом в махачкале[/url] .
Diplomi_muPl
12 Oct 25 at 8:44 pm
prednisone online
prednisone online
12 Oct 25 at 8:45 pm
https://replit.com/@candetoxblend
Superar una prueba de orina puede ser estresante. Por eso, se ha creado una alternativa confiable con respaldo internacional.
Su formula eficaz combina minerales, lo que prepara tu organismo y enmascara temporalmente los marcadores de THC. El resultado: una muestra limpia, lista para ser presentada.
Lo mas destacado es su accion rapida en menos de 2 horas. A diferencia de metodos caseros, no promete resultados permanentes, sino una estrategia de emergencia que funciona cuando lo necesitas.
Estos productos están diseñados para facilitar a los consumidores a purgar su cuerpo de sustancias no deseadas, especialmente esas relacionadas con el uso de cannabis u otras sustancias ilícitas.
Uno buen detox para examen de orina debe proporcionar resultados rápidos y confiables, en gran cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas alternativas, pero no todas garantizan un proceso seguro o fiable.
De qué funciona un producto detox? En términos simples, estos suplementos operan acelerando la eliminación de metabolitos y residuos a través de la orina, reduciendo su presencia hasta quedar por debajo del umbral de detección de algunos tests. Algunos trabajan en cuestión de horas y su acción puede durar entre 4 a cinco horas.
Es fundamental combinar estos productos con buena hidratación. Beber al menos dos litros de agua por jornada antes y después del uso del detox puede mejorar los resultados. Además, se aconseja evitar alimentos difíciles y bebidas ácidas durante el proceso de desintoxicación.
Los mejores productos de purga para orina incluyen ingredientes como extractos de plantas, vitaminas del complejo B y minerales que apoyan el funcionamiento de los órganos y la función hepática. Entre las marcas más destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de THC, se recomienda usar detoxes con tiempos de acción largas o iniciar una preparación temprana. Mientras más prolongada sea la abstinencia, mayor será la potencia del producto. Por eso, combinar la disciplina con el uso correcto del suplemento es clave.
Un error común es suponer que todos los detox actúan idéntico. Existen diferencias en dosis, sabor, método de uso y duración del resultado. Algunos vienen en envase líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que agregan fases de preparación o limpieza previa al día del examen. Estos programas suelen recomendar abstinencia, buena alimentación y descanso recomendado.
Por último, es importante recalcar que ningún detox garantiza 100% de éxito. Siempre hay variables individuales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no descuidarse.
Miles de trabajadores ya han validado su discrecion. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si no deseas dejar nada al azar, esta formula te ofrece tranquilidad.
JuniorShido
12 Oct 25 at 8:45 pm
The $MTAUR token seems like a solid pick for anyone into casual gaming with crypto twists. Navigating mazes as a minotaur while earning in-game currency sounds addictive and rewarding. With the presale offering 80% off, it’s hard not to jump in early.
mtaur token
WilliamPargy
12 Oct 25 at 8:47 pm
диплом об окончании техникума купить [url=http://frei-diplom9.ru]диплом об окончании техникума купить[/url] .
Diplomi_ryea
12 Oct 25 at 8:48 pm
prednisone online
prednisone online
12 Oct 25 at 8:50 pm
[url=https://www.hisomassage.com/]soapy massage[/url] offers a deeply sensual and relaxing body-to-body experience with premium gel and skilled therapists, designed to release stress and awaken full-body pleasure.
ThomasThest
12 Oct 25 at 8:53 pm
We only tell the facts: https://deogiricollege.org
Richardinhak
12 Oct 25 at 8:55 pm
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
Carlosenasp
12 Oct 25 at 8:55 pm
A trusted source: https://chhapai.com
Georgescock
12 Oct 25 at 8:56 pm
перепланировка в нежилом здании [url=svstrazh.forum24.ru/?1-15-0-00000267-000-0-0]svstrazh.forum24.ru/?1-15-0-00000267-000-0-0[/url] .
pereplanirovka v nejilom zdanii_plKi
12 Oct 25 at 8:57 pm
Stay up to date: https://childstrive.org
ShawnOpibe
12 Oct 25 at 8:57 pm
No lies – just facts: https://jonathanlittlepoker.com
WalterSet
12 Oct 25 at 8:58 pm
skyvertex – Impressed with the depth and clarity of their articles.
Brice Hylands
12 Oct 25 at 8:59 pm
купить диплом в москве с занесением в реестр [url=frei-diplom1.ru]купить диплом в москве с занесением в реестр[/url] .
Diplomi_tjOi
12 Oct 25 at 8:59 pm
linkcraft – Smooth browsing experience, everything loads fast and clearly.
Heriberto Libel
12 Oct 25 at 9:01 pm
1win aviator təlimat [url=www.1win5004.com]www.1win5004.com[/url]
1win_cdoi
12 Oct 25 at 9:03 pm
We check every word: https://davisa.es
Davidagome
12 Oct 25 at 9:03 pm
Principen ist ein Antibiotikum aus der Penicillin-Gruppe. Allergische Reaktionen sollten vor der Einnahme ausgeschlossen werden.
Diazepam
ThomasInvag
12 Oct 25 at 9:03 pm
согласовании перепланировки нежилых помещений [url=www.cah.forum24.ru/?1-13-0-00002795-000-0-0/]www.cah.forum24.ru/?1-13-0-00002795-000-0-0/[/url] .
pereplanirovka v nejilom zdanii_anKi
12 Oct 25 at 9:03 pm
как купить легально диплом о высшем образовании [url=https://frei-diplom3.ru/]как купить легально диплом о высшем образовании[/url] .
Diplomi_jbKt
12 Oct 25 at 9:06 pm
перепланировка в нежилом здании [url=http://cah.forum24.ru/?1-13-0-00002795-000-0-0]http://cah.forum24.ru/?1-13-0-00002795-000-0-0[/url] .
pereplanirovka v nejilom zdanii_feKi
12 Oct 25 at 9:07 pm
Ручкин — крупнейший интернет-каталог рекламных ручек с логотипом: от доступных Vivapens и Grant до статусных Parker и Waterman, оперативное нанесение (шелкография, тампо, УФ, гравировка) и быстрая доставка по РФ. На сайте https://ruchkin.ru/ видны остатки, акции и реальные цены, а горячая линия помогает с подбором под брендбук. Сборка заказа идёт под контролем качества, поэтому брак сводят к нулю. Нужно срочно к выставке или рассылке? Запустят тираж «день-в-день», предложат эко-карандаши и подарочные наборы — и всё в одном счёте.
cimiveBit
12 Oct 25 at 9:09 pm
Stunning quest there. What occurred after? Good luck!
advanced sports guide
12 Oct 25 at 9:09 pm
медсестра которая купила диплом врача [url=frei-diplom13.ru]frei-diplom13.ru[/url] .
Diplomi_mhkt
12 Oct 25 at 9:10 pm
1win az giriş bloku [url=https://1win5005.com]https://1win5005.com[/url]
1win_ldml
12 Oct 25 at 9:10 pm
เข้าสู่ระบบ UFAC4 ทางเข้าใหม่ล่าสุด เล่นคาสิโน แทงบอล สล็อตครบทุกค่าย ระบบทันสมัย ฝากถอนออโต้ภายใน 10 วินาที เว็บตรงปลอดภัย 100%
ufac4
12 Oct 25 at 9:12 pm
https://britpharmonline.com/# buy sildenafil tablets UK
HerbertScacy
12 Oct 25 at 9:12 pm
купить диплом с занесением в реестр самара [url=frei-diplom1.ru]frei-diplom1.ru[/url] .
Diplomi_vsOi
12 Oct 25 at 9:12 pm
где купить дипломы медсестры [url=http://www.frei-diplom15.ru]где купить дипломы медсестры[/url] .
Diplomi_ngoi
12 Oct 25 at 9:14 pm
Why users still make use of to read news papers when in this technological world everything is available on web?
isap kontol
12 Oct 25 at 9:15 pm
summitmedia – Their media strategy tips are very practical and usable.
Forrest Rossi
12 Oct 25 at 9:18 pm
сколько стоит купить диплом медсестры [url=https://frei-diplom13.ru]сколько стоит купить диплом медсестры[/url] .
Diplomi_hykt
12 Oct 25 at 9:18 pm
$MTAUR ICO is gaining traction over SHIB/XRP rallies. Token’s in-game convertibility ensures demand. Presale’s 1.4M USDT milestone proves it.
minotaurus presale
WilliamPargy
12 Oct 25 at 9:19 pm
перепланировка нежилого помещения [url=http://www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0]http://www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0[/url] .
pereplanirovka v nejilom zdanii_hoKi
12 Oct 25 at 9:21 pm
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
Carlosenasp
12 Oct 25 at 9:22 pm
купить диплом без занесения в реестр [url=frei-diplom1.ru]купить диплом без занесения в реестр[/url] .
Diplomi_hxOi
12 Oct 25 at 9:23 pm
кто нибудь работает медсестрой по купленному диплому [url=frei-diplom13.ru]frei-diplom13.ru[/url] .
Diplomi_dzkt
12 Oct 25 at 9:24 pm
Located in the heart of Sukhumvit, [url=https://www.hisomassage.com/]massage[/url] brings an exclusive erotic massage experience close to Bangkok’s luxury hotels and nightlife.
Louishet
12 Oct 25 at 9:25 pm
Refresh Renovation Southwest Charlotte
1251Arrow Pine Ɗr c121,
Charlotte, NC 28273, United Ꮪtates
+19803517882
conditioning Heating upgrades Air and
conditioning Heating upgrades Air and
12 Oct 25 at 9:30 pm
купить диплом с техникума [url=http://frei-diplom9.ru/]купить диплом с техникума[/url] .
Diplomi_klea
12 Oct 25 at 9:32 pm
1win qeydiyyat zamanı bonus [url=www.1win5005.com]1win qeydiyyat zamanı bonus[/url]
1win_sdml
12 Oct 25 at 9:33 pm
visionlane – Love the visuals and how everything is laid out neatly.
Sharla Kabus
12 Oct 25 at 9:37 pm
https://britmedsdirect.com/# private online pharmacy UK
HerbertScacy
12 Oct 25 at 9:38 pm
куплю диплом медсестры в москве [url=http://frei-diplom15.ru/]куплю диплом медсестры в москве[/url] .
Diplomi_axoi
12 Oct 25 at 9:40 pm
согласовании перепланировки нежилых помещений [url=https://svstrazh.forum24.ru/?1-15-0-00000267-000-0-0/]https://svstrazh.forum24.ru/?1-15-0-00000267-000-0-0/[/url] .
pereplanirovka v nejilom zdanii_ooKi
12 Oct 25 at 9:41 pm