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!
Estou alucinado com JonBet Casino, tem uma energia de jogo tao pulsante quanto um eco em caverna. O catalogo de jogos e uma camara de prazeres. com caca-niqueis que vibram como harpas. O atendimento esta sempre ativo 24/7. com solucoes precisas e instantaneas. Os saques vibram como harpas. porem as ofertas podiam ser mais generosas. Para encurtar, JonBet Casino e o point perfeito pros fas de cassino para os maestros do cassino! De bonus o design e fluido como uma onda sonora. elevando a imersao ao nivel de um coral.
saque minimo jonbet|
twistycosmicllama3zef
18 Oct 25 at 6:48 am
Your method of describing everything in this
piece of writing is genuinely good, all be capable of simply understand it,
Thanks a lot.
homepage
18 Oct 25 at 6:49 am
https://t.me/s/Official_1xbet_1xbet/1801
Josephadvem
18 Oct 25 at 6:49 am
https://t.me/s/Official_1xbet_1xbet/1788
Josephadvem
18 Oct 25 at 6:50 am
https://potenzvital.com/# Cialis Preisvergleich Deutschland
MickeySum
18 Oct 25 at 6:50 am
В «Частном Медике 24» в Самаре лечение организовано так, чтобы пациент чувствовал себя безопасно и защищённо.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]вывод из запоя в стационаре анонимно самара[/url]
Williamliz
18 Oct 25 at 6:51 am
linebet download
linebet play online
18 Oct 25 at 6:51 am
Having read this I thought it was really enlightening. I appreciate you finding the time and effort
to put this information together. I once again find myself spending a significant amount of time both reading and posting comments.
But so what, it was still worth it!
Dravexoly
18 Oct 25 at 6:52 am
mostbet uz jonli tikish [url=mostbet4185.ru]mostbet4185.ru[/url]
mostbet_uz_qoer
18 Oct 25 at 6:52 am
Singapore’s syѕtem highlights secondary school math tuition аs key for building foundational skills іn Secondary 1 math.
Ꭰon’t play play leh, Singapore’ѕ lead іn international math іs real!
As moms and dads, transform learning ԝith Singapore math tuition’s reflection. Secondary math tuition encourages practice.
Ƭhrough secondary 1 math tuition, trrig ratios
engage.
Secondary 2 math tuition ⲟffers multilingual resources.
Secondary 2 math tuition supports native tongue combination. Culturally delicate secondary 2 math
tuition resonates. Secondary 2 math tuition honors variety.
Ꮤith O-Levels ⲟn the horizon, secondary 3 math exams emphasize excellence.
Тhese outcomes influence curricula enrichment.
Success promotes practical solving.
Тhe pivotal secondary 4 exams check оut heritage іn Singapore.
Secondary 4 math tuition decodess art ρoint of views. This culture enhances O-Level understanding.
Secondary 4 math tuition values ⲣast.
Mathematics extends fаr bеyond exam success; it’ѕ an indispensable skill іn the AI boom, enabling professionals to design algorithms tһat mimic human intelligence.
Ƭo achieve math mastery, love mathematics ɑnd apply principles in real-life daily routines.
Ϝor optimal гesults, past math papers from different schools help іn setting personal benchmarks fօr Singapore secondary tests.
Usіng online math tuition e-learning systems іn Singapore boosts exam performance ᴡith
multilingual subtitles.
Alamak leh, ɗon’t fret lah, secondary school teachers caring, support ԝithout pressure.
Bү connecting mathematics to innovative tasks,
OMT awakens аn enthusiasm in pupils, motivating tһem to accept the subject ɑnd
pursue test mastery.
Dive іnto self-paced math proficiency ѡith OMT’s 12-month e-learning courses, ϲomplete ᴡith practice worksheets аnd tape-recorded
sessions fⲟr extensive revision.
As math forms thе bedrock ⲟf rational thinking ɑnd vital analytical іn Singapore’s education systеm, professional math tuition оffers the tailored guidance neсessary to tuгn obstacless іnto triumphs.
Witһ PSLE math evolving tо іnclude more interdisciplinary components,
tuition қeeps trainees updated οn incorporated concerns mixing math ѡith science contexts.
By սsing extensive experiment pаst O Level papers, tuition equips students ѡith experience and the capability t᧐ prepare for question patterns.
Junior college math tuition iѕ vital for A Levels аs it strengthens
understanding ⲟf sophisticated calculus subjects ⅼike integration strategies ɑnd differential equations, ѡhich aгe main to the exam syllabus.
What differentiates OMT іs its custom-made curriculum thаt
aligns wіth MOE wһile concentrating on metacognitive abilities, teaching pupils еxactly how to learn math effectively.
Endless retries оn quizzes ѕia, best for understanding subjects ɑnd accomplishing tһose A grades in mathematics.
Ꮃith evolving MOE standards, math tuition қeeps Singapore pupils upgraded
ⲟn syllabus modifications for exam readiness.
secondary 1 math tuition
18 Oct 25 at 6:52 am
Слив курсов подготовки ЕГЭ профильная математика https://courses-ege.ru
courses-ege-336
18 Oct 25 at 6:53 am
заказ перепланировки квартиры [url=www.soglasovanie-pereplanirovki-kvartiry3.ru/]www.soglasovanie-pereplanirovki-kvartiry3.ru/[/url] .
soglasovanie pereplanirovki kvartiri _ydPi
18 Oct 25 at 6:54 am
букмекер мелбет [url=https://www.melbetbonusy.ru]букмекер мелбет[/url] .
melbet_heOi
18 Oct 25 at 6:56 am
официальный сайт мелбет [url=http://melbetbonusy.ru]официальный сайт мелбет[/url] .
melbet_efOi
18 Oct 25 at 6:56 am
заказать перепланировку [url=http://www.soglasovanie-pereplanirovki-kvartiry11.ru]http://www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _slMi
18 Oct 25 at 6:57 am
оформление перепланировки квартиры цена [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru]http://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_wyet
18 Oct 25 at 6:57 am
проект перепланировки для согласования [url=www.proekt-pereplanirovki-kvartiry16.ru/]www.proekt-pereplanirovki-kvartiry16.ru/[/url] .
proekt pereplanirovki kvartiri_nrMl
18 Oct 25 at 6:58 am
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 token
WilliamPargy
18 Oct 25 at 6:58 am
согласование перепланировок [url=https://soglasovanie-pereplanirovki-kvartiry14.ru]https://soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _clEl
18 Oct 25 at 6:59 am
Стационарная детоксикация от алкоголя в Воронеже — восстановление организма под наблюдением специалистов. Мы проводим процедуры очищения организма от токсинов, восстанавливая физическое и психоэмоциональное состояние пациента.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]наркология вывод из запоя в стационаре в воронеже[/url]
RichardJuids
18 Oct 25 at 7:00 am
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ɗr c121,
Charlotte, NC 28273, United Ꮪtates
+19803517882
Bookmarks
Bookmarks
18 Oct 25 at 7:00 am
yoga lying down
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
yoga lying down
18 Oct 25 at 7:04 am
стоимость согласования перепланировки квартиры в москве [url=https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_avPt
18 Oct 25 at 7:05 am
investsmarttoday – Excellent explanations and tips, saves a lot of time learning today.
Johnna Ruggerio
18 Oct 25 at 7:05 am
Покупка номера телефона
Ricardopam
18 Oct 25 at 7:08 am
заказать проект перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry16.ru/]www.proekt-pereplanirovki-kvartiry16.ru/[/url] .
proekt pereplanirovki kvartiri_zwMl
18 Oct 25 at 7:08 am
online meet
MichaelSig
18 Oct 25 at 7:08 am
Сливы онлайн курсов ЕГЭ https://courses-ege.ru
courses-ege-466
18 Oct 25 at 7:11 am
I don’t know if it’s just me or if everybody else encountering
issues with your website. It appears like some of the text
in your posts are running off the screen. Can somebody
else please comment and let me know if this is happening to them too?
This might be a problem with my browser because I’ve had this happen before.
Cheers
1 year mba in malaysia
18 Oct 25 at 7:11 am
Подготовка к ЕГЭ 2025 курсы https://courses-ege.ru
courses-ege-25
18 Oct 25 at 7:11 am
Купить виртуальный номер
Ricardopam
18 Oct 25 at 7:13 am
https://t.me/s/Official_1xbet_1xbet/1825
Josephadvem
18 Oct 25 at 7:13 am
Подготовка к IELTS в CT Group начинается с диагностики и индивидуального плана, затем — целевые тренировки по всем модулям. Ищете https://www.ctgroup.kz/ielts? ctgroup.kz/ielts — это точка входа: расписания, запись на поток или индивидуальные занятия, описание программ. Акцент на стратегии: разбор критериев, типовых ловушек и структур ответов для стабильного результата. Регулярные мини-моки и контроль прогресса помогают держать темп до экзамена.
wolubifex
18 Oct 25 at 7:15 am
соглосование [url=www.soglasovanie-pereplanirovki-kvartiry3.ru]www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _ukPi
18 Oct 25 at 7:16 am
мелбет бонус на депозит [url=https://melbetbonusy.ru/]мелбет бонус на депозит[/url] .
melbet_lcOi
18 Oct 25 at 7:16 am
где согласовать перепланировку квартиры [url=http://soglasovanie-pereplanirovki-kvartiry11.ru/]http://soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _beMi
18 Oct 25 at 7:16 am
First of all I want to say great blog! I had a
quick question in which I’d like to ask if you do not mind.
I was interested to know how you center yourself and clear your head prior to writing.
I have had a hard time clearing my thoughts in getting my ideas out there.
I truly do take pleasure in writing however it just seems like the
first 10 to 15 minutes are usually lost simply just trying to figure out how to begin. Any ideas
or tips? Thank you!
FreundGentak Erfahrungen
18 Oct 25 at 7:17 am
https://t.me/s/Official_1xbet_1xbet/1794
Josephadvem
18 Oct 25 at 7:18 am
https://t.me/Official_1xbet_1xbet/1719
Josephadvem
18 Oct 25 at 7:19 am
перепланировка согласование [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _khEl
18 Oct 25 at 7:19 am
программы https://softprogram-free.ru/
Maximodaf
18 Oct 25 at 7:21 am
Reefresh Renovation Broomfield
11001 Ԝ 120th Ave 400 suite 459а,
Broomfield, СO 80021, United Stаtes
+13032681372
Services renovations and remodeling home
Services renovations and remodeling home
18 Oct 25 at 7:21 am
Estou vidrado no BacanaPlay Casino, e um cassino online que explode como um desfile de carnaval. As opcoes de jogo no cassino sao ricas e cheias de gingado, com jogos de cassino perfeitos pra criptomoedas. A equipe do cassino entrega um atendimento que e puro carnaval, garantindo suporte de cassino direto e sem perder o ritmo. O processo do cassino e limpo e sem tumulto, mesmo assim mais recompensas no cassino seriam um diferencial festivo. No fim das contas, BacanaPlay Casino vale demais sambar nesse cassino para os apaixonados por slots modernos de cassino! Alem disso o design do cassino e um desfile visual vibrante, adiciona um toque de folia ao cassino.
bacanaplay casino review|
fizzylightningotter2zef
18 Oct 25 at 7:24 am
согласование [url=http://soglasovanie-pereplanirovki-kvartiry4.ru]согласование[/url] .
soglasovanie pereplanirovki kvartiri _inOr
18 Oct 25 at 7:24 am
сделать проект перепланировки квартиры [url=https://www.proekt-pereplanirovki-kvartiry16.ru]https://www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_mdMl
18 Oct 25 at 7:24 am
вывод из запоя круглосуточно смоленск
vivod-iz-zapoya-smolensk023.ru
лечение запоя смоленск
vivodsmolenskNeT
18 Oct 25 at 7:25 am
букмекерская контора мелбет официальный сайт [url=www.melbetbonusy.ru]букмекерская контора мелбет официальный сайт[/url] .
melbet_aqOi
18 Oct 25 at 7:26 am
стоимость оформления перепланировки [url=http://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]http://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_khPt
18 Oct 25 at 7:26 am
заказать перепланировку [url=www.soglasovanie-pereplanirovki-kvartiry11.ru]www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _arMi
18 Oct 25 at 7:27 am
show updates
MichaelSig
18 Oct 25 at 7:30 am