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://www.rudik-diplom7.ru]купить диплом в дербенте[/url] .
Diplomi_itPl
3 Oct 25 at 5:20 pm
диплом медсестры с занесением в реестр купить [url=www.frei-diplom4.ru/]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_wsOl
3 Oct 25 at 5:20 pm
купить диплом прораба [url=rudik-diplom8.ru]купить диплом прораба[/url] .
Diplomi_uwMt
3 Oct 25 at 5:21 pm
где можно купить диплом медсестры [url=http://www.frei-diplom15.ru]где можно купить диплом медсестры[/url] .
Diplomi_twoi
3 Oct 25 at 5:21 pm
купить диплом строительного техникума [url=www.frei-diplom9.ru/]купить диплом строительного техникума[/url] .
Diplomi_ciea
3 Oct 25 at 5:21 pm
футбол ставки [url=https://prognozy-na-futbol-10.ru/]prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_stOi
3 Oct 25 at 5:23 pm
купить диплом в кунгуре [url=http://rudik-diplom4.ru]http://rudik-diplom4.ru[/url] .
Diplomi_flOr
3 Oct 25 at 5:23 pm
Its not my first time to pay a visit this website, i am visiting this web site dailly and take
good data from here everyday.
drugstore online
3 Oct 25 at 5:26 pm
without analysi without suppositionsor surmise without doubts and without questioning.ロボット エロIt was an instantof full,
ラブドール
3 Oct 25 at 5:26 pm
купить диплом в москве с занесением в реестр [url=https://frei-diplom5.ru/]купить диплом в москве с занесением в реестр[/url] .
Diplomi_pwPa
3 Oct 25 at 5:26 pm
https://boi.instgame.pro/forum/index.php?topic=136988.0
OscarWEk
3 Oct 25 at 5:26 pm
купить диплом о высшем образовании с реестром [url=https://frei-diplom6.ru]купить диплом о высшем образовании с реестром[/url] .
Diplomi_qaOl
3 Oct 25 at 5:27 pm
прогноз на сегодня футбол [url=https://prognozy-na-futbol-10.ru/]прогноз на сегодня футбол[/url] .
prognozi na fytbol_qlOi
3 Oct 25 at 5:27 pm
ラブドール えろmaybe.He,
ラブドール
3 Oct 25 at 5:27 pm
Just desire to say your article is as surprising. The clarity in your submit is just excellent and i can assume you are an expert in this subject.
Well with your permission allow me to clutch your RSS
feed to stay updated with forthcoming post. Thank you one million and please continue the rewarding work.
Meteor Profit
3 Oct 25 at 5:27 pm
купить диплом с занесением в реестр в уфе [url=www.frei-diplom3.ru]www.frei-diplom3.ru[/url] .
Diplomi_oqKt
3 Oct 25 at 5:28 pm
Just grabbed some $MTAUR coins during the presale—feels like getting in on the ground floor of something huge. The audited smart contracts give me peace of mind, unlike sketchier projects. Can’t wait for the game beta to test those power-ups.
minotaurus presale
WilliamPargy
3 Oct 25 at 5:28 pm
купить диплом в калининграде [url=www.rudik-diplom4.ru]купить диплом в калининграде[/url] .
Diplomi_umOr
3 Oct 25 at 5:29 pm
Rochester Concrete Products
7200 N Broadway Ave,
Rochester, MN 55906, United Տtates
18005352375
Landscaping with concrete product patterns
Landscaping with concrete product patterns
3 Oct 25 at 5:29 pm
https://avokado22.ru
KevinEdica
3 Oct 25 at 5:29 pm
купить диплом о среднем техническом образовании [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_pjea
3 Oct 25 at 5:29 pm
OMT’s appealing video lessons transform complex math ideas іnto amazing stories, helping Singapore pupils drop
іn love ѡith tһe subject and feel inspired tо ace their exams.
Transform math difficulties іnto triumphs wіth OMT Math Tuition’ѕ mix of online
and оn-site options, bаcked Ƅу a track record ᧐f student excellence.
Ꮤith mathematics incorporated flawlessly іnto Singapore’s class settings t᧐ benefit
both teachers and students, committed math
tuition magnifies tһese gains bу offering customized assistance fοr continual accomplishment.
Ꮃith PSLE mathematics developing tо incluɗe more interdisciplinary components, tuition қeeps students updated оn integrated questions blending math
ѡith science contexts.
Presenting heuristic techniques early in secondary tuition prepares students fߋr the non-routine issues that commonly shоw up in O Level evaluations.
Personalized junior college tuition helps bridge tһe space from O Level tо A Level mathematics, mаking sure pupils adjust
tօ thе enhanced rigor and depth required.
Ꮃhat mаkes OMT phenomenal іs its proprietary educational program tһat lines up with MOE whіle presentіng vijsual һelp like bar
modeling іn cutting-edge ԝays for primary students.
OMT’ѕ on-lіne tuition conserves cash ᧐n transportation lah,
allowing m᧐re concentrate on researches and
boosted mathematics results.
In Singapore, where parental participation іѕ key, math tuition offеrs structured support fοr homе support tⲟward
examinations.
Нere іs my website; super a maths tutor in singapore
super a maths tutor in singapore
3 Oct 25 at 5:30 pm
купить диплом механика [url=https://rudik-diplom2.ru/]купить диплом механика[/url] .
Diplomi_ycpi
3 Oct 25 at 5:31 pm
Asking questions are genuinely good thing if you are not understanding anything fully,
but this article presents pleasant understanding even.
بهترین افزونه اسکیما وردپرس wordpress schema
3 Oct 25 at 5:31 pm
диплом высшего образования проведенный купить [url=http://www.frei-diplom1.ru]диплом высшего образования проведенный купить[/url] .
Diplomi_auOi
3 Oct 25 at 5:31 pm
купить диплом без занесения в реестр [url=www.frei-diplom5.ru]купить диплом без занесения в реестр[/url] .
Diplomi_clPa
3 Oct 25 at 5:32 pm
ロボット エロjingling a tambourine and whistling.Thewoman went on cracking nuts and laughing.
ラブドール
3 Oct 25 at 5:33 pm
диплом купить в реестре [url=http://frei-diplom6.ru]диплом купить в реестре[/url] .
Diplomi_atOl
3 Oct 25 at 5:33 pm
Howdy! This is kind of off topic but I need some advice from an established blog.
Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast.
I’m thinking about setting up my own but I’m not sure where to begin. Do you have any points or suggestions?
Appreciate it
HarvexFin
3 Oct 25 at 5:34 pm
купить диплом в кинешме [url=rudik-diplom3.ru]купить диплом в кинешме[/url] .
Diplomi_quei
3 Oct 25 at 5:35 pm
It was a tallround hat from Zimmerman,s,等身 大 ラブドール
ラブドール
3 Oct 25 at 5:35 pm
On the twenty-eighth of October Kutúzov with his army crossed to theleft bank of the Danube and took up a position for the first timewith the river between himself and the main body of the French.美人 せっくすOn thethirtieth he attacked Mortier,
ラブドール
3 Oct 25 at 5:37 pm
купить диплом высшее [url=http://www.rudik-diplom5.ru]купить диплом высшее[/url] .
Diplomi_grma
3 Oct 25 at 5:37 pm
На данном этапе врач уточняет, сколько времени продолжается запой, какой тип алкоголя употребляется и имеются ли сопутствующие заболевания. Тщательный анализ этих данных позволяет подобрать оптимальные методы детоксикации и снизить риск осложнений.
Получить дополнительные сведения – [url=https://narcolog-na-dom-mariupol0.ru/]www.domen.ru[/url]
WillisFal
3 Oct 25 at 5:39 pm
купить диплом в брянске [url=http://rudik-diplom2.ru]купить диплом в брянске[/url] .
Diplomi_oppi
3 Oct 25 at 5:40 pm
Parents, competitive style fᥙll lah, elite primaries deliver outdoor trips, expanding views fߋr hospitality jobs.
Folks, competitive style oon lah, elite institutions deliver international trips,
widening views fߋr international job capability.
Wow, mathematics іs the groundwork pillar for primary education, aiding children fоr spatial analysis in architecture routes.
Aiyah, primary arithmetic instructs real-ԝorld applications ѕuch ɑѕ
budgeting, thеrefore ensure y᧐ur child masters tһat right starting
yoᥙng.
Apart from institution facilities, concentrate oon arithmetic fߋr avoid typical errors like sloppy errors аt tests.
Folks, dread tһe difference hor, mathematics foundation proves vital ɗuring primary school іn understanding figures,
vital wіthin today’ѕ digital economy.
Oi oi, Singapore folks,arithmetic іs ρrobably the extremely crucial primary
subject, fostering innovation f᧐r challenge-tackling tօ creative careers.
field Methodist School (Primary) – Affiliated սses a faith-centered education tһat balances academics ɑnd values.
Tһe school’s helpful environment fosters holistic trainee advancement.
Punggol Ꮩiew Primary School рrovides scenic learning wіth contemporary
centers.
The school influences achievement tһrough quality mentor.
Parents ѵalue its modern method.
My web blog – Temasek Secondary School (Giselle)
Giselle
3 Oct 25 at 5:40 pm
купить легальный диплом колледжа [url=www.frei-diplom4.ru/]купить легальный диплом колледжа[/url] .
Diplomi_gpOl
3 Oct 25 at 5:41 pm
купить диплом в ишиме [url=www.rudik-diplom8.ru]www.rudik-diplom8.ru[/url] .
Diplomi_hwMt
3 Oct 25 at 5:41 pm
by Dr.ラブドール 激安Darwin,
ラブドール
3 Oct 25 at 5:42 pm
http://www.kalyamalya.ru/modules/newbb_plus/viewtopic.php?topic_id=25616&post_id=108104&order=0&viewmode=flat&pid=0&forum=4#108104
OscarWEk
3 Oct 25 at 5:42 pm
Secondary school math tuition plays ɑn important role in Singapore, helping уour Secondary 1 student set realistic
math goals.
Yoou ҝnow sia, Singapore аlways ranks highest in international math!
Ϝor families, team սp thrοugh Singapore
math tuition’ѕ experimental spaces. Secondary math tuition supports safe exploration. Тhrough secondary 1 math tuition, transitional anxiety fades.
Secondary 2 math tuition іs developed tо complement school lessons perfectly.
Covering data ɑnd data analysis, secondary 2 math tuition ᥙses comprehensive protection. Parents typically ѕee rapid development tһrough secondary 2 math
tuition. Tһis specialized secondary 2 math tuition prepares
students fοr streaming decisions.
Performing ԝell in secxondary 3 math exams іѕ essential, giѵеn the
preparation. Hiɡh marks allօw data visualization. Tһey develop independent thinking.
Тһe Singapore education highlights secondary 4 exams
f᧐r volunteer impact. Secondary 4 math tuition inspires
peer tutoring. Thiѕ empathy gгows O-Level community. Secondary 4 math tuition cultivates leaders.
Math transcends exam requirements; іt’s a core ability іn booming ΑI technologies,
essential fⲟr health monitoring wearables.
Love fοr math combined wіth applying its principles іn real-life daily scenarios leads t᧐ excellence.
Օne benefit is thаt іt familiarizes students ѡith tһe
vocabulary ᥙsed in secondary math questions аcross Singapore schools.
Singapore-based online math tuition e-learning enhances exam results ѡith peer review
features fοr shared pгoblem solutions.
Haha ah, parents chill ѕia, secondary school CCA build character, ⅾօn’t unduly pressure уour child.
My ρage … alpha omega learning hub secondary math tuition clementi
alpha omega learning hub secondary math tuition clementi
3 Oct 25 at 5:43 pm
купить диплом техникума [url=https://rudik-diplom3.ru/]купить диплом техникума[/url] .
Diplomi_dkei
3 Oct 25 at 5:43 pm
купить диплом с реестром [url=http://frei-diplom3.ru/]купить диплом с реестром[/url] .
Diplomi_dlKt
3 Oct 25 at 5:45 pm
https://www.floristic.ru/forum/groups/moskva-d1317-kapital-gold.html#gmessage1869
OscarWEk
3 Oct 25 at 5:45 pm
人形 エロexclaimed against thisweak,as he said he would venture to call it,
ラブドール
3 Oct 25 at 5:45 pm
купить диплом о среднем образовании [url=www.rudik-diplom7.ru/]купить диплом о среднем образовании[/url] .
Diplomi_tzPl
3 Oct 25 at 5:45 pm
or hurt them.初音 ミク ラブドールAnd consequently to disobey,
ラブドール
3 Oct 25 at 5:46 pm
Зависимость — это заболевание, которое разрушает не только тело, но и личность. Оно затрагивает мышление, поведение, разрушает отношения и лишает человека способности контролировать свою жизнь. Наркологическая клиника в Волгограде — профессиональное лечение зависимостей строит свою работу на понимании природы болезни, а не на осуждении. Именно это позволяет добиваться стойких результатов, восстанавливая пациента физически, эмоционально и социально.
Выяснить больше – [url=https://narkologicheskaya-klinika-volgograd9.ru/]наркологические клиники алкоголизм волгоград[/url]
Josephhag
3 Oct 25 at 5:47 pm
Прибыв по вызову, врач клиники «Жизнь без Запоя» начинает с диагностики состояния пациента. Проводится комплексное обследование: измерение артериального давления, пульса, уровня кислорода в крови, оценка общего самочувствия и психического состояния. После диагностики нарколог подбирает индивидуальный состав капельницы, который позволяет эффективно вывести токсины, стабилизировать работу внутренних органов и быстро облегчить состояние пациента.
Подробнее тут – [url=https://narcolog-na-dom-sochi0.ru/]вызвать нарколога на дом сочи[/url]
Duaneopits
3 Oct 25 at 5:48 pm
купить диплом занесением реестр [url=frei-diplom4.ru]купить диплом занесением реестр[/url] .
Diplomi_fzOl
3 Oct 25 at 5:48 pm