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!
https://www.blogger.com/profile/03880422133551082712
Superar un control sorpresa puede ser estresante. Por eso, se ha creado un suplemento innovador desarrollada en Canada.
Su formula unica combina vitaminas, lo que prepara tu organismo y neutraliza temporalmente los marcadores de toxinas. El resultado: una muestra limpia, lista para entregar tranquilidad.
Lo mas valioso es su accion rapida en menos de 2 horas. A diferencia de detox irreales, no promete resultados permanentes, sino una herramienta puntual que funciona cuando lo necesitas.
Estos suplementos están diseñados para ayudar a los consumidores a limpiar su cuerpo de residuos no deseadas, especialmente las relacionadas con el consumo de cannabis u otras drogas.
El buen detox para examen de orina debe brindar resultados rápidos y efectivos, en gran cuando el tiempo para desintoxicarse es limitado. En el mercado actual, hay muchas variedades, pero no todas prometen un proceso seguro o efectivo.
De qué funciona un producto detox? En términos básicos, estos suplementos funcionan acelerando la depuración de metabolitos y componentes a través de la orina, reduciendo su concentración hasta quedar por debajo del límite de detección de algunos tests. Algunos trabajan en cuestión de horas y su acción puede durar entre 4 a 6 horas.
Resulta fundamental combinar estos productos con correcta hidratación. Beber al menos 2 litros de agua por jornada antes y después del ingesta del detox puede mejorar los resultados. Además, se aconseja evitar alimentos grasos y bebidas procesadas durante el proceso de desintoxicación.
Los mejores productos de detox para orina incluyen ingredientes como extractos de plantas, vitaminas del complejo B y minerales que favorecen el funcionamiento de los sistemas y la función hepática. Entre las marcas más destacadas, se encuentran aquellas que presentan certificaciones sanitarias y estudios de eficacia.
Para usuarios frecuentes de THC, se recomienda usar detoxes con ventanas de acción largas o iniciar una preparación temprana. Mientras más larga sea la abstinencia, mayor será la potencia del producto. Por eso, combinar la disciplina con el uso correcto del producto es clave.
Un error común es creer que todos los detox actúan igual. Existen diferencias en dosis, sabor, método de uso y duración del impacto. Algunos vienen en envase líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que incorporan fases de preparación o purga previa al día del examen. Estos programas suelen instruir abstinencia, buena alimentación y descanso adecuado.
Por último, es importante recalcar que todo detox garantiza 100% de éxito. Siempre hay variables personales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no relajarse.
Miles de estudiantes ya han comprobado su efectividad. Testimonios reales mencionan paquetes 100% confidenciales.
Si necesitas asegurar tu resultado, esta solucion te ofrece seguridad.
JuniorShido
13 Oct 25 at 4:09 am
Je suis entierement obsede par Locowin Casino, c’est une plateforme qui explose d’energie. Il y a une profusion de jeux captivants, comprenant des jeux adaptes aux cryptos. Renforcant l’experience de depart. Le service est operationnel 24/7, proposant des reponses limpides. La procedure est aisee et efficace, cependant des offres plus liberales ajouteraient de la valeur. En fin de compte, Locowin Casino garantit du divertissement constant pour les adeptes de sensations intenses ! Ajoutons que la plateforme est esthetiquement remarquable, ajoute un confort notable. Un plus significatif les tournois periodiques pour la rivalite, qui stimule l’engagement.
Explorer les dГ©tails|
NeonPulseG5zef
13 Oct 25 at 4:11 am
где купить диплом образование [url=http://www.rudik-diplom2.ru]где купить диплом образование[/url] .
Diplomi_ixpi
13 Oct 25 at 4:12 am
купить диплом техникума ссср в мурманске [url=frei-diplom8.ru]купить диплом техникума ссср в мурманске[/url] .
Diplomi_sosr
13 Oct 25 at 4:12 am
1win promo qeydiyyat [url=https://1win5004.com]1win promo qeydiyyat[/url]
1win_vpoi
13 Oct 25 at 4:13 am
купить диплом ижевск с занесением в реестр [url=frei-diplom3.ru]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_swKt
13 Oct 25 at 4:15 am
Saya menyukai artikel ini karena menyajikan informasi seimbang antara KUBET
dan Situs Judi Bola Terlengkap.
Penulis tidak hanya fokus pada satu sisi, tetapi juga memberikan gambaran umum mengenai Situs Mix Parlay, Situs Parlay Resmi,
serta situs parlay secara keseluruhan.
Informasi tentang toto macau dan kubet login juga menambah wawasan pembaca tentang
tren digital saat ini.
Situs Judi Bola Terlengkap
13 Oct 25 at 4:15 am
certainly like your web-site however you have to check the spelling
on quite a few of your posts. Many of them are rife with spelling issues and I to find it very bothersome to inform the reality then again I’ll definitely come back again.
broken biscuit wholesaler
13 Oct 25 at 4:18 am
купить диплом продавца [url=https://rudik-diplom2.ru]купить диплом продавца[/url] .
Diplomi_eqpi
13 Oct 25 at 4:19 am
купить диплом об окончании колледжа [url=http://frei-diplom8.ru/]купить диплом об окончании колледжа[/url] .
Diplomi_jjsr
13 Oct 25 at 4:21 am
Стоп нарко форум — дискуссионная площадка Stop-Narcology с тематическими ветками по алкоголизму, наркоманиям и сопутствующим расстройствам; здесь публикуются разборы случаев, памятки для близких и ответы специалистов.
Ознакомиться с деталями – [url=https://stop-narcology.ru/article/benzodiazepiny-effektivnost-protivorechiya-i-skrytye-ugrozy/]бензодиазепины список препаратов[/url]
Bettybog
13 Oct 25 at 4:21 am
купить диплом с занесением в реестры [url=http://www.frei-diplom3.ru]купить диплом с занесением в реестры[/url] .
Diplomi_lnKt
13 Oct 25 at 4:23 am
купить проведенный диплом всеми [url=http://frei-diplom2.ru]купить проведенный диплом всеми[/url] .
Diplomi_akEa
13 Oct 25 at 4:24 am
купить медицинский диплом медсестры [url=http://frei-diplom14.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_ngoi
13 Oct 25 at 4:25 am
https://s-resheniya.ru
RandyEluse
13 Oct 25 at 4:25 am
диплом высшего образования с занесением в реестр купить [url=https://frei-diplom3.ru/]диплом высшего образования с занесением в реестр купить[/url] .
Diplomi_piKt
13 Oct 25 at 4:28 am
купить старый диплом техникума [url=frei-diplom8.ru]купить старый диплом техникума[/url] .
Diplomi_uzsr
13 Oct 25 at 4:29 am
Je suis impressionne par Locowin Casino, il delivre une experience unique. La diversite des titres est epoustouflante, incluant des paris sportifs electrisants. Renforcant l’experience de depart. L’aide est performante et experte, accessible a tout instant. La procedure est aisee et efficace, cependant des bonus plus diversifies seraient souhaitables. Pour synthetiser, Locowin Casino est une plateforme qui excelle pour les joueurs a la recherche d’aventure ! En outre la navigation est simple et engageante, facilite une immersion complete. A souligner aussi le programme VIP avec des niveaux exclusifs, garantit des transactions securisees.
Entrer sur le site web|
EnigmaReelD5zef
13 Oct 25 at 4:30 am
Ты игрок в CS2 или КС ГО? Если тебе надоели твои обыные скины и ты хочешь продать их и вывести деньги себе на карту, то для этого существуют специальные сайты, которые помогают с этим. ТУТ: сайт для вывода скинов кс го в деньги ты сможешь реализовать свои скины вывести деньги на карту в течение 10 минут.
Lamarduh
13 Oct 25 at 4:30 am
купить vip диплом техникума ссср [url=www.frei-diplom9.ru]купить vip диплом техникума ссср[/url] .
Diplomi_pjea
13 Oct 25 at 4:31 am
1win aviator demo [url=http://1win5005.com/]http://1win5005.com/[/url]
1win_qpml
13 Oct 25 at 4:32 am
Asking questions are in fact good thing if you are not understanding something fully, except this piece of writing provides pleasant understanding yet.
speculoos biscuit crumb manufacturer
13 Oct 25 at 4:32 am
купить диплом средне техническое [url=www.rudik-diplom7.ru]купить диплом средне техническое[/url] .
Diplomi_quPl
13 Oct 25 at 4:34 am
https://medreliefuk.shop/# buy corticosteroids without prescription UK
HerbertScacy
13 Oct 25 at 4:38 am
https://communication15662.tinyblogging.com/poco-conocidos-hechos-sobre-detox-examen-de-orina-81698763
Detox para examen de orina se ha convertido en una solucion cada vez mas conocida entre personas que requieren eliminar toxinas del cuerpo y superar pruebas de test de drogas. Estos suplementos estan disenados para facilitar a los consumidores a purgar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el uso de cannabis u otras sustancias ilicitas.
Uno buen detox para examen de pipi debe ofrecer resultados rapidos y confiables, en gran cuando el tiempo para desintoxicarse es limitado. En el mercado actual, hay muchas variedades, pero no todas aseguran un proceso seguro o fiable.
?Como funciona un producto detox? En terminos simples, estos suplementos actuan acelerando la expulsion de metabolitos y componentes a traves de la orina, reduciendo su concentracion hasta quedar por debajo del nivel de deteccion de los tests. Algunos funcionan en cuestion de horas y su efecto puede durar entre 4 a seis horas.
Parece fundamental combinar estos productos con adecuada hidratacion. Beber al menos par litros de agua por jornada antes y despues del ingesta del detox puede mejorar los beneficios. Ademas, se recomienda evitar alimentos pesados y bebidas procesadas durante el proceso de desintoxicacion.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de plantas, vitaminas del tipo B y minerales que apoyan el funcionamiento de los rinones y la funcion hepatica. Entre las marcas mas destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de prueba.
Para usuarios frecuentes de cannabis, se recomienda usar detoxes con margenes de accion largas o iniciar una preparacion anticipada. Mientras mas extendida sea la abstinencia, mayor sera la efectividad del producto. Por eso, combinar la planificacion con el uso correcto del suplemento es clave.
Un error comun es creer que todos los detox actuan igual. Existen diferencias en dosis, sabor, metodo de ingesta y duracion del efecto. Algunos vienen en formato liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que incluyen fases de preparacion o preparacion 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 biologicas como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no confiarse.
JuniorShido
13 Oct 25 at 4:39 am
купить диплом в бугульме [url=http://rudik-diplom2.ru]купить диплом в бугульме[/url] .
Diplomi_cipi
13 Oct 25 at 4:40 am
купить диплом техникума ссср в нижнем новгороде [url=http://www.frei-diplom9.ru]купить диплом техникума ссср в нижнем новгороде[/url] .
Diplomi_qpea
13 Oct 25 at 4:41 am
Minotaurus coin’s ecosystem fun-focused. ICO’s legal green light. DAO votes exciting.
mtaur token
WilliamPargy
13 Oct 25 at 4:42 am
купить диплом в соликамске [url=www.rudik-diplom7.ru/]купить диплом в соликамске[/url] .
Diplomi_hpPl
13 Oct 25 at 4:43 am
платный психиатр на дом в москве
psychiatr-moskva008.ru
консультация врача психиатра
psihmskNeT
13 Oct 25 at 4:45 am
Xanax hilft bei Panikattacken, birgt aber Abhangigkeitsrisiken. Konsultieren Sie einen Arzt vor der Einnahme.
Lioresal
ThomasInvag
13 Oct 25 at 4:46 am
Just grabbed some $MTAUR coins during the presale—feels like getting in on the ground floor of something huge. The audited smart contracts give me peace of mind, unlike sketchier projects. Can’t wait for the game beta to test those power-ups.
minotaurus ico
WilliamPargy
13 Oct 25 at 4:46 am
купить диплом техникума в сочи [url=https://frei-diplom9.ru/]купить диплом техникума в сочи[/url] .
Diplomi_beea
13 Oct 25 at 4:47 am
купить диплом в муроме [url=http://www.rudik-diplom7.ru]купить диплом в муроме[/url] .
Diplomi_vaPl
13 Oct 25 at 4:49 am
1win az aviator [url=https://www.1win5004.com]https://www.1win5004.com[/url]
1win_ckoi
13 Oct 25 at 4:49 am
купить диплом с занесением в реестр новосибирск [url=http://www.frei-diplom3.ru]купить диплом с занесением в реестр новосибирск[/url] .
Diplomi_nuKt
13 Oct 25 at 4:50 am
можно купить диплом медсестры [url=http://frei-diplom15.ru/]можно купить диплом медсестры[/url] .
Diplomi_rxoi
13 Oct 25 at 4:51 am
купить диплом с внесением в реестр [url=https://frei-diplom2.ru]купить диплом с внесением в реестр[/url] .
Diplomi_onEa
13 Oct 25 at 4:52 am
https://killjack.ru
RandyEluse
13 Oct 25 at 4:52 am
диплом техникума с отличием купить [url=http://www.frei-diplom8.ru]диплом техникума с отличием купить[/url] .
Diplomi_yhsr
13 Oct 25 at 4:52 am
Discover Bangkok’s finest Nuru and erotic massage experience.
Indulge in sensual VIP and soapy massages with a happy ending
in a private, elegant spa. Real photos,
real therapists, ultimate relaxation.
nuru massage
13 Oct 25 at 4:54 am
купить проведенный диплом отзывы [url=https://frei-diplom1.ru/]https://frei-diplom1.ru/[/url] .
Diplomi_yfOi
13 Oct 25 at 4:58 am
купить диплом в ставрополе [url=https://rudik-diplom2.ru/]купить диплом в ставрополе[/url] .
Diplomi_rtpi
13 Oct 25 at 4:58 am
купить диплом регистрацией [url=http://frei-diplom2.ru/]купить диплом регистрацией[/url] .
Diplomi_lxEa
13 Oct 25 at 5:00 am
درود کاربران، راجع به پلتفرمهای شرطبندی فکر نکنید؛ آنها سایتها مملو از خطرات اقتصادی،
عصبی و روابطی هستند. یکی از آشنایانم به یک کلیک
همه چیزام را از دست داد کردم.
وابستگی نسبت به آنها فعالیتها سریعتر از
آن که ذهن میکنید رشد مینماید.
اصلاً درگیر نخواهید شد!
کلاهبرداری سایت قمار
13 Oct 25 at 5:00 am
Ты игрок в CS2 или КС ГО? Если тебе надоели твои обыные скины и ты хочешь продать их и вывести деньги себе на карту, то для этого существуют специальные сайты, которые помогают с этим. ТУТ: вывод скино кс го ты сможешь реализовать свои скины вывести деньги на карту в течение 10 минут.
Lamarduh
13 Oct 25 at 5:02 am
аренда экскаваторов погрузчиков [url=www.arenda-ekskavatora-pogruzchika-cena-2.ru]аренда экскаваторов погрузчиков[/url] .
arenda ekskavatora pogryzchika cena_xgst
13 Oct 25 at 5:03 am
Ты игрок в CS2 или КС ГО? Если тебе надоели твои обыные скины и ты хочешь продать их и вывести деньги себе на карту, то для этого существуют специальные сайты, которые помогают с этим. ТУТ: вывод скино кс го ты сможешь реализовать свои скины вывести деньги на карту в течение 10 минут.
Lamarduh
13 Oct 25 at 5:04 am
купить диплом в череповце [url=https://rudik-diplom2.ru/]https://rudik-diplom2.ru/[/url] .
Diplomi_repi
13 Oct 25 at 5:08 am
купить диплом о техническом образовании с занесением в реестр [url=https://www.frei-diplom3.ru]https://www.frei-diplom3.ru[/url] .
Diplomi_diKt
13 Oct 25 at 5:08 am