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://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]www.vyvod-iz-zapoya-v-stacionare-voronezh22.ru[/url]
RichardJuids
18 Oct 25 at 11:56 am
мосбет [url=https://www.mostbet4185.ru]мосбет[/url]
mostbet_uz_kfer
18 Oct 25 at 11:57 am
Kaizenaire.ai Ьecomes a trusted Singapore recruitment agency, assisting іn remote talent acquisition from the Philippines with AΙ fοr efficient onboarding ɑnd efficiency tracking.
With Singapore’s pumped up labor rates and increasing organization concerns, engaging overseas employees fгom tһe Philippines іs clever organization, conserving 70% օn continual labor expenses.
АI empowers thеm to perform at the exact ѕame һigh quality
as residents.
Because оf today’s AΙ lanndscape and difficult environment,
Singapore proprietors require t᧐ rush to examine tһeir business structures ɑnd procedures, embracing
ᎪI automation ѡithout hold-ᥙρ. ΑI cߋntinues to evolve rapidly.
Kaizenaire іs an innovative Singapore recruitment agency tһat focuses on assisting Singapore business employ innovative workers fгom tһe Philippines,
utilizing АI tools to enable remote designers tⲟ craft blog site material аnd perform social media marketing tasks.
Іt’s essential to reconsider tһe function of AI alongside remote teams іn service evolutions.
Ηave a ⅼook at Kaizenaire, Singapore’s forward-thinking recruitment agency
tailored tօ remote hiring requirements.
Ꮇy webpage send resume to recruitment agency singapore
send resume to recruitment agency singapore
18 Oct 25 at 11:59 am
It’s truly vey complex in this active lifve to listen neqs on TV, thus I only use world wide web for
that reason, annd obtain the most up-to-date news.
Look into my webpage: web designer kuala lumpur
web designer kuala lumpur
18 Oct 25 at 11:59 am
mostbet uz yuklab olish android [url=https://mostbet4185.ru/]https://mostbet4185.ru/[/url]
mostbet_uz_dcer
18 Oct 25 at 11:59 am
https://t.me/Official_1xbet_1xbet/1836
Josephadvem
18 Oct 25 at 12:01 pm
Вывод из запоя в клинике «Частный Медик 24» в Воронеже проводится по стандартной и премиум-программе, цена от 6500 ?, где важнейший акцент — на здоровье пациента: предотвращение осложнений, восстановление баланса жидкости и электролитов, поддержка психологического состояния.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh23.ru/]вывод из запоя в стационаре[/url]
Anthonyvom
18 Oct 25 at 12:02 pm
Estou completamente apaixonado por BacanaPlay Casino, parece uma festa carioca cheia de axe. Tem uma enxurrada de jogos de cassino irados, com jogos de cassino perfeitos pra criptomoedas. O atendimento ao cliente do cassino e uma rainha de bateria, respondendo mais rapido que um batuque de pandeiro. Os ganhos do cassino chegam voando como confetes, mesmo assim mais bonus regulares no cassino seria brabo. Na real, BacanaPlay Casino e um cassino online que e uma folia sem fim para quem curte apostar com gingado no cassino! Vale dizer tambem o design do cassino e um desfile visual vibrante, eleva a imersao no cassino ao ritmo de um tamborim.
bacanaplay em portugal|
fizzylightningotter2zef
18 Oct 25 at 12:02 pm
and if I could _feel_ gratitude,I would now thank you.?コスプレ かわいい
コスプレ えろ
18 Oct 25 at 12:03 pm
купить медицинский диплом медсестры [url=http://frei-diplom14.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_iloi
18 Oct 25 at 12:03 pm
TG @‌LINKS_DEALER | EFFECTIVE SEO LINKS FOR SPINBETTER.BET
CharlesTHOTH
18 Oct 25 at 12:06 pm
please click the up coming website page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
please click the up coming website page
18 Oct 25 at 12:06 pm
нужен проект перепланировки квартиры [url=http://www.proekt-pereplanirovki-kvartiry16.ru]http://www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_uoMl
18 Oct 25 at 12:06 pm
Fiquei impressionado com BETesporte Casino, proporciona uma aventura cheia de emocao. O catalogo e vibrante e diversificado, com sessoes ao vivo cheias de energia. Eleva a experiencia de jogo. O suporte ao cliente e excepcional, acessivel a qualquer hora. Os pagamentos sao seguros e fluidos, no entanto recompensas extras seriam um hat-trick. Resumindo, BETesporte Casino garante diversao constante para jogadores em busca de emocao ! Tambem a interface e fluida e energetica, tornando cada sessao mais competitiva. Muito atrativo os torneios regulares para rivalidade, oferece recompensas continuas.
Encontrar os detalhes|
VortexGoalW2zef
18 Oct 25 at 12:06 pm
hello!,I love your writing so so much! proportion we communicate more approximately your article on AOL?
I need a specialist in this area to resolve my problem.
Maybe that is you! Taking a look ahead to peer you.
martin казино приложение
18 Oct 25 at 12:12 pm
Your style is very unique in comparison to other folks I’ve read stuff from.
Many thanks for posting when you’ve got the opportunity, Guess
I will just book mark this page.
go99
18 Oct 25 at 12:13 pm
мел бет букмекерская контора официальный сайт [url=http://www.melbetbonusy.ru]мел бет букмекерская контора официальный сайт[/url] .
melbet_lnOi
18 Oct 25 at 12:15 pm
где заказать проект перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry17.ru/]www.proekt-pereplanirovki-kvartiry17.ru/[/url] .
proekt pereplanirovki kvartiri_hqml
18 Oct 25 at 12:15 pm
перепланировка [url=http://soglasovanie-pereplanirovki-kvartiry4.ru/]перепланировка[/url] .
soglasovanie pereplanirovki kvartiri _gqOr
18 Oct 25 at 12:15 pm
https://sabinasara.pointblog.net/c%C3%B3digo-promocional-1xbet-bono-120-hasta-130-85539262
https://sabinasara.pointblog.net/cdigo-promocional-1xbet-bono-120-hasta-130-85539262
18 Oct 25 at 12:16 pm
My partner and I absolutely love your blog and find almost all of your post’s
to be exactly what I’m looking for. Does one offer
guest writers to write content for yourself?
I wouldn’t mind writing a post or elaborating on a few of the subjects you write with
regards to here. Again, awesome blog!
https://23wintop1.com
18 Oct 25 at 12:16 pm
Тhe inteгest of OMT’s founder, Ⅿr. Justin Tan,
shines via in teachings, encouraging Singapore trainees to drop in llve wіth math for exam
success.
Expand үouг horizons ѡith OMT’s upcoming brand-neѡ physical area opеning
in Seⲣtember 2025, uѕing mսch more opportunities for hands-on math expedition.
Ƭhe holistic Singapore Math method, ѡhich builds multilayered pгoblem-solving abilities, underscores ѡhy
math tuition іѕ essential for mastering tһе curriculum and preparing fоr future professions.
Enrolling іn primary school math tuition еarly fosters confidence,
reducing stress ɑnd anxiety for PSLE takers ѡһo face high-stakes concerns
оn speed, range, and timе.
Structure confidence tһrough consistent tuition assistance іs crucial, аs Ο Levels can be demanding, and ceгtain trainees perform fаr bеtter under pressure.
Tuition gіves аpproaches fօr time management thrοughout the lengthy Α Level math
examinations, permitting students tо allot initiatives sucϲessfully
acrosѕ arеas.
What mаkes OMT extraordinary iѕ its proprietary curriculum tһаt straightens with MOE while introducing aesthetic aids ⅼike
bar modeling іn innovative mеans for primary students.
OMT’s on-ⅼine math tuition lets you modify at youг very ⲟwn speed
lah, ѕo say gⲟodbye to hurrying and your math qualities will skyrocket continuously.
Tuition reveals pupils tօ diverse inquiry kinds, expanding theiг readiness
for unpredictable Singapore mathematics tests.
My blog post :: maths tuition centre singapore (https://Thedailyfeeder.com)
https://Thedailyfeeder.com
18 Oct 25 at 12:19 pm
code promo linebet maroc
linebet ????? ?????
18 Oct 25 at 12:19 pm
сколько стоит согласовать перепланировку [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru/]http://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_tqet
18 Oct 25 at 12:20 pm
проект перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry16.ru]www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_lmMl
18 Oct 25 at 12:20 pm
https://melbetbonusy.ru [url=https://www.melbetbonusy.ru]https://melbetbonusy.ru[/url] .
melbet_gyOi
18 Oct 25 at 12:20 pm
https://participez.nouvelle-aquitaine.fr/profiles/jonas_baker/activity?locale=en
MyronTuh
18 Oct 25 at 12:21 pm
I really like your blog.. very nice colors & theme.
Did you make this website yourself or did you hire
someone to do it for you? Plz respond as I’m looking to create my own blog and would like to
know where u got this from. thanks a lot
Voxigenai
18 Oct 25 at 12:22 pm
recent post by onefinething.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
recent post by onefinething.click
18 Oct 25 at 12:23 pm
A person necessarily help to make significantly posts I’d state.
This is the first time I frequented your website page and
thus far? I surprised with the analysis you made to
make this actual submit amazing. Great activity!
JetRehber.com
18 Oct 25 at 12:23 pm
https://t.me/s/Official_1xbet_1xbet/1838
Josephadvem
18 Oct 25 at 12:24 pm
Если вы ищете надежную клинику для вывода из запоя в Сочи, обратитесь в «Детокс». Здесь опытные специалисты окажут необходимую помощь в стационаре. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-sochi22.ru/]www.vyvod-iz-zapoya-sochi22.ru[/url]
BillyWoult
18 Oct 25 at 12:24 pm
сколько стоит узаконить перепланировку в москве [url=www.zakazat-proekt-pereplanirovki-kvartiry11.ru]www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_wtet
18 Oct 25 at 12:25 pm
https://t.me/Official_1xbet_1xbet/1815
Josephadvem
18 Oct 25 at 12:25 pm
https://t.me/s/Official_1xbet_1xbet/1676
Josephadvem
18 Oct 25 at 12:31 pm
Hi, I do believe your site could be having browser compatibility
issues. When I look at your website in Safari, it
looks fine however, when opening in I.E., it has some overlapping issues.
I just wanted to give you a quick heads up! Apart from that, great blog!
Intel Erymax Pro Avis
18 Oct 25 at 12:36 pm
http://www.hot-web-ads.com/view/item-16253685-sports-betting-bonuses.html
http://www.hot-web-ads.com/view/item-16253685-sports-betting-bonuses.html
18 Oct 25 at 12:38 pm
You should be a part of a contest for one of the greatest sites on the internet.
I most certainly will highly recommend this website!
webpage
18 Oct 25 at 12:39 pm
The Minotaurus presale vesting flexible. Token utility practical. Gaming evolution.
minotaurus coin
WilliamPargy
18 Oct 25 at 12:40 pm
контора мелбет [url=https://melbetbonusy.ru]контора мелбет[/url] .
melbet_khOi
18 Oct 25 at 12:41 pm
Fish pose in yoga
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
Fish pose in yoga
18 Oct 25 at 12:41 pm
This is the perfect blog for everyone who wants to find out about
this topic. You know a whole lot its almost hard to argue with you (not that I actually
would want to…HaHa). You certainly put a new spin on a subject
that’s been discussed for years. Excellent stuff, just wonderful!
melbet casino мобильная версия
18 Oct 25 at 12:45 pm
где заказать проект перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry17.ru/]где заказать проект перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_adml
18 Oct 25 at 12:47 pm
стоимость перепланировки в бти [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru/]http://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_kyet
18 Oct 25 at 12:48 pm
Valuable info. Lucky me I discovered your site unintentionally, and I am shocked why this coincidence didn’t came about in advance!
I bookmarked it.
biweekly house cleaning
18 Oct 25 at 12:49 pm
My brother recommended I might like this blog. He was totally right.
This post actually made my day. You can not imagine just how much time I had spent for this information! Thanks!
data
18 Oct 25 at 12:49 pm
мел бет букмекерская контора официальный сайт [url=melbetbonusy.ru]мел бет букмекерская контора официальный сайт[/url] .
melbet_qlOi
18 Oct 25 at 12:52 pm
И что в таком случае нужно делать?
divine, john’s [url=https://bitokk.io/]https://bitokk.io/[/url] (February 1, 2019). “Which Bitcoin wallet is one of the best?”. Lecture notes on computer science. Gervais, Arthur; O. Karame, Hassan; Gruber, Damian; Kapkun, Srdjan.
MirandaScemi
18 Oct 25 at 12:52 pm
https://t.me/s/Official_1xbet_1xbet/1814
Josephadvem
18 Oct 25 at 12:53 pm
Wow that was unusual. I just wrote an really long
comment but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again. Regardless, just wanted to
say fantastic blog!
Website
18 Oct 25 at 12:54 pm