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!
PilloleVerdi: miglior prezzo Cialis originale – acquistare Cialis online Italia
JosephPseus
18 Oct 25 at 4:54 pm
https://t.me/Official_1xbet_1xbet/1683
Josephadvem
18 Oct 25 at 4:54 pm
https://t.me/Official_1xbet_1xbet/1703
Josephadvem
18 Oct 25 at 4:55 pm
согласование перепланировки квартиры [url=https://www.soglasovanie-pereplanirovki-kvartiry3.ru]https://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _nhPi
18 Oct 25 at 4:57 pm
узаконить перепланировку стоимость [url=https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_wvPt
18 Oct 25 at 4:57 pm
проектная организация перепланировка [url=proekt-pereplanirovki-kvartiry16.ru]proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_ciMl
18 Oct 25 at 5:01 pm
В ТЕЧЕНИЕ очерк [url=https://www.igor-scherbakov.ru/muzykant-v-sovremennom-mire]«Шумовик в современном ладе»[/url] дискуссируется роль артиста в течение эпоху цифровых технологий. Щербаков ратифицирует, что подлинное эстрада остаётся потребованным, если оно искренне. Его умозрение побуждает хранить честность призванию.
AnWap
18 Oct 25 at 5:02 pm
Wonderful site you have here but I was wanting to know if you knew of
any message boards that cover the same topics talked about
here? I’d really like to be a part of online community where I can get feed-back from other experienced individuals that share the same interest.
If you have any recommendations, please let me know.
Appreciate it!
Best road trip gear for dogs
18 Oct 25 at 5:03 pm
фрибеты мелбет [url=https://melbetbonusy.ru/]фрибеты мелбет[/url] .
melbet_cwOi
18 Oct 25 at 5:05 pm
Najlepsze kasyno online w Polsce
Dolacz do [url=https://billionaire-casino.pl/]billionaire casino huuge[/url]
i ciesz sie najlepszymi grami online, zakladami sportowymi i ekscytujacymi bonusami w Polsce.
WilliamLit
18 Oct 25 at 5:06 pm
лечение запоя смоленск
vivod-iz-zapoya-smolensk024.ru
вывод из запоя круглосуточно
zapojsmolenskNeT
18 Oct 25 at 5:07 pm
сколько стоит перепланировка [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru/]http://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_wdet
18 Oct 25 at 5:07 pm
I’m not sure where you are getting your info, but great topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent information I was looking for this information for my mission.
thuong thuc phim nguoi lon moi nhat
18 Oct 25 at 5:07 pm
tadalafilo sin receta: comprar Cialis online España – tadalafilo sin receta
JosephPseus
18 Oct 25 at 5:08 pm
мелбет промокод на депозит
регистрация мелбет промокод
18 Oct 25 at 5:09 pm
metaboost.click – Just visited the site, the layout is clean and the navigation flows nicely.
Pura Jason
18 Oct 25 at 5:09 pm
шины для минипогрузчиков
RalphTheno
18 Oct 25 at 5:10 pm
перепланировки квартир [url=soglasovanie-pereplanirovki-kvartiry3.ru]soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _cpPi
18 Oct 25 at 5:12 pm
можно купить диплом медсестры [url=http://frei-diplom14.ru]можно купить диплом медсестры[/url] .
Diplomi_jfoi
18 Oct 25 at 5:13 pm
проект для перепланировки квартиры стоимость [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru]http://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_qmet
18 Oct 25 at 5:14 pm
перепланировки квартир [url=https://soglasovanie-pereplanirovki-kvartiry4.ru/]soglasovanie-pereplanirovki-kvartiry4.ru[/url] .
soglasovanie pereplanirovki kvartiri _avOr
18 Oct 25 at 5:15 pm
seowhale.click – The colour palette is subtle and pleasing, doesn’t distract from reading.
Graham Hodermarsky
18 Oct 25 at 5:15 pm
перепланировка согласование [url=http://soglasovanie-pereplanirovki-kvartiry11.ru/]http://soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _unMi
18 Oct 25 at 5:19 pm
согласованте [url=http://www.soglasovanie-pereplanirovki-kvartiry11.ru]http://www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _vhMi
18 Oct 25 at 5:22 pm
по согласованию [url=soglasovanie-pereplanirovki-kvartiry14.ru]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _mlEl
18 Oct 25 at 5:23 pm
https://t.me/s/Official_1xbet_1xbet/1796
Josephadvem
18 Oct 25 at 5:23 pm
For most up-to-date information you have to go to see the web and on world-wide-web I found this website as a most excellent site for hottest
updates.
เบ็ตฟลิก93
18 Oct 25 at 5:23 pm
click through the next website
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
click through the next website
18 Oct 25 at 5:23 pm
изготовление проекта перепланировки [url=https://proekt-pereplanirovki-kvartiry17.ru]изготовление проекта перепланировки[/url] .
proekt pereplanirovki kvartiri_hrml
18 Oct 25 at 5:24 pm
melbet [url=https://melbetbonusy.ru]melbet[/url] .
melbet_yhOi
18 Oct 25 at 5:25 pm
заказ перепланировки квартиры [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _kzEl
18 Oct 25 at 5:25 pm
перепланировка квартиры согласование [url=http://soglasovanie-pereplanirovki-kvartiry3.ru]http://soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _xnPi
18 Oct 25 at 5:26 pm
mostbet [url=https://www.mostbet4182.ru]https://www.mostbet4182.ru[/url]
mostbet_uz_oxkt
18 Oct 25 at 5:26 pm
купить диплом медсестры [url=www.frei-diplom14.ru/]купить диплом медсестры[/url] .
Diplomi_wkoi
18 Oct 25 at 5:26 pm
Pretty! This was a really wonderful article.
Thank you for providing this information.
https://www.theepochtimes.com/epochfun/word-roundup-4016913
18 Oct 25 at 5:28 pm
согласовать перепланировку квартиры [url=soglasovanie-pereplanirovki-kvartiry4.ru]согласовать перепланировку квартиры[/url] .
soglasovanie pereplanirovki kvartiri _poOr
18 Oct 25 at 5:28 pm
промокод в мелбет
промокод melbet при регистрации на сегодня
18 Oct 25 at 5:30 pm
проектная организация москва перепланировка квартиры [url=https://proekt-pereplanirovki-kvartiry17.ru/]https://proekt-pereplanirovki-kvartiry17.ru/[/url] .
proekt pereplanirovki kvartiri_rqml
18 Oct 25 at 5:30 pm
нужен проект перепланировки [url=http://www.proekt-pereplanirovki-kvartiry16.ru]http://www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_puMl
18 Oct 25 at 5:31 pm
стоимость перепланировки в бти [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_apPt
18 Oct 25 at 5:32 pm
заказ перепланировки квартиры [url=www.soglasovanie-pereplanirovki-kvartiry11.ru/]www.soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _ybMi
18 Oct 25 at 5:32 pm
Hello, constantly i used to check blog posts here in the early hours in the morning, because i love to learn more and more.
転職 技術
18 Oct 25 at 5:34 pm
Если пациент не может приехать в клинику, в Краснодаре нарколог приедет к нему домой. Помощь оказывает «Детокс» круглосуточно.
Изучить вопрос глубже – [url=https://narkolog-na-dom-krasnodar25.ru/]нарколог на дом цены в краснодаре[/url]
JamieOvedy
18 Oct 25 at 5:34 pm
согласование перепланировки цена в москве [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_zaPt
18 Oct 25 at 5:35 pm
услуги по согласованию перепланировки квартиры [url=soglasovanie-pereplanirovki-kvartiry14.ru]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _yvEl
18 Oct 25 at 5:35 pm
изготовление проекта перепланировки [url=www.proekt-pereplanirovki-kvartiry16.ru/]www.proekt-pereplanirovki-kvartiry16.ru/[/url] .
proekt pereplanirovki kvartiri_yhMl
18 Oct 25 at 5:36 pm
перепланировка под ключ цена [url=zakazat-proekt-pereplanirovki-kvartiry11.ru]zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_vtet
18 Oct 25 at 5:37 pm
сколько стоит купить диплом медсестры [url=www.frei-diplom14.ru/]сколько стоит купить диплом медсестры[/url] .
Diplomi_rboi
18 Oct 25 at 5:37 pm
Secondary school math tuition іs impօrtant іn Singapore, offering your
child access to experienced educators post-PSLE.
Heng lah, ѡith suсһ high scores, Singapore leads іn math globally!
Parents, excellence structure with Singapore math tuition’s synonym.
Secondary math tuition basics սpon builds. Ԝith secondary 1 math
tuition, graphed charts.
Ingenious tasks іn secondary 2 math tuition сreate designs.
Secondary 2 math tuition consatructs geometric structures.
Hands-оn secondary 2 math tuition reinforces theory. Secondary 2 math tuition triggers imagination.
Secondary 3 math exams hold tremendous weight, tɑking plаce
a yеаr beforе O-Levels, where cumulative mastery іs tested.
Hіgh accomplishment enables optional focus іn Sеⅽ 4, expanding horizons.
It promotes ethical гesearch study practices tһat endure bеyond exams.
Thе Singapore education ѕystem positions secondary 4
exams ɑt the heart of student evaluation, makіng math proficiency neϲessary.
Secondary 4 math tuition supplies customized strategies fоr data analysis topics.
Trainees take advantage оf expert feedback, improving tһeir
skills foг nationals. Secondary 4 math tuition ⅽhanges prospective іnto achievement in tһеse impoгtant
evaluations.
Wһile exams arre ѕignificant, math stands as a key ability іn the AI
еra, driving innovations in augmented reality.
Ꭲo excel іn mathematics, nurture love fⲟr thе subject ɑnd usе math principles in daily
life applications.
Τhe practice іѕ crucial fоr integrating feedback from mock tests based օn varіous Singapore secondary school papers.
Online math tuition е-learning platforms in Singapore improve
performance Ƅy archiving sessions f᧐r long-term reference.
Eh lor, steady siɑ, yοur kid ѡill excel in secondary school, ⅾоn’t stress tһem unduly.
OMT’ѕ seⅼf-paced e-learning ѕystem ɑllows students tо explore math аt their own rhythm,
changing aggravation іnto fascination ɑnd inspiring excellent examination efficiency.
Ԍet ready for success іn upcoming tests ᴡith OMT Math Tuition’s proprietary curriculum, ϲreated
tο cultivate critical thinking ɑnd confidence in еvery trainee.
Singapore’ѕ emphasis օn іmportant analyzing mathematics highlights tһe value of math tuition, which helps students develop tһe analytical
abilities demanded Ƅү thе nation’s forward-thinking syllabus.
primary tuition іs essential fоr developing durability
versus PSLE’ѕ challenging questions, ѕuch as those on probabilty аnd easy
data.
Tuition fosters sophisticated analytic skills, essential f᧐r addressing tһe complex, multi-step questions tһɑt define О Level
math obstacles.
Junior college math tuition promotes joint learning іn smalⅼ
groսps, enhancing peer conversations on complicated Α Level principles.
Ԝhat sets apart OMT iѕ its proprietary program tһat matches MOE’ѕ via focus on moral analytical іn mathematical contexts.
OMT’s online neighborhood supplies assistance leh, ԝhere you can ask inquiries and improve your learning for far Ьetter qualities.
Tuition facilities іn Singapore specialize іn heuristic techniques,
crucial f᧐r dealing with tһe challenging ѡorԁ problemѕ in math examinations.
Ꭺlso visit my web paɡe maths tuition near me
maths tuition near me
18 Oct 25 at 5:38 pm
1xbet afrique apk pronostic foot gratuit
parifoot-533
18 Oct 25 at 5:38 pm