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.narkolog-na-dom-1.ru/]www.narkolog-na-dom-1.ru/[/url] .
narkolog na dom_mrkt
7 Oct 25 at 1:00 pm
It’s quick to use, taking around 10 to 15 seconds to download a 5-minute video.
mp3 twitter downloader
7 Oct 25 at 1:00 pm
купить диплом техникума в спб [url=frei-diplom8.ru]купить диплом техникума в спб[/url] .
Diplomi_tasr
7 Oct 25 at 1:01 pm
вывод из запоя москва клиника [url=https://narkologicheskaya-klinika-20.ru]https://narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _obPr
7 Oct 25 at 1:02 pm
Развлечение, обучение и маркетинг в одном флаконе. Квизы, или интерактивные опросы, стали неотъемлемой частью современной цифровой культуры. Они повсюду: в социальных сетях, на сайтах, в онлайн-играх.
Но что же делает их такими популярными и почему они продолжают набирать обороты? Куда свходить на [url=https://webhamster.ru/punbb/viewtopic.php?pid=6021#p6021]квиз в Москве[/url]
Edwardsog
7 Oct 25 at 1:02 pm
купить диплом в иваново [url=www.rudik-diplom6.ru/]купить диплом в иваново[/url] .
Diplomi_yiKr
7 Oct 25 at 1:03 pm
новости легкой атлетики [url=sport-novosti-1.ru]sport-novosti-1.ru[/url] .
sport novosti_gapa
7 Oct 25 at 1:03 pm
I am sure this article has touched all the internet
viewers, its really really nice article on building up new
blog.
부산철거
7 Oct 25 at 1:04 pm
новости тенниса [url=http://sport-novosti-1.ru]http://sport-novosti-1.ru[/url] .
sport novosti_thpa
7 Oct 25 at 1:05 pm
none of the participants who reported communicating about their desire discrepancies reported this strategy to be unhelpful.ラブドール エロTake AwayMost of the participants indicated that doing nothing was not a helpful strategy,
ラブドール
7 Oct 25 at 1:06 pm
В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
Хочу знать больше – https://devilleelectrique.com/electricien-st-jerome
WillieememN
7 Oct 25 at 1:06 pm
купить диплом колледжа пермь [url=www.frei-diplom8.ru]www.frei-diplom8.ru[/url] .
Diplomi_pksr
7 Oct 25 at 1:07 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ꭰr c121,
Charlotte, NC 28273, United Ѕtates
+19803517882
remodeling consultants in the us
remodeling consultants in the us
7 Oct 25 at 1:08 pm
купить оригинальный диплом техникума [url=https://frei-diplom9.ru/]купить оригинальный диплом техникума[/url] .
Diplomi_leea
7 Oct 25 at 1:09 pm
новости хоккея [url=http://sportivnye-novosti-1.ru/]новости хоккея[/url] .
sportivnie novosti_gdpi
7 Oct 25 at 1:09 pm
It has worried meterriblyon Sunday afternoons,that is,エロオナホ
ラブドール
7 Oct 25 at 1:10 pm
кухни от производителя спб недорого и качественно [url=https://kuhni-spb-4.ru]https://kuhni-spb-4.ru[/url] .
kyhni spb_xoer
7 Oct 25 at 1:10 pm
помощь алкоголику на дому [url=https://www.narkolog-na-dom-1.ru]https://www.narkolog-na-dom-1.ru[/url] .
narkolog na dom_fnkt
7 Oct 25 at 1:11 pm
наркологическая услуга москва [url=www.narkologicheskaya-klinika-20.ru/]www.narkologicheskaya-klinika-20.ru/[/url] .
narkologicheskaya klinika _ucPr
7 Oct 25 at 1:12 pm
linebet website
linebet free
7 Oct 25 at 1:12 pm
Minotaurus ICO’s whitepaper highlights balanced token release. $MTAUR holders shape via DAO—democratic and cool. Casual market entry is spot on.
minotaurus coin
WilliamPargy
7 Oct 25 at 1:13 pm
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Детальнее – https://www.harfabusinesscenter.cz/section-detail/hbc-b-employee-friendly
MichaelPep
7 Oct 25 at 1:15 pm
https://marka-food.ru
DonaldtiEls
7 Oct 25 at 1:15 pm
кухня глория [url=http://www.kuhni-spb-4.ru]http://www.kuhni-spb-4.ru[/url] .
kyhni spb_ccer
7 Oct 25 at 1:16 pm
новости спорта россии [url=http://sportivnye-novosti-1.ru/]новости спорта россии[/url] .
sportivnie novosti_xdpi
7 Oct 25 at 1:16 pm
Hi there, just wanted to mention, I loved this article.
It was funny. Keep on posting!
Nordiqo
7 Oct 25 at 1:16 pm
нарколог выездной [url=https://narkolog-na-dom-1.ru/]narkolog-na-dom-1.ru[/url] .
narkolog na dom_zukt
7 Oct 25 at 1:17 pm
частная наркологическая клиника [url=https://www.narkologicheskaya-klinika-20.ru]https://www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _myPr
7 Oct 25 at 1:17 pm
Βy stressing conceptual mastery, OMT discloses math’ѕ internal appeal, igniting love аnd drive for tοp
exam qualities.
Get ready for success іn upcoming tests witһ OMT Math Tuition’ѕ exclusive curriculum, designed t᧐ cultivate crucial thinking and self-confidence іn eveгy trainee.
As math forms thе bedrock of logical thinking ɑnd critical analytical іn Singapore’s education ѕystem, professional math tuition supplies
tһe tailored assistance required tօ turn obstacles іnto triumphs.
Tuition programs f᧐r primary mathematics concentrate оn error analysis from ⲣrevious PSLE papers, teaching trainees t᧐
prevent repeating mistakes іn calculations.
Tuition fosters sophisticated рroblem-solving abilities,
essential fօr resolving tһe complex, multi-step questions tһat define O Level mathematics difficulties.
Junior college math tuition іs essential fߋr A Levels as it strengthens understanding οf innovative calculus subjects ⅼike integration methods
аnd differential equations, ԝhich аre main to tһe test curriculum.
OMT’ѕ custom-made curriculum uniquely enhances tһe MOE structure ƅy offering thematic units that link math topics аcross primary to JC levels.
Ӏn-depth options supplied on the internet leh, training
you just how to solve probⅼems properly
for muϲh better qualities.
Singapore’ѕ focus on рroblem-solving in math tests mаkes tuition vital fоr creating critical thinking abilities рast school hourѕ.
Visit my blog … bigtits student fuck math tutor
bigtits student fuck math tutor
7 Oct 25 at 1:18 pm
кухня на заказ спб [url=http://www.kuhni-spb-4.ru]http://www.kuhni-spb-4.ru[/url] .
kyhni spb_umer
7 Oct 25 at 1:19 pm
купить диплом в славянске-на-кубани [url=https://rudik-diplom15.ru/]https://rudik-diplom15.ru/[/url] .
Diplomi_vhPi
7 Oct 25 at 1:20 pm
новости хоккея [url=https://novosti-sporta-7.ru/]новости хоккея[/url] .
novosti sporta_gcOt
7 Oct 25 at 1:22 pm
https://pumpswap.co/
Thurmandwelt
7 Oct 25 at 1:23 pm
наркологическая клиника в москве [url=http://www.narkologicheskaya-klinika-20.ru]http://www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _jbPr
7 Oct 25 at 1:24 pm
лечение зависимости на дому [url=http://narkolog-na-dom-1.ru]http://narkolog-na-dom-1.ru[/url] .
narkolog na dom_kskt
7 Oct 25 at 1:24 pm
Secondary school math tuition іs vital fߋr Secondary 1 students,helping them integrate technology in math learning.
Ѕia, thе waу Singapore kids excel іn math globally,
гeally ᧐ne kind!
Dear Singapore parents, Singapore math tuition рrovides thе customized touch
your child shоuld have. Secondary math tuition scaffolds advanced studies efficiently.
Secondary 1 math tuition dominates inequalities, constructing ѕеlf-confidence acyion Ƅy action.
Tһe humanitarian element ⲟf ѕome secondary 2 math
tuition programs оffers scholarships. Secondary 2 math
tuition һelp impoverished students. Generous secondary 2 math tuition promotes
equity. Secondary 2 math tuition returns t᧐ society.
Ԝith Ο-Levels on thе horizon, secondary 3 math exams stress quality.
Тhese results affect curricula enrichment. Success promotes սseful solving.
Тһe crucial secondary 4 exams foster international exchanges
іn Singapore. Secondary 4 math tuition links virtual peers.
This broaqdening boosts Ο-Level viewpoints.
Secondary 4 math tuition internationalizes education.
Math ցoes further tһan exam scores; it’s a vital
talent in surging ᎪI technologies, essential fоr traffic flow optimization.
Excelling ɑt math rеquires fostering a love fߋr the discipline ᴡhile applying іts core ideas to
everyday situations.
Օne key aspect is that іt helps іn appreciating
tһe interdisciplinary linkѕ in math frоm ⅾifferent Singapore secondary papers.
Uѕing online math tuition e-learning systems іn Singapore boosts exam performance ѡith multilingual subtitles.
Ѕia lor, steady ah, kids thrive іn secondary school
environment, no undue pressure рlease.
math tuition
7 Oct 25 at 1:25 pm
Hello to every body, it’s my first pay a visit of this blog;
this blog carries remarkable and actually good data for readers.
трипскан
7 Oct 25 at 1:25 pm
спорт 24 часа [url=sportivnye-novosti-1.ru]sportivnye-novosti-1.ru[/url] .
sportivnie novosti_ohpi
7 Oct 25 at 1:26 pm
свежие новости спорта [url=www.novosti-sporta-7.ru/]www.novosti-sporta-7.ru/[/url] .
novosti sporta_lvOt
7 Oct 25 at 1:27 pm
linebet prediction
linebet login registration
7 Oct 25 at 1:28 pm
Wow that was unusual. I just wrote an incredibly long comment
but after I clicked submit my comment didn’t show up. Grrrr…
well I’m not writing all that over again. Regardless,
just wanted to say excellent blog!
kl999
7 Oct 25 at 1:28 pm
купить легальный диплом техникума [url=www.frei-diplom8.ru/]купить легальный диплом техникума[/url] .
Diplomi_dvsr
7 Oct 25 at 1:28 pm
новости тенниса [url=https://www.sportivnye-novosti-1.ru]новости тенниса[/url] .
sportivnie novosti_eipi
7 Oct 25 at 1:30 pm
последние новости спорта [url=https://novosti-sporta-7.ru]https://novosti-sporta-7.ru[/url] .
novosti sporta_iaOt
7 Oct 25 at 1:31 pm
how to get Prednisone legally online: Prednisone tablets online USA – PredniWell Online
Morrisluh
7 Oct 25 at 1:32 pm
I’m not sure why but this web site is loading incredibly slow
for me. Is anyone else having this problem or is it a
issue on my end? I’ll check back later on and see if the problem still exists.
CalvenRidge Trust Legit Or Not
7 Oct 25 at 1:32 pm
literally justified byhis vivid aspect,オナホ フィギュアwhen seen gliding at high noon through a dark bluesea,
ラブドール
7 Oct 25 at 1:34 pm
новости олимпиады [url=http://sport-novosti-1.ru/]http://sport-novosti-1.ru/[/url] .
sport novosti_bxpa
7 Oct 25 at 1:35 pm
купить диплом в волгограде [url=http://rudik-diplom15.ru/]купить диплом в волгограде[/url] .
Diplomi_qoPi
7 Oct 25 at 1:36 pm
ラブドール(2) In your own apartment building,you can interfere with radioreception at times when the enemy wants everybody to listen.
ラブドール
7 Oct 25 at 1:38 pm