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!
1xbet resmi sitesi [url=www.1xbet-giris-1.com/]www.1xbet-giris-1.com/[/url] .
1xbet giris_vbkt
23 Oct 25 at 6:54 pm
one x bet [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .
1xbet giris_tcPt
23 Oct 25 at 6:54 pm
купить диплом в рыбинске [url=http://rudik-diplom9.ru]http://rudik-diplom9.ru[/url] .
Diplomi_rsei
23 Oct 25 at 6:54 pm
Отличная команда, которая делает всё быстро и качественно. Работают с уважением: Таможенный брокер в Домодедово
Brianovalt
23 Oct 25 at 6:55 pm
Чтобы у пациента и близких не возникал вопрос «что дальше», мы используем карту первых часов. Она задаёт цели, действия, контроль и критерии перехода между этапами. Такой подход экономит минуты и исключает импровизации «ради уверенности».
Получить больше информации – [url=https://narkologicheskaya-klinika-v-kaliningrade15.ru/]платная наркологическая клиника в калининграде[/url]
Richarddit
23 Oct 25 at 6:55 pm
seo рейтинг [url=www.reiting-seo-kompaniy.ru/]seo рейтинг[/url] .
reiting seo kompanii_jqon
23 Oct 25 at 6:56 pm
1win букмекерская контора скачать приложение [url=http://1win5519.ru/]http://1win5519.ru/[/url]
1win_kg_irEr
23 Oct 25 at 6:56 pm
В столичном регионе доступны два основных формата лечения: выезд специалиста на дом и госпитализация в специализированный центр. Каждый вариант имеет свои особенности и показания, которые врач анализирует при первичном осмотре.
Детальнее – https://алко-избавление.рф
KennethDak
23 Oct 25 at 6:56 pm
Мы не используем «универсальные коктейли». Капельницы собираются из модулей под ведущую задачу, а поведенческая часть усиливает эффект. Окончательные назначения делает врач с учётом противопоказаний и взаимодействий; таблица ниже — ориентир для пациента и семьи.
Выяснить больше – [url=https://vyvod-iz-zapoya-murmansk15.ru/]вывод из запоя клиника мурманск[/url]
Darwingow
23 Oct 25 at 6:57 pm
Cocaine comes from coca leaves organize in South America.
While once in use accustomed to in established cure-all,
it’s now a banned substance due to its dangers. It’s
hugely addictive, unrivalled to well-being risks like heart attacks, mentally ill disorders, and severe
addiction.
кокаин
23 Oct 25 at 6:58 pm
If you are interested in US casinos, then this is definitely worth checking out. Discover the full details via the attached link:
http://brooks.e-strona.pl/online-casino-fun-and-rewards/
LeonardbrOto
23 Oct 25 at 6:59 pm
1xbetgiri? [url=https://1xbet-giris-5.com/]1xbet-giris-5.com[/url] .
1xbet giris_rgSa
23 Oct 25 at 6:59 pm
1xbet turkey [url=http://1xbet-giris-6.com]http://1xbet-giris-6.com[/url] .
1xbet giris_xosl
23 Oct 25 at 7:00 pm
1 xbet giri? [url=https://1xbet-giris-6.com]https://1xbet-giris-6.com[/url] .
1xbet giris_wrsl
23 Oct 25 at 7:03 pm
Существует ряд ситуаций, при которых домашний визит специалиста становится не просто удобным, а жизненно необходимым:
Подробнее можно узнать тут – [url=https://narcolog-na-dom-v-moskve55.ru/]помощь нарколога на дому в красногорске[/url]
DavidKab
23 Oct 25 at 7:04 pm
1xbet g?ncel giri? [url=https://1xbet-giris-1.com/]https://1xbet-giris-1.com/[/url] .
1xbet giris_apkt
23 Oct 25 at 7:05 pm
You actually make it appear really easy with your presentation however I to find this matter to be really one thing which I believe I might by no means understand.
It kind of feels too complicated and very large for
me. I’m looking forward to your subsequent publish, I’ll attempt to get the hold
of it!
photoroom mod apk full unlocked
23 Oct 25 at 7:06 pm
купить диплом в каменске-уральском [url=https://rudik-diplom9.ru/]купить диплом в каменске-уральском[/url] .
Diplomi_htei
23 Oct 25 at 7:06 pm
лучшие seo компании [url=http://reiting-seo-kompaniy.ru/]http://reiting-seo-kompaniy.ru/[/url] .
reiting seo kompanii_dmon
23 Oct 25 at 7:07 pm
1xbet giri? linki [url=http://1xbet-giris-9.com/]1xbet giri? linki[/url] .
1xbet giris_jxon
23 Oct 25 at 7:07 pm
high roller online casino
best online casinos that payout
best online craps real money
online casino real money california
23 Oct 25 at 7:09 pm
A person necessarily lend a hand to make severely
articles I might state. This is the very first time I
frequented your website page and thus far? I surprised with the research you
made to create this particular put up extraordinary. Fantastic process!
Opulatrix
23 Oct 25 at 7:10 pm
1xbet turkey [url=https://www.1xbet-giris-4.com]https://www.1xbet-giris-4.com[/url] .
1xbet giris_ziSa
23 Oct 25 at 7:11 pm
1 xbet giri? [url=1xbet-giris-6.com]1xbet-giris-6.com[/url] .
1xbet giris_evsl
23 Oct 25 at 7:12 pm
незнаю.сколько раз зака зывал , всегда приходило качество , был один момент когда был ркс 4. он был 15 минутный слабый. Но это сам реактив был такой. Он использовался как урб для добавок к другим. А так то что присылали всегда всё ровно. кач и кол..
https://hizbih.info
Встану на пробу новых веществ сочный трип со мной
Alexistum
23 Oct 25 at 7:12 pm
Ruleta online
Ruleta online Amazing777
23 Oct 25 at 7:12 pm
findyourperfectdeal – Saved a few articles for future reference; this site is becoming a favourite.
Vickie Biddy
23 Oct 25 at 7:12 pm
купить диплом в ханты-мансийске [url=https://rudik-diplom9.ru/]купить диплом в ханты-мансийске[/url] .
Diplomi_deei
23 Oct 25 at 7:13 pm
1xbet yeni giri? [url=http://1xbet-giris-5.com/]1xbet yeni giri?[/url] .
1xbet giris_iwSa
23 Oct 25 at 7:14 pm
1x lite [url=http://1xbet-giris-1.com]http://1xbet-giris-1.com[/url] .
1xbet giris_jpkt
23 Oct 25 at 7:14 pm
Для юридических лиц есть удобная отчётность и прозрачные условия: https://tamozhenniiy-predstavitel.ru/
NathanDax
23 Oct 25 at 7:17 pm
1xbet giris [url=https://1xbet-giris-6.com/]1xbet giris[/url] .
1xbet giris_hesl
23 Oct 25 at 7:18 pm
MannensApotek [url=https://mannensapotek.shop/#]mannens apotek[/url] Sildenafil-tabletter pris
Davidduese
23 Oct 25 at 7:19 pm
1xbet lite [url=www.1xbet-giris-5.com/]www.1xbet-giris-5.com/[/url] .
1xbet giris_xeSa
23 Oct 25 at 7:19 pm
mystylecorner – Love the variety of clothes here, really stylish daily finds.
Jared Pannunzio
23 Oct 25 at 7:20 pm
Сотрудничаем по импорту оборудования, брокер всегда решает вопросы оперативно, https://vkobroker.ru/
Brianovalt
23 Oct 25 at 7:20 pm
hello there and thank you for your information – I’ve certainly
picked up anything new from right here. I did however expertise some technical points using this web
site, as I experienced to reload the website many times previous to I could get it to load correctly.
I had been wondering if your web hosting is OK?
Not that I’m complaining, but sluggish loading instances times
will often affect your placement in google
and could damage your high quality score if ads and marketing with Adwords.
Well I’m adding this RSS to my e-mail and could look
out for a lot more of your respective interesting content.
Ensure that you update this again very soon.
Fidat Monvex
23 Oct 25 at 7:20 pm
1xbwt giri? [url=www.1xbet-giris-8.com/]www.1xbet-giris-8.com/[/url] .
1xbet giris_mhPn
23 Oct 25 at 7:23 pm
1x giri? [url=1xbet-giris-4.com]1xbet-giris-4.com[/url] .
1xbet giris_xmSa
23 Oct 25 at 7:23 pm
Its such as you learn my thoughts! You appear to understand a lot
about this, like you wrote the e book in it or something.
I think that you can do with some percent to pressure the message home a bit, however other than that, this is wonderful blog.
An excellent read. I’ll certainly be back.
https://catchabigone.com/
Tren Digital
23 Oct 25 at 7:24 pm
1xbet [url=http://www.1xbet-giris-2.com]1xbet[/url] .
1xbet giris_fnPt
23 Oct 25 at 7:25 pm
каталог seo агентств [url=www.reiting-seo-kompaniy.ru]www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_sjon
23 Oct 25 at 7:25 pm
1xbet tr [url=https://1xbet-giris-2.com/]1xbet tr[/url] .
1xbet giris_fyPt
23 Oct 25 at 7:28 pm
ordinare Viagra generico in modo sicuro [url=https://mediuomo.com/#]trattamento ED online Italia[/url] Medi Uomo
Davidduese
23 Oct 25 at 7:29 pm
I blog frequently and I truly appreciate your information. This
great article has truly peaked my interest. I am
going to bookmark your site and keep checking for new information about once per week.
I opted in for your Feed as well.
Ip Port Proxy
23 Oct 25 at 7:31 pm
1xbet turkey [url=https://www.1xbet-giris-6.com]https://www.1xbet-giris-6.com[/url] .
1xbet giris_yhsl
23 Oct 25 at 7:33 pm
1xbet spor bahislerinin adresi [url=www.1xbet-giris-1.com/]www.1xbet-giris-1.com/[/url] .
1xbet giris_dfkt
23 Oct 25 at 7:33 pm
Oi oi, calm lah, renowned institutions possess horticulture programs,
instructing green practices f᧐r eco positions.
Hey hey, Singapore folks, prestigious primary sets tһe atmosphere fοr discipline, guiding t᧐ consistent superiority іn ѕec institution and beyond.
Alas, without solid math іn primary school, reցardless prestigious establishment youngsters mɑy stumble in secondary equations,
ѕo build that now leh.
Wah lao, еven whether establishment remains fancy, math іs the decisive topic for
building poise іn figures.
In adɗition to establishment facilities, focus ѡith mathematics іn order to
prevent common errors including inattentive blunders ɑt exams.
Oh no, primary math educates practical implementations including budgeting,
tһerefore ensure уoᥙr kid masters tһat properly fгom early.
Eh eh, composed pom рі pi, arithmetic іs рart in the leading subjects іn primary
school, establishing groundwork tо A-Level calculus.
Compassvale Primary School develops а vibrant aгea for үoung minds tօ explore ɑnd prosper.
Ingenious teaching аnd varied activities promote holistic student development.
CHIJ Ⲟur Lady of tһе Nativity supplies ɑn encouraging environment fօr ladies’ growth.
Ԝith strong programs in arts and academics, іt fosters imagination.
Parents apprеciate itѕ commitment to all-round development.
Feel free tо surf to my web paցe – Kaizenaire math tuition singapore
Kaizenaire math tuition singapore
23 Oct 25 at 7:34 pm
seo рейтинг [url=www.reiting-seo-kompaniy.ru]seo рейтинг[/url] .
reiting seo kompanii_gyon
23 Oct 25 at 7:35 pm
1xbet tr [url=www.1xbet-giris-9.com]1xbet tr[/url] .
1xbet giris_zeon
23 Oct 25 at 7:36 pm