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!
бонусный счет 1win как использовать [url=https://1win5518.ru/]https://1win5518.ru/[/url]
1win_kg_jykl
23 Oct 25 at 6:17 pm
После поступления вызова нарколог клиники «АльфаНаркология» оперативно выезжает по указанному адресу. На месте врач проводит первичную диагностику, оценивая степень интоксикации, физическое и психологическое состояние пациента. По результатам осмотра врач подбирает индивидуальный комплекс лечебных процедур, в который входит постановка капельницы с растворами для детоксикации, препараты для стабилизации работы органов и нормализации психического состояния.
Узнать больше – [url=https://narcolog-na-dom-sankt-peterburg000.ru/]вызвать нарколога на дом санкт-петербург[/url]
TerryCaf
23 Oct 25 at 6:19 pm
https://omaranhense.com/codigo-promocional-1xbet-bonus-vip-130-eur/
othkfbe
23 Oct 25 at 6:19 pm
1 x bet giri? [url=https://1xbet-giris-8.com/]1xbet-giris-8.com[/url] .
1xbet giris_fxPn
23 Oct 25 at 6:19 pm
Every weekend i used to visit this web page, because i want enjoyment, for the reason that this this web page conations
truly fastidious funny material too.
ankara kürtaj
23 Oct 25 at 6:19 pm
I visited various web sites except the audio feature for audio songs existing at this site is in fact marvelous.
homepage
23 Oct 25 at 6:20 pm
http://mannensapotek.com/# kopa Viagra online Sverige
Hermanereli
23 Oct 25 at 6:23 pm
Сотрудничаем по импорту оборудования, брокер всегда решает вопросы оперативно https://tamozhenniiy-broker-moskva11.ru/
NathanDax
23 Oct 25 at 6:24 pm
Thanks for sharing your info. I truly appreciate your
efforts and I will be waiting for your next write ups thank
you once again.
techtra Malaysia
23 Oct 25 at 6:25 pm
1x lite [url=http://1xbet-giris-1.com]http://1xbet-giris-1.com[/url] .
1xbet giris_njkt
23 Oct 25 at 6:26 pm
диплом медсестры с аккредитацией купить [url=http://frei-diplom14.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_iyoi
23 Oct 25 at 6:27 pm
1xbet giri? [url=https://1xbet-giris-6.com/]1xbet giri?[/url] .
1xbet giris_bhsl
23 Oct 25 at 6:28 pm
Грамотно консультируют по документам, всегда отвечают на вопросы https://tamozhenniiy-broker-moskva.ru/
NathanDax
23 Oct 25 at 6:28 pm
займ без переплат https://zaimy-78.ru
denezhnyy-zaym-940
23 Oct 25 at 6:29 pm
взять займ на карту https://zaimy-76.ru
zaym vzyat 957
23 Oct 25 at 6:29 pm
Hello colleagues, how is everything, and what you wish for to say concerning this piece of writing, in my view its actually remarkable in favor of me.
cat casino
GichardMam
23 Oct 25 at 6:29 pm
займ деньги сразу https://zaimy-73.ru
zaimy-vsem-659
23 Oct 25 at 6:30 pm
onlineapotek för män: köp receptfria potensmedel online – MannensApotek
Jesuskax
23 Oct 25 at 6:30 pm
1x bet giri? [url=1xbet-giris-4.com]1xbet-giris-4.com[/url] .
1xbet giris_bwSa
23 Oct 25 at 6:31 pm
Folks, fear tһe gap hor, gooԁ establishments offer strategy activities, sharpening tactics ffor commerce.
Alas, ƅetter chiong music lessons lah, cultivating skills f᧐r entertainment sector positions.
Вesides from school amenities, concentrate οn math fоr prevent typical errors including
inattentive errors іn tests.
Hey hey, Singapore moms аnd dads, mathematics remаins perhаps the extremely essential primary
topic, fostering innovation tһrough рroblem-solving for creative
jobs.
Wow, arithmetic іѕ the foundation stone fоr primary schooling, assisting hildren ᴡith spatial
reasoning ffor architecture routes.
Goodness, even ᴡhether institution proves һigh-end, math serves as thе decisive subject tо building confidence іn figures.
Goodness, no matter ѡhether institution proves atas, mathematics
serves ɑs the critical topic t᧐ developing poise with calculations.
Woodlands Primary School cultivates а favorable environment promoting comprehensive progress.
Τhe school inspires accomplishment tһrough ingenious teaching.
Zhangde Primary School fosters bilingual quality ԝith strong academics.
Ꭲhe school constructs cultural pride.
Іt’s perfect foг heritage-focused families.
Ꭺlso visit my hߋmepage; Kaizenaire Math Tuition Centres Singapore
Kaizenaire Math Tuition Centres Singapore
23 Oct 25 at 6:32 pm
1xbet [url=www.1xbet-giris-1.com/]www.1xbet-giris-1.com/[/url] .
1xbet giris_fjkt
23 Oct 25 at 6:32 pm
Экстренный вывод из запоя на дому — это управляемая медицинская последовательность, а не «сильная капельница на удачу». В наркологической клинике «КалининградМедПрофи» мы выстраиваем помощь вокруг трёх опор: безопасность, конфиденциальность и предсказуемый результат. Выездная бригада приезжает круглосуточно, работает в гражданской одежде и без опознавательных знаков, чтобы не привлекать внимания соседей. Каждое вмешательство имеет измеримую цель, окно проверки и прозрачный критерий перехода к следующему шагу. Благодаря этому темп лечения остаётся мягким, а динамика — понятной для пациента и близких.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-kaliningrad15.ru/]помощь вывод из запоя[/url]
Williammet
23 Oct 25 at 6:33 pm
Домашнее лечение уместно, если сохранён ясный контакт и стабильное дыхание, нет признаков делирия и угрожающей гемодинамики. Алгоритм выстроен так, чтобы каждая минута работала на результат. Семья видит прозрачные шаги, а у пациента появляется ощущение предсказуемости. Ниже — ориентир; по месту врач адаптирует длительности и приоритеты под возраст, сопутствующие заболевания и исходные показатели.
Разобраться лучше – [url=https://narcolog-na-dom-ekaterinburg0.ru/]нарколог на дом срочно екатеринбург[/url]
Wayneorifs
23 Oct 25 at 6:34 pm
1 xbet giri? [url=www.1xbet-giris-9.com]www.1xbet-giris-9.com[/url] .
1xbet giris_ydon
23 Oct 25 at 6:35 pm
займ с плохой кредитной лучшие займы онлайн
denezhnyy-zaym-423
23 Oct 25 at 6:36 pm
Natural cleaning recipes that work as well as store-bought chemicals https://ecofriendlystore.ru/
EcoFriendNeuct
23 Oct 25 at 6:37 pm
взять займ срочно займ на карту за несколько минут
zaym vzyat 966
23 Oct 25 at 6:37 pm
займ онлайн без отказа https://zaimy-73.ru
zaimy-vsem-139
23 Oct 25 at 6:38 pm
взять займ онлайн https://zaimy-78.ru
denezhnyy-zaym-202
23 Oct 25 at 6:39 pm
Amazing blog! Is your theme custom made or did you download
it from somewhere? A design like yours with a few simple adjustements would really make my blog stand out.
Please let me know where you got your design. With thanks
Anchor Gainlux Review
23 Oct 25 at 6:39 pm
1xbet yeni giri? adresi [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .
1xbet giris_koPt
23 Oct 25 at 6:39 pm
займ мгновенно получить онлайн займ круглосуточно
zaym vzyat 519
23 Oct 25 at 6:40 pm
займ срочно без отказа https://zaimy-73.ru
zaimy-vsem-205
23 Oct 25 at 6:41 pm
1xbet giri? adresi [url=https://1xbet-giris-5.com]1xbet giri? adresi[/url] .
1xbet giris_yhSa
23 Oct 25 at 6:41 pm
1xbet yeni adresi [url=https://www.1xbet-giris-2.com]https://www.1xbet-giris-2.com[/url] .
1xbet giris_qaPt
23 Oct 25 at 6:42 pm
bahis siteler 1xbet [url=http://1xbet-giris-4.com]bahis siteler 1xbet[/url] .
1xbet giris_moSa
23 Oct 25 at 6:42 pm
Вызывать нарколога на дом рекомендуется при следующих состояниях:
Подробнее – [url=https://narcolog-na-dom-sankt-peterburg000.ru/]нарколог капельница на дом санкт-петербург[/url]
TerryCaf
23 Oct 25 at 6:42 pm
1xbet resmi giri? [url=https://1xbet-giris-5.com]https://1xbet-giris-5.com[/url] .
1xbet giris_gySa
23 Oct 25 at 6:44 pm
займ срочно без отказа https://zaimy-78.ru
denezhnyy-zaym-653
23 Oct 25 at 6:45 pm
займ срочно мфо займ
zaym vzyat 760
23 Oct 25 at 6:46 pm
Такая система терапии позволяет охватить сразу несколько звеньев патологического процесса и ускорить выздоровление.
Подробнее тут – [url=https://narcolog-na-dom-sankt-peterburg0.ru/]вызов нарколога на дом санкт-петербург[/url]
Jamielic
23 Oct 25 at 6:46 pm
взять займ без отказа https://zaimy-73.ru
zaimy-vsem-950
23 Oct 25 at 6:47 pm
monumentremoval – The purpose is bold and the site feels deeply meaningful and timely.
Tomas Breaker
23 Oct 25 at 6:48 pm
Наркологическая клиника в Жуковском — это круглосуточная служба экстренной и плановой помощи при алкогольной, наркотической и лекарственной зависимости. Наркологическая клиника «Север-Мед» сочетает современные методики детоксикации, медикаментозного и психологического кодирования, а также комплексный подход к последующей реабилитации. Мы работаем без выходных и праздников, чтобы вы могли получить профессиональную помощь в любое время суток.
Подробнее можно узнать тут – https://narkologicheskaya-klinika-zhukovskij4.ru/platnaya-narkologicheskaya-klinika-v-zhukovskom
WilliamTromo
23 Oct 25 at 6:48 pm
1xbet t?rkiye giri? [url=http://1xbet-giris-4.com/]1xbet t?rkiye giri?[/url] .
1xbet giris_ukSa
23 Oct 25 at 6:52 pm
1xbet g?ncel giri? [url=https://www.1xbet-giris-8.com]1xbet g?ncel giri?[/url] .
1xbet giris_xfPn
23 Oct 25 at 6:52 pm
топ seo агентств мира [url=http://reiting-seo-kompaniy.ru]http://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_wqon
23 Oct 25 at 6:52 pm
Sildenafil utan recept [url=https://mannensapotek.shop/#]billig Viagra Sverige[/url] erektionspiller på nätet
Davidduese
23 Oct 25 at 6:53 pm
1xbet turkiye [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .
1xbet giris_xwSa
23 Oct 25 at 6:53 pm
Не менее опасны и психоэмоциональные нарушения, связанные с абстинентным синдромом: тревога, чувство паники, галлюцинации, нарушения координации. В тяжёлых случаях может развиться алкогольный делирий (белая горячка) со спутанностью сознания, бредовыми идеями и приступами агрессии. Самостоятельный резкий отказ от спиртного в этом состоянии чреват непредсказуемыми осложнениями вплоть до судорог и комы.
Получить больше информации – [url=https://narko-reabcentr.ru/]narko-reabcentr.ru/[/url]
MelvinPrusy
23 Oct 25 at 6:54 pm