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=www.rudik-diplom7.ru]купить диплом в новороссийске[/url] .
Diplomi_yiPl
14 Oct 25 at 3:26 am
https://reality38261.blogzet.com/detox-examen-de-orina-cosas-que-debe-saber-antes-de-comprar-52593947
Purificacion para examen de muestra se ha transformado en una solucion cada vez mas conocida entre personas que requieren eliminar toxinas del organismo y superar pruebas de deteccion de drogas. Estos productos estan disenados para facilitar a los consumidores a depurar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el uso de cannabis u otras sustancias.
Un buen detox para examen de fluido debe proporcionar resultados rapidos y efectivos, en especial cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas variedades, pero no todas prometen un proceso seguro o rapido.
De que funciona un producto detox? En terminos simples, estos suplementos funcionan acelerando la depuracion de metabolitos y residuos a traves de la orina, reduciendo su presencia hasta quedar por debajo del nivel de deteccion de ciertos tests. Algunos actuan en cuestion de horas y su impacto puede durar entre 4 a seis horas.
Parece fundamental combinar estos productos con adecuada hidratacion. Beber al menos dos litros de agua por jornada antes y despues del consumo del detox puede mejorar los resultados. Ademas, se aconseja evitar alimentos pesados y bebidas azucaradas durante el proceso de uso.
Los mejores productos de detox para orina incluyen ingredientes como extractos de naturales, vitaminas del complejo B y minerales que respaldan el funcionamiento de los rinones y la funcion hepatica. Entre las marcas mas destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de eficacia.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con margenes de accion largas o iniciar una preparacion anticipada. Mientras mas prolongada sea la abstinencia, mayor sera la efectividad del producto. Por eso, combinar la planificacion con el uso correcto del producto es clave.
Un error comun es pensar que todos los detox actuan lo mismo. Existen diferencias en formulacion, sabor, metodo de uso y duracion del impacto. Algunos vienen en envase 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 adecuado.
Por ultimo, es importante recalcar que ninguno detox garantiza 100% de exito. Siempre hay variables biologicas como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir las instrucciones del fabricante y no descuidarse.
JuniorShido
14 Oct 25 at 3:27 am
алюминиевые электрожалюзи [url=https://zhalyuzi-s-elektroprivodom77.ru/]https://zhalyuzi-s-elektroprivodom77.ru/[/url] .
jaluzi na okna s elektroprivodom_hgpa
14 Oct 25 at 3:27 am
карниз электроприводом штор купить [url=http://karniz-elektroprivodom.ru]http://karniz-elektroprivodom.ru[/url] .
karniz elektroprivodom shtor kypit_zqei
14 Oct 25 at 3:28 am
что будет если купить диплом о высшем образовании с занесением в реестр [url=www.frei-diplom1.ru/]что будет если купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_elOi
14 Oct 25 at 3:29 am
When someone writes an piece of writing he/she keeps the image of a user in his/her mind that how a user can be aware of it.
Therefore that’s why this piece of writing is perfect.
Thanks!
плосковеточник на участке
14 Oct 25 at 3:29 am
Mandingo
Brentsek
14 Oct 25 at 3:30 am
купить диплом во владимире [url=www.rudik-diplom10.ru/]купить диплом во владимире[/url] .
Diplomi_zxSa
14 Oct 25 at 3:31 am
порядок согласования перепланировки нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/[/url] .
pereplanirovka nejilogo pomesheniya_zmer
14 Oct 25 at 3:31 am
проект перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]проект перепланировки нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_weer
14 Oct 25 at 3:33 am
обслуживание мини экскаватора [url=https://www.arenda-mini-ekskavatora-v-moskve-2.ru]https://www.arenda-mini-ekskavatora-v-moskve-2.ru[/url] .
arenda mini ekskavatora v moskve_adKt
14 Oct 25 at 3:33 am
рулонные шторы на окна цена [url=https://rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на окна цена[/url] .
rylonnaya shtora s elektroprivodom_zgKt
14 Oct 25 at 3:35 am
Howdy! I could have sworn I’ve been to this blog before but after browsing through some
of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found
it and I’ll be book-marking and checking back often!
kylesfootballcards
14 Oct 25 at 3:35 am
As the admin of this web page is working, no hesitation very rapidly it will be
famous, due to its feature contents.
boobs
14 Oct 25 at 3:37 am
перепланировка нежилого помещения в москве [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_clSr
14 Oct 25 at 3:37 am
купить диплом с занесением в реестр тюмень [url=https://frei-diplom1.ru]купить диплом с занесением в реестр тюмень[/url] .
Diplomi_rdOi
14 Oct 25 at 3:38 am
мини экскаватор услуги [url=arenda-mini-ekskavatora-v-moskve-2.ru]arenda-mini-ekskavatora-v-moskve-2.ru[/url] .
arenda mini ekskavatora v moskve_rcKt
14 Oct 25 at 3:39 am
электрокарнизы купить в москве [url=www.karniz-shtor-elektroprivodom.ru/]электрокарнизы купить в москве[/url] .
karniz dlya shtor s elektroprivodom_pper
14 Oct 25 at 3:40 am
карнизы для штор с электроприводом [url=http://karniz-elektroprivodom.ru/]карнизы для штор с электроприводом[/url] .
karniz elektroprivodom shtor kypit_mmei
14 Oct 25 at 3:40 am
I am sure this paragraph has touched all the internet users, its really really nice article on building up new web site.
dark web hosting for businesses
14 Oct 25 at 3:40 am
Получить диплом о высшем образовании поспособствуем. Купить аттестат в Барнауле – [url=http://diplomybox.com/kupit-attestat-v-barnaule/]diplomybox.com/kupit-attestat-v-barnaule[/url]
Cazrurp
14 Oct 25 at 3:41 am
Описание
Получить больше информации – [url=https://vyvod-iz-zapoya-odincovo6.ru/]вывод из запоя[/url]
ArturoHow
14 Oct 25 at 3:41 am
бамбуковые электрожалюзи [url=http://zhalyuzi-s-elektroprivodom77.ru/]http://zhalyuzi-s-elektroprivodom77.ru/[/url] .
jaluzi na okna s elektroprivodom_okpa
14 Oct 25 at 3:41 am
согласование перепланировки в нежилом помещении [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_heer
14 Oct 25 at 3:41 am
купить диплом в евпатории [url=www.rudik-diplom7.ru]купить диплом в евпатории[/url] .
Diplomi_ppPl
14 Oct 25 at 3:42 am
проект перепланировки нежилого помещения стоимость [url=http://pereplanirovka-nezhilogo-pomeshcheniya10.ru]http://pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_loSr
14 Oct 25 at 3:42 am
компания потолочкин [url=https://natyazhnye-potolki-samara-1.ru]https://natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_eqor
14 Oct 25 at 3:44 am
купить диплом педагога [url=www.rudik-diplom10.ru]купить диплом педагога[/url] .
Diplomi_zrSa
14 Oct 25 at 3:44 am
Основные услуги наркологической помощи
Получить дополнительные сведения – [url=https://narkologicheskaya-pomoshch-domodedovo6.ru/]narkologicheskaya-pomoshch-domodedovo[/url]
EugeneOrask
14 Oct 25 at 3:45 am
I’ve been following the Minotaurus presale closely, and it’s impressive how they’ve structured the tokenomics for long-term sustainability. The vesting bonuses are a smart incentive that could really reward patient holders. Excited to see $MTAUR launch and disrupt the blockchain gaming space.
minotaurus ico
WilliamPargy
14 Oct 25 at 3:45 am
узаконивание перепланировки нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]узаконивание перепланировки нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_ceer
14 Oct 25 at 3:46 am
рулонные шторы с электроприводом на пластиковые окна [url=www.rulonnaya-shtora-s-elektroprivodom.ru]www.rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_alKt
14 Oct 25 at 3:48 am
Minotaurus ICO details are out, and the referral program is genius for building community fast. I’ve already invited a few friends, and the bonuses are stacking up nicely. This could be the next big play-to-earn gem in 2025.
minotaurus token
WilliamPargy
14 Oct 25 at 3:48 am
купить диплом в петропавловске-камчатском [url=www.rudik-diplom7.ru/]купить диплом в петропавловске-камчатском[/url] .
Diplomi_wpPl
14 Oct 25 at 3:49 am
горизонтальные жалюзи с электроприводом [url=www.zhalyuzi-s-elektroprivodom77.ru/]горизонтальные жалюзи с электроприводом[/url] .
jaluzi na okna s elektroprivodom_ippa
14 Oct 25 at 3:50 am
купить диплом техникума украина [url=frei-diplom8.ru]купить диплом техникума украина[/url] .
Diplomi_xosr
14 Oct 25 at 3:51 am
What i don’t understood is in truth how you are not really a lot more neatly-preferred than you might
be right now. You’re so intelligent. You already know therefore
considerably in terms of this topic, produced me personally imagine it
from a lot of numerous angles. Its like women and men aren’t involved until
it’s one thing to accomplish with Woman gaga!
Your own stuffs outstanding. All the time maintain it up!
singapore services
14 Oct 25 at 3:51 am
натяжные потолки потолочкин отзывы [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_eokl
14 Oct 25 at 3:51 am
потолочкин самара [url=www.stretch-ceilings-samara-1.ru/]www.stretch-ceilings-samara-1.ru/[/url] .
natyajnie potolki samara_utsl
14 Oct 25 at 3:52 am
В наше динамичное время, насыщенное напряжением и беспокойством, анксиолитики и транквилизаторы оказались надежным средством для огромного количества людей, позволяя преодолевать панические приступы, генерализованную тревогу и прочие нарушения, мешающие нормальной жизни. Эти препараты, такие как бензодиазепины (диазепам, алпразолам) или небензодиазепиновые варианты вроде буспирона, действуют через усиление эффекта ГАМК в мозге, снижая нейрональную активность и принося облегчение уже через короткое время. Они особенно ценны в начале курса антидепрессантов, поскольку смягчают стартовые нежелательные реакции, вроде усиленной раздражительности или проблем со сном, повышая удобство и результативность терапии. Но стоит учитывать возможные опасности: от сонливости и ухудшения внимания до риска привыкания, из-за чего их прописывают на ограниченный период под тщательным медицинским надзором. В центре “Эмпатия” опытные специалисты, включая психиатров и психотерапевтов, подбирают индивидуальные схемы, минимизируя противопоказания вроде проблем с дыханием или беременности. Подробнее о механизмах, применении и безопасном использовании читайте на https://empathycenter.ru/articles/anksiolitiki-i-trankvilizatory/ , где собрана вся актуальная информация для вашего спокойствия.
vuctcDooms
14 Oct 25 at 3:52 am
купить диплом в железногорске [url=rudik-diplom10.ru]rudik-diplom10.ru[/url] .
Diplomi_mdSa
14 Oct 25 at 3:52 am
Наркологическая клиника в Омске специализируется на оказании профессиональной помощи людям, столкнувшимся с зависимостью от алкоголя и наркотиков. Лечение строится на принципах доказательной медицины и сочетает современные методы детоксикации, фармакотерапии, психотерапевтической поддержки и программ социальной адаптации. Комплексный подход позволяет пациентам не только стабилизировать состояние, но и вернуться к полноценной жизни без зависимости.
Подробнее тут – http://narkologicheskaya-klinika-v-omske0.ru/narkologicheskaya-bolnicza-omsk/
Davidfarie
14 Oct 25 at 3:52 am
порядок согласования перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru]https://pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_nxer
14 Oct 25 at 3:53 am
электрокарнизы цена [url=www.karniz-shtor-elektroprivodom.ru]электрокарнизы цена[/url] .
karniz dlya shtor s elektroprivodom_hner
14 Oct 25 at 3:54 am
потолочкин натяжные потолки самара [url=https://natyazhnye-potolki-samara-2.ru/]natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_xgPi
14 Oct 25 at 3:56 am
переустройство нежилого помещения [url=www.pereplanirovka-nezhilogo-pomeshcheniya11.ru/]переустройство нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_gqer
14 Oct 25 at 3:57 am
электрокарниз [url=karniz-elektroprivodom.ru]электрокарниз[/url] .
karniz elektroprivodom shtor kypit_hcei
14 Oct 25 at 3:58 am
Hiya! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly?
My blog looks weird when viewing from my iphone 4. I’m trying to find
a template or plugin that might be able to correct this problem.
If you have any suggestions, please share. Thank you!
лост мэри
14 Oct 25 at 3:58 am
купить диплом в кызыле [url=http://www.rudik-diplom7.ru]купить диплом в кызыле[/url] .
Diplomi_ehPl
14 Oct 25 at 3:59 am
купить старый диплом техникума в спб [url=https://www.frei-diplom8.ru]купить старый диплом техникума в спб[/url] .
Diplomi_iisr
14 Oct 25 at 4:02 am