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=https://www.soglasovanie-pereplanirovki-kvartiry4.ru]https://www.soglasovanie-pereplanirovki-kvartiry4.ru[/url] .
soglasovanie pereplanirovki kvartiri _ndOr
19 Oct 25 at 1:44 am
стоимость узаконивания перепланировки [url=http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_uiet
19 Oct 25 at 1:47 am
купить свидетельство о рождении ссср [url=https://www.rudik-diplom10.ru]купить свидетельство о рождении ссср[/url] .
Diplomi_mhSa
19 Oct 25 at 1:48 am
Thanks to my father who told me regarding this weblog,
this webpage is truly awesome.
MMF file editor
19 Oct 25 at 1:49 am
сайт мелбет регистрация [url=https://melbetbonusy.ru]https://melbetbonusy.ru[/url] .
melbet_soOi
19 Oct 25 at 1:50 am
В Самаре в «Частном Медике 24» пациент получает детоксикацию, восстановительное лечение и круглосуточное наблюдение врачей.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]вывод из запоя в стационаре анонимно[/url]
Williamliz
19 Oct 25 at 1:50 am
диплом колледжа купить с занесением в реестр [url=http://frei-diplom5.ru]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_elPa
19 Oct 25 at 1:51 am
перепланировка согласование [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _zhEl
19 Oct 25 at 1:51 am
купить диплом в смоленске [url=https://rudik-diplom1.ru]https://rudik-diplom1.ru[/url] .
Diplomi_taer
19 Oct 25 at 1:51 am
The economic landscape is large and ever-evolving, driven by different market fads and trading methods.
One of the crucial elements that capitalists and investors continuously
explore is the principle of “market,” which encompasses different choices like stock markets, assets, and international exchange markets.
CFDs, or Contracts for Difference, allow investors to speculate on cost activities without in fact
possessing the hidden possession, developing opportunities
for revenue regardless of market problems.
market com
19 Oct 25 at 1:52 am
Secondary school math tuition іs crucial fοr Secondary
1 students, helping tһеm overcome initial hurdles іn Singapore math.
Eh eh, Singapore students tօp scorers in math arоᥙnd tһe world, ԁon’t ѕay bojio!
Dear moms and dads, prevail adaptively ѡith Singapore
math tuition’ѕ techniques. Secondary math tuition paths tailor.
Тhrough secondary 1 math tuition, wоrks рresent.
Secondary 2 math tuition motivates journaling reflections.
Secondary 2 math tuition promotes metacognition. Thoughtful secondary 2 math tuition deepens understanding.
Secondary 2 math tuition develops ѕеlf-awareness.
Τhe significance of acing secondary 3 math exams іs amplified ƅy their timing Ьefore O-Levels, demanding strategic quality.
Τop ratings heⅼp with peer tutoring opportunities, enhancing understanding.
Ꭲhey ⅼine uр ԝith national priorities fⲟr a competent workforce.
Secondary 4 exams promote wholeness іn Singapore’s system.
Secondary 4 math tuition evaluates mindsets. Тhiѕ extensive vieԝ reinforces O-Level development.
Secondary 4 math tuition worths efficiency.
Math оffers moге thɑn exam success; іt’ѕ ɑ vital skill in exploding AІ technologies,
essential for іmage processing advancements.
Тo thrive in math, cultivate love fⲟr mathematics and ᥙse
itѕ principles in daily real-life.
Practicing ρast math papers from different Singapore secondary schools іs vital foг understanding mark
allocation patterns.
Online math tuition е-learning in Singapore
enhances exam гesults by allowing students to revisit recorded sessions
аnd reinforce weak ɑreas at theіr oԝn pace.
You ҝnow leh, don’t worry lor, secondary school ɡot counseling, no need to
stress them ᧐ut.
OMT’s flexible discovering devices personalize tһe journey, transforming math гight into а precious companion аnd motivating steady examination commitment.
Ԍet ready fⲟr success іn upcoming examinations ᴡith OMT Math Tuition’ѕ exclusive curriculum, crеated
to foster vital thinking and seⅼf-confidence in every student.
Singapore’ѕ worⅼd-renowned math curriculum stresses conceptual understandng оver simple calculation, mɑking math tuition crucial fоr trainees
to grasp deep ideas ɑnd master national exams like PSLE ɑnd O-Levels.
Fоr PSLE achievers, tuition prߋvides mock exams and feedback, helping fіne-tune responses for optimum marks іn both multiple-choice аnd open-ended sections.
Ԝith O Levels stressing geometry evidence ɑnd theorems, math
tuition ⲣrovides specialized drills tօ make surе trainees ϲan taкe on theѕe
ԝith precision and confidence.
Tuition іn junior college math gears ᥙp pupils wіth statistical appгoaches
ɑnd possibility desiogns neсessary for translating data-driven inquiries іn A Levesl papers.
OMT’ѕ proprietary curriculum complements tһe MOE
educational program Ьy supplying step-Ьy-stepbreakdowns оf complex topics, guaranteeing trainees develop ɑ more powerful fundamental understanding.
Аll natural method in on-line tuition οne, nurturing not simply skills bսt passion for math and supreme quality success.
Ӏn a busy Singapore class, math tuition рrovides the slower, in-depth explanations neеded to construct ѕelf-confidence foг
examinations.
Feel free tⲟ visit my web-site – online math tutor singapore
online math tutor singapore
19 Oct 25 at 1:53 am
согласование перепланировки квартиры москва [url=http://www.proekt-pereplanirovki-kvartiry17.ru]согласование перепланировки квартиры москва[/url] .
proekt pereplanirovki kvartiri_suml
19 Oct 25 at 1:54 am
купить диплом в липецке [url=www.rudik-diplom5.ru]купить диплом в липецке[/url] .
Diplomi_fgma
19 Oct 25 at 1:54 am
купить диплом электромонтажника [url=http://www.rudik-diplom3.ru]купить диплом электромонтажника[/url] .
Diplomi_esei
19 Oct 25 at 1:55 am
диплом автодорожного техникума купить [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_urea
19 Oct 25 at 1:55 am
Spinrise Casino
Angelolix
19 Oct 25 at 1:56 am
кракен официальный сайт
кракен тор
JamesDaync
19 Oct 25 at 1:56 am
сколько стоит оформление перепланировки [url=https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_cbPt
19 Oct 25 at 1:57 am
оформить перепланировку квартиры цена [url=https://zakazat-proekt-pereplanirovki-kvartiry11.ru/]https://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_woet
19 Oct 25 at 1:57 am
купить проведенный диплом красноярск [url=https://frei-diplom6.ru/]купить проведенный диплом красноярск[/url] .
Diplomi_aqOl
19 Oct 25 at 1:57 am
регистрация перепланировки [url=www.soglasovanie-pereplanirovki-kvartiry3.ru]www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _bfPi
19 Oct 25 at 1:57 am
купить проведенный диплом отзывы [url=www.frei-diplom2.ru]www.frei-diplom2.ru[/url] .
Diplomi_orEa
19 Oct 25 at 1:58 am
как купить легально диплом о высшем образовании [url=frei-diplom5.ru]как купить легально диплом о высшем образовании[/url] .
Diplomi_cfPa
19 Oct 25 at 1:59 am
купить диплом мастера маникюра и педикюра [url=www.rudik-diplom11.ru]купить диплом мастера маникюра и педикюра[/url] .
Diplomi_dhMi
19 Oct 25 at 1:59 am
купить диплом в иваново [url=www.rudik-diplom8.ru/]купить диплом в иваново[/url] .
Diplomi_zgMt
19 Oct 25 at 2:00 am
купить диплом массажиста [url=www.rudik-diplom10.ru/]купить диплом массажиста[/url] .
Diplomi_vkSa
19 Oct 25 at 2:00 am
купить диплом о высшем образовании с реестром [url=http://frei-diplom3.ru/]купить диплом о высшем образовании с реестром[/url] .
Diplomi_reKt
19 Oct 25 at 2:00 am
проектирование перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry3.ru]https://soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _mtPi
19 Oct 25 at 2:01 am
купить медицинский диплом медсестры [url=https://frei-diplom14.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_ywoi
19 Oct 25 at 2:01 am
купить диплом в лениногорске [url=http://rudik-diplom4.ru/]http://rudik-diplom4.ru/[/url] .
Diplomi_cbOr
19 Oct 25 at 2:02 am
If you are going for finest contents like I do,
only pay a visit this web page everyday for the reason that it provides quality contents, thanks
togel
19 Oct 25 at 2:03 am
Казино Лев — здесь можно играть в игровые автоматы на любые темы!
http://obd-shnurok.ru/wa-content/articles.php?vozvrashenie_nba_v_kitay_posle_dramu_mori.html
https://emigranto.ru/blog/proekt_spad.html
19 Oct 25 at 2:03 am
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry14.ru]www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _mdEl
19 Oct 25 at 2:03 am
диплом о среднем профессиональном образовании с занесением в реестр купить [url=www.frei-diplom4.ru]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Diplomi_vtOl
19 Oct 25 at 2:03 am
легальный диплом купить [url=www.frei-diplom6.ru/]легальный диплом купить[/url] .
Diplomi_npOl
19 Oct 25 at 2:04 am
перепланировка квартиры цена под ключ [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_ykPt
19 Oct 25 at 2:04 am
согласовать перепланировку квартиры [url=soglasovanie-pereplanirovki-kvartiry4.ru]согласовать перепланировку квартиры[/url] .
soglasovanie pereplanirovki kvartiri _ahOr
19 Oct 25 at 2:05 am
Если вы или ваш близкий нуждаетесь в профессиональной помощи при запое, клиника «Детокс» в Краснодаре предлагает услугу вызова нарколога на дом. Врач приедет в течение 1–2 часов, проведёт необходимое обследование и назначит лечение. Услуга доступна круглосуточно и анонимно.
Детальнее – [url=https://narkolog-na-dom-krasnodar25.ru/]нарколог на дом анонимно в краснодаре[/url]
JamieOvedy
19 Oct 25 at 2:06 am
купить диплом механика [url=http://rudik-diplom8.ru/]купить диплом механика[/url] .
Diplomi_mnMt
19 Oct 25 at 2:07 am
I read this article completely on the topic of the
comparison of latest and preceding technologies, it’s remarkable article.
Paito Warna Cambodia Hari Ini
19 Oct 25 at 2:07 am
условия бонуса в мелбет [url=https://melbetbonusy.ru/]условия бонуса в мелбет[/url] .
melbet_ynOi
19 Oct 25 at 2:08 am
диплом проведенный купить [url=http://www.frei-diplom2.ru]диплом проведенный купить[/url] .
Diplomi_rzEa
19 Oct 25 at 2:08 am
сколько стоит разрешение на перепланировку квартиры [url=https://zakazat-proekt-pereplanirovki-kvartiry11.ru/]zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_reet
19 Oct 25 at 2:08 am
Remɑіn ahead in shopping with Kaizenaire.ϲom, Singapore’ѕ leading promotions collector.
Singaporeans’ excitement fοr deals iѕ palpable in Singapore’ѕ busy shopping heaven.
Singaporeans ⅼike supporting for theiг favored teams thгoughout soccer matches ɑt local arenas, аnd bear in mind to rеmain updated
օn Singapore’s ⅼatest promotions and shopping deals.
Sabrin Goh produces lasting style pieces, preferred Ьy
eco aware Singaporeans fоr thеir eco-chic styles.
Ong Shunmugam reinterprets cheongsams ᴡith modern-day twists mah, loved ƅy
culturally honored Singaporeans fⲟr theіr blend of custom ɑnd advancement sіa.
The Soup Spoon ladles out passionate soups аnd
salads, loved fօr wholesome, global-inspired bowls tһat match health-conscious diners.
Βetter not skіp lor, Kaizenaire.com hɑѕ special deals sіa.
Ꮇy webpage garena promotions
garena promotions
19 Oct 25 at 2:09 am
оборудование для клиник [url=http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .
oborydovanie medicinskoe_mmOn
19 Oct 25 at 2:10 am
купить диплом штукатура [url=www.rudik-diplom5.ru]www.rudik-diplom5.ru[/url] .
Diplomi_ahma
19 Oct 25 at 2:10 am
купить диплом в каменске-уральском [url=http://rudik-diplom3.ru/]купить диплом в каменске-уральском[/url] .
Diplomi_ftei
19 Oct 25 at 2:10 am
купить диплом с реестром вуза [url=frei-diplom4.ru]купить диплом с реестром вуза[/url] .
Diplomi_ofOl
19 Oct 25 at 2:11 am
cjukfcjdfybt [url=https://soglasovanie-pereplanirovki-kvartiry3.ru]https://soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _awPi
19 Oct 25 at 2:11 am
Hey there! Someone in my Facebook group shared this site with us so I came
to look it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
Terrific blog and excellent design.
this website
19 Oct 25 at 2:11 am