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!
I always spent my half an hour to read this web site’s articles or reviews
everyday along with a cup of coffee.
boyarka
4 Oct 25 at 1:02 am
What’s up, after reading this amazing article i
am also happy to share my familiarity here with mates.
XX88
4 Oct 25 at 1:02 am
купить диплом техникума в воронеже [url=frei-diplom9.ru]купить диплом техникума в воронеже[/url] .
Diplomi_nnea
4 Oct 25 at 1:03 am
сколько стоит купить диплом техникума [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_kkea
4 Oct 25 at 1:04 am
купить диплом реестр [url=www.frei-diplom2.ru/]купить диплом реестр[/url] .
Diplomi_psEa
4 Oct 25 at 1:04 am
Этот этап лечения направлен на купирование острых симптомов, связанных с абстинентным синдромом. Пациенту назначаются современные препараты, способствующие выведению токсинов, нормализации работы сердца, печени, центральной нервной системы.
Получить больше информации – http://
Josephhag
4 Oct 25 at 1:06 am
https://13win.co.com
https://13win.co.com
4 Oct 25 at 1:06 am
где купить диплом техникума собою [url=www.frei-diplom8.ru]где купить диплом техникума собою[/url] .
Diplomi_ujsr
4 Oct 25 at 1:06 am
https://epcsoft.ru
PatrickGop
4 Oct 25 at 1:08 am
Hmm is anyone else experiencing problems with the pictures on this blog loading?
I’m trying to figure out if its a problem on my end or if it’s the blog.
Any feed-back would be greatly appreciated.
Meteor Profit Legit Or Not
4 Oct 25 at 1:10 am
Woah! I’m really digging the template/theme of this website.
It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between user friendliness and visual
appeal. I must say that you’ve done a great job with this.
Also, the blog loads very fast for me on Safari.
Excellent Blog!
ket testai
4 Oct 25 at 1:12 am
Frozen Yeti 1win AZ
Andreasvek
4 Oct 25 at 1:12 am
купить диплом колледжа пермь [url=www.frei-diplom9.ru/]www.frei-diplom9.ru/[/url] .
Diplomi_lrea
4 Oct 25 at 1:12 am
купить диплом диспетчера [url=www.rudik-diplom11.ru/]купить диплом диспетчера[/url] .
Diplomi_evMi
4 Oct 25 at 1:13 am
With OMT’ѕ custom syllabus that complements tһe MOE educational program, pupils discover the charm of
logical patterns, cultivating а deep love for
math and inspiration fоr high examination ratings.
Founded іn 2013 by Mr. Justin Tan, OMT Math Tuition has assisted many students ace exams ⅼike
PSLE, Օ-Levels, and А-Levels with proven pгoblem-solving techniques.
As mathematics underpins Singapore’ѕ reputation fօr excellence in global
benchmarks lіke PISA, math tuition is key to opеning a kid’ѕ potential and securing academic benefits in thіs
core subject.
Math tuitfion іn primary school bridges spaces іn classroom learning, guaranteeing students comprehend complicated topics ѕuch as geometry and data analysis Ьefore the PSLE.
Αll natural growth νia math tuition not оnly boosts Ⲟ
Level ratings ƅut additionally ցrows abstract tһougһt skills beneficial for lifelong
discovering.
Tuition teaches mistake analysis techniques, helping junior college trainees prevent typical risks іn A Level
estimations ɑnd proofs.
OMT establishes іtself аpart ѡith a curriculum thɑt enhances MOE curriculum uѕing joint օn the internet forums for talking аbout proprietary mathematics
difficulties.
Interactive tools mаke learning fun lor, ѕο yоu remain motivated and watch yoᥙr math grades climb սp
continuously.
Tuition reveals traainees tߋ diverse concern types, broadening
tһeir readiness f᧐r uncertain Singapore mathematics
exams.
Review my web pɑge … A levels math tuition
A levels math tuition
4 Oct 25 at 1:15 am
купить диплом в дербенте [url=http://rudik-diplom7.ru/]купить диплом в дербенте[/url] .
Diplomi_agPl
4 Oct 25 at 1:16 am
купить диплом кулинарного техникума [url=http://www.frei-diplom8.ru]купить диплом кулинарного техникума[/url] .
Diplomi_lesr
4 Oct 25 at 1:16 am
купить диплом с занесением в реестр в красноярске [url=https://frei-diplom2.ru]https://frei-diplom2.ru[/url] .
Diplomi_qvEa
4 Oct 25 at 1:17 am
диплом купить техникума в новосибирске [url=http://frei-diplom9.ru]диплом купить техникума в новосибирске[/url] .
Diplomi_njea
4 Oct 25 at 1:19 am
купить диплом в новочеркасске [url=http://www.rudik-diplom10.ru]http://www.rudik-diplom10.ru[/url] .
Diplomi_hrSa
4 Oct 25 at 1:20 am
купить диплом в петрозаводске [url=rudik-diplom11.ru]купить диплом в петрозаводске[/url] .
Diplomi_qdMi
4 Oct 25 at 1:21 am
Very good article! We will be linking to this great post on our website.
Keep up the great writing.
Swap Hiprex Nx
4 Oct 25 at 1:22 am
медоборудование [url=http://www.medtehnika-msk.ru]медоборудование[/url] .
oborydovanie medicinskoe_hlpa
4 Oct 25 at 1:22 am
где лучше купить диплом техникума [url=http://frei-diplom8.ru]где лучше купить диплом техникума[/url] .
Diplomi_nksr
4 Oct 25 at 1:23 am
купить государственный диплом с занесением в реестр [url=https://frei-diplom1.ru]купить государственный диплом с занесением в реестр[/url] .
Diplomi_dgOi
4 Oct 25 at 1:23 am
В каталоге «Вип Сейфы» собраны элитные модели с акцентом на дизайн и функционал: биометрия, кодовые замки, продуманная организация внутреннего пространства. Страница https://safes.ctlx.ru указывает режим работы, форму обратной связи и позиционирование: сейф как эстетичный элемент интерьера и надежный способ защиты ценностей. Отделки — от классики до минимализма, материалы устойчивы к повреждениям, есть отсеки и выдвижные модули. Навигация простая, тексты — без лишней «воды». Уместный выбор, если важны безопасность и статус.
jorunalbourl
4 Oct 25 at 1:24 am
купить диплом историка [url=https://www.rudik-diplom7.ru]купить диплом историка[/url] .
Diplomi_soPl
4 Oct 25 at 1:25 am
Personalized advice fгom OMT’s experienced tutors helps pupils ɡеt rid
of mathematics obstacles, promoting а wholehearted link
to the subject аnd ideas fоr exams.
Experience versatile learning anytime, ɑnywhere thrօugh
OMT’s extensive online e-learning platform, featuring limitless access tօ video lessons ɑnd interactive tests.
Singapore’ѕ focus on critical analyzing mathematics highlights tһe significance of math tuition, ѡhich helps trainees develop tһe analytical abilities demanded by the nation’s forward-thinking curriculum.
Ƭhrough math tuition, trainees practice PSLE-style concerns typicallies ɑnd graphs, enhancing precision ɑnd speed ᥙnder examination conditions.
Ꮐiven thе hiցh risks of O Levels fоr high school development іn Singapore, math tuition makes the m᧐st of chances for
top grades ɑnd desired positionings.
Personalized junior college tuition aids bridge tһe gap from O Level to A Level mathematics, mɑking suгe trainees
adapt tⲟ the enhanced rigor ɑnd depth ⅽalled fοr.
Distinctly, OMT’ѕ curriculum matches tһe MOE
structure Ƅy offering modular lessons that enable foг duplicated support
of weak locations at tһe trainee’ѕ pace.
OMT’s on-ⅼine system advertises self-discipline lor, secret tо consistent study ɑnd higheг exam outcomes.
Singapore moms ɑnd dads purchase math tuition tо guarantee thеiг youngsters fulfill tһe hiɡh expectations
оf the education ѕystem for examination success.
my website :: maths tuition centre іn jurong west (world-businesses.com)
world-businesses.com
4 Oct 25 at 1:25 am
I was curious if you ever thought of changing the layout of your
website? Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so people could connect with it better.
Youve got an awful lot of text for only having one or two images.
Maybe you could space it out better?
luxury black car service
4 Oct 25 at 1:26 am
как купить легальный диплом о среднем образовании [url=frei-diplom2.ru]frei-diplom2.ru[/url] .
Diplomi_lnEa
4 Oct 25 at 1:26 am
Для безопасного и эффективного лечения дома необходимо:
Узнать больше – [url=https://narkologicheskaya-pomoshh-ufa9.ru/]наркологическая помощь на дому[/url]
LionelBok
4 Oct 25 at 1:26 am
рейтинг онлайн слотов
ScottTem
4 Oct 25 at 1:27 am
После поступления в клинику проводится осмотр, измеряется давление, оценивается общее состояние. При необходимости проводятся экспресс-анализы на содержание веществ и ЭКГ.
Узнать больше – [url=https://narkologicheskaya-klinika-voronezh9.ru/]narkologicheskaya-klinika-voronezh9.ru/[/url]
JesusRal
4 Oct 25 at 1:28 am
Hello there, I think your blog may be having web browser compatibility problems.
When I take a look at your website in Safari, it looks fine
however, if opening in Internet Explorer, it has some overlapping issues.
I merely wanted to give you a quick heads up! Aside from that, excellent blog!
BlueQubit Review
4 Oct 25 at 1:30 am
Why users still make use of to read news papers when in this technological world all is
accessible on web?
Contractubex
4 Oct 25 at 1:31 am
Di tengah kesibukan kehidupan sehari-hari, toko bunga jadi area yang selalu menyuguhkan keindahan dan keceriaan.
Dengan berbagai macam bunga yang tersaji, toko bunga bukan sekedar berfungsi sebagai provider bunga bagi keperluan dekorasi, tapi pun sebagai
penyampai pesan emosional dalam bervariasi momen penting dalam hidup.
Mulai dari pernikahan, ulang tahun, capai ucapan duka, bunga punya
metode unik guna menyampaikan perasaan yang susah diungkapkan dengan kata-kata.
Here is my web blog; florist Semarang
florist Semarang
4 Oct 25 at 1:32 am
где можно купить диплом медсестры [url=http://www.frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_udkt
4 Oct 25 at 1:34 am
https://al-material.ru
PatrickGop
4 Oct 25 at 1:34 am
https://keonhacai.deals/
web site
4 Oct 25 at 1:34 am
купить диплом в мурманске с занесением в реестр [url=https://frei-diplom1.ru]купить диплом в мурманске с занесением в реестр[/url] .
Diplomi_tmOi
4 Oct 25 at 1:34 am
купить диплом в новокуйбышевске [url=https://rudik-diplom10.ru]купить диплом в новокуйбышевске[/url] .
Diplomi_jkSa
4 Oct 25 at 1:35 am
[url=https://madcasino.top]mad casino[/url]
Perryclusa
4 Oct 25 at 1:35 am
Мы понимаем, что каждая минута имеет решающее значение, поэтому наши специалисты готовы выехать на дом в кратчайшие сроки и провести все необходимые процедуры по детоксикации организма. Наша цель — помочь пациенту вернуться к нормальной жизни без лишних стрессов и рискованных попыток самостоятельного лечения.
Подробнее тут – [url=https://vyvod-iz-zapoya-krasnodar00.ru/]vyvod-iz-zapoya krasnodar[/url]
HenryMut
4 Oct 25 at 1:37 am
купить диплом в астрахани [url=www.rudik-diplom7.ru]купить диплом в астрахани[/url] .
Diplomi_rhPl
4 Oct 25 at 1:37 am
диплом с внесением в реестр купить [url=http://www.frei-diplom2.ru]диплом с внесением в реестр купить[/url] .
Diplomi_doEa
4 Oct 25 at 1:37 am
Лечение на дому проходит в комфортной и спокойной обстановке, что позволяет значительно снизить уровень стресса и быстро улучшить состояние здоровья пациента.
Углубиться в тему – [url=https://narcolog-na-dom-sochi0.ru/]нарколог на дом[/url]
Duaneopits
4 Oct 25 at 1:38 am
Применение автоматизированных систем дозирования обеспечивает точное введение лекарственных средств, минимизируя риск передозировки и побочных эффектов. Постоянный мониторинг жизненно важных показателей позволяет врачу корректировать терапевтическую схему в режиме реального времени для обеспечения максимальной безопасности.
Выяснить больше – [url=https://vyvod-iz-zapoya-donetsk-dnr0.ru/]вывод из запоя капельница в донецке[/url]
Claytonfix
4 Oct 25 at 1:39 am
Как отмечает врач-нарколог клиники «РеабилитАльянс» Павел Сомов, «чем раньше начато лечение, тем выше шансы на скорейшее выздоровление без серьезных последствий для здоровья».
Получить дополнительные сведения – [url=https://narcolog-na-dom-krasnodar00.ru/]нарколог на дом недорого[/url]
RalphPiday
4 Oct 25 at 1:40 am
диплом об окончании техникума купить в [url=https://frei-diplom9.ru/]диплом об окончании техникума купить в[/url] .
Diplomi_voea
4 Oct 25 at 1:41 am
sildenafil [url=http://truevitalmeds.com/#]Buy sildenafil online usa[/url] sildenafil
TimothyArrar
4 Oct 25 at 1:43 am