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=http://rudik-diplom10.ru]купить диплом с реестром[/url] .
Diplomi_sfSa
14 Oct 25 at 4:02 am
аренда мини экскаватора в московской области [url=www.arenda-mini-ekskavatora-v-moskve-2.ru/]www.arenda-mini-ekskavatora-v-moskve-2.ru/[/url] .
arenda mini ekskavatora v moskve_upKt
14 Oct 25 at 4:02 am
согласование перепланировки нежилого здания [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]http://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_ocSr
14 Oct 25 at 4:04 am
купить диплом медбрата [url=https://www.rudik-diplom5.ru]купить диплом медбрата[/url] .
Diplomi_zdma
14 Oct 25 at 4:04 am
рулонные шторы автоматические купить [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]https://rulonnaya-shtora-s-elektroprivodom.ru/[/url] .
rylonnaya shtora s elektroprivodom_cjKt
14 Oct 25 at 4:04 am
купить диплом о среднем образовании с занесением в реестр [url=www.frei-diplom6.ru/]купить диплом о среднем образовании с занесением в реестр[/url] .
Diplomi_dbOl
14 Oct 25 at 4:05 am
Very nice article, exactly what I wanted to find.
nft collectibles
14 Oct 25 at 4:05 am
visit the next site
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
visit the next site
14 Oct 25 at 4:05 am
рулонная штора автоматическая [url=rulonnaya-shtora-s-elektroprivodom.ru]rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_mqKt
14 Oct 25 at 4:06 am
порядок согласования перепланировки нежилого помещения [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_oser
14 Oct 25 at 4:07 am
электрокарниз купить в москве [url=www.karniz-elektroprivodom.ru]электрокарниз купить в москве[/url] .
karniz elektroprivodom shtor kypit_apei
14 Oct 25 at 4:07 am
потолочкин отзывы самара [url=https://natyazhnye-potolki-samara-1.ru/]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_bwor
14 Oct 25 at 4:09 am
горизонтальные жалюзи с электроприводом [url=http://zhalyuzi-s-elektroprivodom77.ru]горизонтальные жалюзи с электроприводом[/url] .
jaluzi na okna s elektroprivodom_mupa
14 Oct 25 at 4:10 am
gratis guthaben ohne einzahlung sportwetten
Look into my site :: WettbüRo Frankfurt
WettbüRo Frankfurt
14 Oct 25 at 4:10 am
потолочкин ру натяжные потолки отзывы [url=www.stretch-ceilings-samara-1.ru/]www.stretch-ceilings-samara-1.ru/[/url] .
natyajnie potolki samara_jysl
14 Oct 25 at 4:11 am
услуги экскаватора москва [url=arenda-mini-ekskavatora-v-moskve-2.ru]услуги экскаватора москва[/url] .
arenda mini ekskavatora v moskve_saKt
14 Oct 25 at 4:13 am
вывод из запоя круглосуточно
vivod-iz-zapoya-cherepovec014.ru
экстренный вывод из запоя
narkologiyacherepovecNeT
14 Oct 25 at 4:14 am
электрокарнизы москва [url=http://karniz-shtor-elektroprivodom.ru/]http://karniz-shtor-elektroprivodom.ru/[/url] .
karniz dlya shtor s elektroprivodom_oaer
14 Oct 25 at 4:14 am
регистрация перепланировки нежилого помещения [url=www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_bvSr
14 Oct 25 at 4:14 am
рулонные шторы на пластиковые окна на кухню [url=www.rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на пластиковые окна на кухню[/url] .
rylonnaya shtora s elektroprivodom_pgKt
14 Oct 25 at 4:15 am
OMT’s enrichment tasks pɑst the syllabus unveil math’s unlimited possibilities, firing սp passion and examination passion.
Discover tһe benefit of 24/7 online math tuition ɑt OMT, where appealing resources mɑke finding оut fun and effective
fߋr all levels.
As mathematics underpins Singapore’ѕ track
record for excellence іn worldwide standards lіke PISA, math tuition іs crucial t᧐ unlocking a kid’s possible and protecting academic advantages in thiѕ
core subject.
Wіth PSLE math concerns frequently involving real-ᴡorld applications, tuition ⲟffers targeted practice tⲟ establish crucial believing
skills іmportant for hіgh ratings.
Рrovided tһe high risks ⲟf O Levels fоr secondary school development іn Singapore, math tuition mаkes bеst use of opportunities fоr t᧐p grades and wanted placements.
With A Levels influencing profession courses іn STEM areas, math tuition strengthens fundamental abilities fօr future
university гesearch studies.
Ꮤhɑt collections OMT aрart is іts customized curriculum that straightens ᴡith MOE ᴡhile
providing adaptable pacing, allowing sophisticated pupils tо increase their discovering.
Gamified elements mɑke modification enjoyable lor,
urging еven more practice and bring aЬօut grade enhancements.
Tuition helps stabilize ϲo-curricular activities ԝith resеarch studies, allowing Singapore students tօ stand
out in mathematics examinations ԝithout exhaustion.
Мy webpage – secondary 3 math tuition singapore
secondary 3 math tuition singapore
14 Oct 25 at 4:16 am
By commemorating littⅼe victories underway tracking, OMT supports ɑ positive relationship ᴡith mathematics, motivating students fоr test quality.
Transform mathematics challenges іnto accomplishments ᴡith OMT Math Tuition’s mix oof
online and on-site alternatives, Ьacked bү ɑ track record οf
trainee excellence.
Singapore’ѕ worlⅾ-renowned math curriculum stresses
conceptual understanding оver mere computation, mɑking math tuition imрortant for trainees t᧐ comprehend deep concepts
аnd stand οut in national tests like PSLE and O-Levels.
Tuition іn primary school math іs key fоr PSLE preparation, ɑs it presents sophisticated techniques fоr managing non-routine issues tһɑt
stump numerous candidates.
Secondary math tuition lays ɑ strong foundation for post-O
Level rеsearch studies, sucһ аѕ A Levels or polytechnic training courses, by mastering fundamental subjects.
Ꮃith Α Levels demanding proficiency іn vectors ɑnd
complex numbers, math tuition supplies targeted practice tօ manage thеsе abstract concepts
ѕuccessfully.
OMT’ѕ custom curriculum distinctively lines ᥙp
wіth MOE framework by giving connecting modules
fоr smooth transitions in betԝeen primary, secondary,
ɑnd JC mathematics.
OMT’s e-learning decreases mathematics anxiety lor, mɑking you
extra positive ɑnd rеsulting in highеr test marks.
Math tuition іn little grouρs makes ceгtain individualized attention,
typically lacking іn largе Singapore school classes fοr examination preparation.
Feel free tօ visit mʏ web blog singapore math tuition
singapore math tuition
14 Oct 25 at 4:16 am
купить диплом в новочебоксарске [url=http://www.rudik-diplom5.ru]http://www.rudik-diplom5.ru[/url] .
Diplomi_asma
14 Oct 25 at 4:17 am
электрокарниз недорого [url=http://karniz-elektroprivodom.ru]http://karniz-elektroprivodom.ru[/url] .
karniz elektroprivodom shtor kypit_asei
14 Oct 25 at 4:17 am
купить диплом с занесением в реестр в иркутске [url=http://www.frei-diplom3.ru]купить диплом с занесением в реестр в иркутске[/url] .
Diplomi_vmKt
14 Oct 25 at 4:17 am
диплом проведенный купить [url=frei-diplom2.ru]диплом проведенный купить[/url] .
Diplomi_efEa
14 Oct 25 at 4:17 am
купить диплом вуза с реестром [url=https://www.frei-diplom6.ru]купить диплом вуза с реестром[/url] .
Diplomi_qpOl
14 Oct 25 at 4:18 am
купить диплом с занесением в реестр самара [url=http://frei-diplom5.ru/]http://frei-diplom5.ru/[/url] .
Diplomi_xdPa
14 Oct 25 at 4:18 am
перепланировка и согласование [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_tper
14 Oct 25 at 4:19 am
Just want to say your article is as astounding.
The clearness in your post is simply cool and i can assume you are an expert
on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date
with forthcoming post. Thanks a million and
please continue the rewarding work.
Rozmarín na vlasy
14 Oct 25 at 4:20 am
жалюзи на окна с электроприводом [url=https://zhalyuzi-s-elektroprivodom77.ru/]жалюзи на окна с электроприводом[/url] .
jaluzi na okna s elektroprivodom_igpa
14 Oct 25 at 4:20 am
купить диплом о среднем образовании [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_vgea
14 Oct 25 at 4:23 am
купить диплом техникума открыто [url=https://www.frei-diplom8.ru]купить диплом техникума открыто[/url] .
Diplomi_fgsr
14 Oct 25 at 4:23 am
https://eosio.stackexchange.com/users/7626/free-spins-no-deposit-india?tab=profile
nuqziyb
14 Oct 25 at 4:24 am
потолочник [url=https://stretch-ceilings-samara.ru/]https://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_tukl
14 Oct 25 at 4:26 am
Good day! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having problems finding one?
Thanks a lot!
turkey visa for australian
14 Oct 25 at 4:28 am
перепланировка нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_sjer
14 Oct 25 at 4:29 am
жалюзи для пластиковых окон с электроприводом [url=http://www.zhalyuzi-s-elektroprivodom77.ru]http://www.zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_ywpa
14 Oct 25 at 4:31 am
купить диплом техникума ссср в санкт [url=frei-diplom11.ru]купить диплом техникума ссср в санкт[/url] .
Diplomi_gusa
14 Oct 25 at 4:32 am
купить диплом в спб с занесением в реестр [url=www.frei-diplom5.ru]www.frei-diplom5.ru[/url] .
Diplomi_wePa
14 Oct 25 at 4:32 am
Hi there, i read your blog occasionally and i own a similar
one and i was just curious if you get a lot of spam comments?
If so how do you reduce it, any plugin or anything you can suggest?
I get so much lately it’s driving me crazy so any help is very much appreciated.
Yupoo Celine
14 Oct 25 at 4:32 am
услуги мини экскаватора [url=https://arenda-mini-ekskavatora-v-moskve-2.ru]услуги мини экскаватора[/url] .
arenda mini ekskavatora v moskve_myKt
14 Oct 25 at 4:33 am
электрическая рулонная штора [url=http://www.rulonnaya-shtora-s-elektroprivodom.ru]http://www.rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_fcKt
14 Oct 25 at 4:33 am
натяжные потолки сайт [url=www.stretch-ceilings-samara-1.ru]натяжные потолки сайт[/url] .
natyajnie potolki samara_fbsl
14 Oct 25 at 4:34 am
согласование проекта перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/]pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_apSr
14 Oct 25 at 4:34 am
пластиковые жалюзи с электроприводом [url=https://zhalyuzi-s-elektroprivodom77.ru/]https://zhalyuzi-s-elektroprivodom77.ru/[/url] .
jaluzi na okna s elektroprivodom_ynpa
14 Oct 25 at 4:34 am
купить диплом в владикавказе [url=www.rudik-diplom8.ru/]www.rudik-diplom8.ru/[/url] .
Diplomi_ngMt
14 Oct 25 at 4:35 am
рулонная штора автоматическая [url=www.rulonnaya-shtora-s-elektroprivodom.ru]www.rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_lbKt
14 Oct 25 at 4:35 am
купить диплом в ишимбае [url=https://www.rudik-diplom11.ru]https://www.rudik-diplom11.ru[/url] .
Diplomi_frMi
14 Oct 25 at 4:35 am
купить диплом в комсомольске-на-амуре [url=http://rudik-diplom1.ru]купить диплом в комсомольске-на-амуре[/url] .
Diplomi_rcer
14 Oct 25 at 4:35 am