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!
Нужна вывеска? сделать вывеску для магазина логотипы, надписи, декор для кафе, офисов и дома. Индивидуальный дизайн, энергосберегающие материалы и эффектный свет в любом стиле.
neonovaya vyveska 536
19 Oct 25 at 6:20 pm
https://allmynursejobs.com/author/brandy-morse/
Anthonycam
19 Oct 25 at 6:27 pm
Excited about Minotaurus presale’s DeFi simplicity. $MTAUR’s appreciation potential high. Whimsical mazes fun.
mtaur token
WilliamPargy
19 Oct 25 at 6:28 pm
The ship departs from St. Pete Beach Harbor. It is a quiet space for parties, mostly for people of retirement age from the [url=https://insuranceexplorer.ca/agen-bola-sbobet-indonesia-panduan-lengkap-untuk-77/]https://insuranceexplorer.ca/agen-bola-sbobet-indonesia-panduan-lengkap-untuk-77/[/url].
Kimbiomi
19 Oct 25 at 6:28 pm
melbet букмекерская контора официальный сайт регистрация [url=melbetbonusy.ru]melbetbonusy.ru[/url] .
melbet_fhOi
19 Oct 25 at 6:32 pm
https://matkafasi.com/user/codepromo1xbet2
Lincolnodorn
19 Oct 25 at 6:35 pm
Un Code promo 1xbet 2026 : obtenez un bonus de bienvenue de 100% sur votre premier depot avec un bonus allant jusqu’a 130 €. Placez vos paris en toute plaisir en utilisant simplement les fonds bonus. Apres l’inscription, il est important de recharger votre compte. Si votre compte est verifie, vous pourrez retirer toutes les sommes d’argent, y compris les bonus. Vous pouvez trouver le code promo 1xbet sur ce lien — https://fgvjr.com/pgs/code_promo_163.html.
Marvinspaft
19 Oct 25 at 6:38 pm
1win tikish qanday qilinadi [url=1win5509.ru]1win5509.ru[/url]
1win_uz_skKt
19 Oct 25 at 6:39 pm
купить диплом в краснодаре [url=http://www.rudik-diplom6.ru]купить диплом в краснодаре[/url] .
Diplomi_iwKr
19 Oct 25 at 6:41 pm
1win video translyatsiya [url=1win5509.ru]1win video translyatsiya[/url]
1win_uz_kmKt
19 Oct 25 at 6:42 pm
Its like you read my mind! You seem to know so much about this, like you wrote the book in it
or something. I think that you could do with some pics to drive the
message home a bit, but other than that, this is magnificent blog.
A great read. I’ll definitely be back.
power washing company
19 Oct 25 at 6:43 pm
melbet актуальный промокод
melbet промокод при регистрации бонус
19 Oct 25 at 6:47 pm
kraken ссылка
кракен обмен
JamesDaync
19 Oct 25 at 6:49 pm
бк мелбет [url=https://www.melbetbonusy.ru]бк мелбет[/url] .
melbet_bzOi
19 Oct 25 at 6:49 pm
OMT’s focus on mistake evaluation tᥙrns blunders rіght
intо learning journeys, assisting pupils love mathematics’ѕ forgiving
nature and goal high in examinations.
Dive into self-paced mathematics mastery wіth OMT’s 12-montһ e-learning
courses, tߋtal with practice worksheets and taped sessions for thoгough
revision.
Thе holistic Singapore Math technique, ѡhich develops
multilayered analytical capabilities, underscores ѡhy math
tuition iѕ indispensable fоr mastering the curriculum and preparing fοr future careers.
Ꭲhrough math tuition, trainees practice PSLE-style concerns οn averages ɑnd charts, improving precision аnd speed ᥙnder examination conditions.
Secondary math tuition lays а slid groundwork for post-Ⲟ Level research studies, such as A Levels οr polytechnic programs, Ƅy excelling in fundamental subjects.
Tuition іn junior college math furnishes students ԝith analytical methods
аnd likelihood designs іmportant for analyzing data-driven concerns іn A Level papers.
OMT’ѕ exclusive curriculum boosts MOE standards via
ɑn all natural method that nurtures both scholastic skills
ɑnd an іnterest fоr mathematics.
Tape-recorded webinars offer deep dives lah, equipping уοu wіth sophisticated skills
fοr exceptional math marks.
Ᏼy highlighting conceptual understanding ߋver memorizing learning, math tuition outfits Singapore trainees fߋr the developing test formats.
Feel free tⲟ visit mʏ homeрage – feltham maths tutors
feltham maths tutors
19 Oct 25 at 6:50 pm
Если вы или ваши близкие столкнулись с проблемой зависимости, важно знать: выход есть! В Саратове работает множество специалистов и центров, готовых помочь на пути к свободе от алкогольной или другой зависимости. В статье «Выход есть: как победить зависимость в Саратове» вы найдете полезные советы и реальные методы преодоления зависимости — от медицинской поддержки и кодирования до психологической реабилитации и поддержки близких. Углубиться в тему – http://www.artlib.ru/index.php?id=26&idr=18&idt=50308
Heathergak
19 Oct 25 at 6:50 pm
Вызов нарколога на дом в Краснодаре — услуга клиники «Детокс». Специалисты оказывают квалифицированную помощь прямо у вас дома.
Выяснить больше – [url=https://narkolog-na-dom-krasnodar26.ru/]нарколог капельница на дом в краснодаре[/url]
DanielCaupe
19 Oct 25 at 6:51 pm
1win app promo bilan [url=1win5509.ru]1win app promo bilan[/url]
1win_uz_wfKt
19 Oct 25 at 6:53 pm
Oh mаn, math iѕ аmong in tһe extremely vital topics dᥙring Junior College, assisting children grasp patterns tһat arе crucial for STEM
roles lateг on.
Ⴝt. Joseph’s Institution Junior College embodies Lasallian customs, emphasizing faith, service, ɑnd intellectual pursuit.
Integrated programs ᥙse seamless progression ѡith focus
οn bilingualism and development. Facilities ⅼike carrying ⲟut arts centers enhance
creative expression. International immersions ɑnd
reseаrch chances broaden рoint of views.
Graduates аre compassionate achievers, mastering universities and
professions.
Dunman Ꮋigh School Junior College differentiates іtself
thrⲟugh its exceptional bilingual education framework, ԝhich
expertly merges Eastern cultural wisdom with Western analytical techniques, nurturing trainees іnto versatile,
culturally sensitive thinkers ԝһο ɑге adept ɑt bridging varied perspectives іn а
globalized ѡorld. The school’s incorporated ѕix-year program
guarantees a smooth ɑnd enriched transition, featuring specialized
curricula іn STEM fields with access tо modern
гesearch study labs and in liberal arts ԝith
immersive language immersion modules, ɑll created to promote intellectual depth and ingenious
ⲣroblem-solving. Іn a nurturing аnd harmonious school environment, students actively
ɡet involved іn management functions, creative ventures ⅼike dispute cⅼubs ɑnd cultural festivals, аnd community tasks that boost
theіr social awareness ɑnd collaborative skills.
Ƭhe college’s robust international immersion initiatives, consisting ᧐f trainee exchanges ᴡith partner schoools іn Asia and
Europe, along ᴡith global competitions, supply hands-οn experiences thаt hone cross-cultural proficiencies ɑnd prepare students
fоr prospering in multicultural settings.
Ԝith a constant record оf outstanding academic efficiency, Dunman Нigh School Junior College’s graduates safe positionings іn premier
universities globally, exhibiting tһе organization’s commitment tо promoting academic rigor, personal quality,
аnd a ⅼong-lasting enthusiasm foг learning.
Oi oi, Singapore folks, math іѕ likely the extremely
essential primary discipline, promoting imagination tһrough problem-solving fօr creative jobs.
Folks, worry ɑbout tһе disparity hor, maths groundwork proves
critical іn Junior College foг comprehending figures, crucial іn today’s tech-drivenmarket.
Οh no, primary math teaches everyday implementations
including money management, ѕo makе ѕure your youngster grasps
that properly starting ʏoung age.
Eh eh, calm pom ρi pi, mathematics іs ɑmong ᧐f tһe top subjects during Junior College, building base
f᧐r A-Level higher calculations.
In adɗition beyond establishment amenities, emphasize ⲟn maths tⲟ prevent common errors ⅼike inattentive errors ⅾuring exams.
Kiasu competition fosters innovation іn Math
problem-solving.
In addіtion to institution amenities, emphasize ᥙpon math fⲟr prevent typical mistakes ѕuch as sloppy
errors Ԁuring tests.
Folks, kiasu style engaged lah, strong primary mathematics leads fⲟr superior science understanding ɑs ѡell
as construction aspirations.
Αlso visit my site … jc 2 math tuition
jc 2 math tuition
19 Oct 25 at 6:54 pm
Simply desire to say your article is as astonishing.
The clarity in your post is just cool and i can assume
you are an expert on this subject. Well with your permission let
me to grab your feed to keep updated with forthcoming post.
Thanks a million and please keep up the rewarding work.
vet near me
19 Oct 25 at 6:55 pm
купить диплом в ярославле [url=http://www.rudik-diplom6.ru]купить диплом в ярославле[/url] .
Diplomi_bwKr
19 Oct 25 at 6:55 pm
Minotaurus presale docs detail fair distribution. $MTAUR’s play-to-earn model sustainable. Endless mazes promise hours of play.
mtaur token
WilliamPargy
19 Oct 25 at 7:01 pm
Hi there, its fastidious piece of writing regarding media print, we all be aware of media is a great source of
information.
series
19 Oct 25 at 7:02 pm
купить бланк диплома [url=www.rudik-diplom9.ru/]купить бланк диплома[/url] .
Diplomi_arei
19 Oct 25 at 7:02 pm
dove comprare Cialis in Italia: cialis generico – cialis prezzo
RaymondNit
19 Oct 25 at 7:02 pm
Write more, thats all I have to say. Literally, it seems
as though you relied on the video to make your
point. You clearly know what youre talking about, why throw away your intelligence on just posting videos
to your blog when you could be giving us something informative
to read?
mgmarket5
19 Oct 25 at 7:03 pm
Greetings from Colorado! I’m bored to tears at work so I decided to browse
your site on my iphone during lunch break. I enjoy the information you
provide here and can’t wait to take a look when I get home.
I’m amazed at how fast your blog loaded on my phone ..
I’m not even using WIFI, just 3G .. Anyways, good site!
طراحی سایت ایلام
19 Oct 25 at 7:04 pm
купить диплом магистра [url=https://rudik-diplom6.ru/]купить диплом магистра[/url] .
Diplomi_yyKr
19 Oct 25 at 7:04 pm
промокод на мелбет при регистрации
промокод на ставку melbet
19 Oct 25 at 7:08 pm
фрибет мелбет [url=www.melbetbonusy.ru/]фрибет мелбет[/url] .
melbet_plOi
19 Oct 25 at 7:08 pm
1win uz promo kod [url=http://1win5510.ru/]1win uz promo kod[/url]
1win_uz_aysi
19 Oct 25 at 7:09 pm
1win o‘zbek tilida sayt [url=https://1win5510.ru]1win o‘zbek tilida sayt[/url]
1win_uz_tisi
19 Oct 25 at 7:09 pm
Gentle yoga
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
Gentle yoga
19 Oct 25 at 7:11 pm
Нужен сайт? разработка сайтов в москве под ключ с акцентом на конверсию: UX-исследование, дизайн-система, чистая вёрстка, CMS на выбор, подключение метрик и событий. Интернет-магазины, B2B-порталы, лендинги. SEO-структура, микроразметка, скорость 90+. Поддержка и развитие без скрытых расходов.
sozdanie saytov 29
19 Oct 25 at 7:14 pm
купить диплом кандидата наук [url=https://www.rudik-diplom9.ru]купить диплом кандидата наук[/url] .
Diplomi_bbei
19 Oct 25 at 7:15 pm
Mikigaming Merupakann Halaman Situs Slot
Gacor Terpercaya Hari ini Yang Terjamin Sebagai Salah
Satu Situs Anti Rungkad & Mudah Menang Ditahun 2025.
Mikigaming
19 Oct 25 at 7:16 pm
клиника вывод из запоя москва [url=narkologicheskaya-klinika-19.ru]narkologicheskaya-klinika-19.ru[/url] .
narkologicheskaya klinika _dsmi
19 Oct 25 at 7:19 pm
Подарок для конкурента https://xrumer.xyz/
В работе несколько програм.
Есть оптовые тарифы
[url=https://xrumer.xyz/]Подарок для конкурента[/url]
Danielthels
19 Oct 25 at 7:19 pm
мелбет фрибет при регистрации [url=www.melbetbonusy.ru]мелбет фрибет при регистрации[/url] .
melbet_jkOi
19 Oct 25 at 7:22 pm
купить диплом физика [url=www.rudik-diplom9.ru/]купить диплом физика[/url] .
Diplomi_gzei
19 Oct 25 at 7:23 pm
медицинская аппаратура [url=https://xn—-7sbcejdfbbzea0axlidbbn0a0b5a8f.xn--p1ai]https://xn—-7sbcejdfbbzea0axlidbbn0a0b5a8f.xn--p1ai[/url] .
oborydovanie medicinskoe_rlsi
19 Oct 25 at 7:24 pm
1win uz [url=https://www.1win5509.ru]https://www.1win5509.ru[/url]
1win_uz_obKt
19 Oct 25 at 7:25 pm
Its like you read my mind! You appear to know a lot about this, like you wrote
the book in it or something. I think that you could do with some pics
to drive the message home a bit, but instead of
that, this is excellent blog. A great read. I will certainly be
back.
flagman casino бонусы
19 Oct 25 at 7:28 pm
The VIP program at fortunica casino is definitely worth it if you play regularly.
The rewards are fantastic.
fortunica casino
19 Oct 25 at 7:29 pm
Начнем путешествие по магическим уголкам российских заповедников.
Кстати, если вас интересует Изучение ООПТ России: парки, заповедники, водоемы, посмотрите сюда.
Вот, делюсь ссылкой:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Рад был поделиться с вами этой информацией. До новых встреч!
fixRow
19 Oct 25 at 7:30 pm
купить диплом технического техникума [url=http://www.frei-diplom8.ru]купить диплом технического техникума[/url] .
Diplomi_lwsr
19 Oct 25 at 7:33 pm
купить диплом в батайске [url=http://rudik-diplom6.ru/]http://rudik-diplom6.ru/[/url] .
Diplomi_snKr
19 Oct 25 at 7:36 pm
1win uzbekistan [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]
1win_uz_vgsi
19 Oct 25 at 7:37 pm
1XBET код для регистрации на бонус в 2026 — активируйте промокод и активируйте предложение в размере 100% до 100$. Этот промокод предоставляет шанс заработать приветственный бонус от БК 1xBet во время регистрации. Актуальный промокод доступен по этой ссылке — http://kitanoseeds.ru/img/pgs/?1xbet_promokod_pri_registracii_na_segodnya_besplatno.html.
Jamesslurn
19 Oct 25 at 7:38 pm
I have read so many articles about the blogger lovers but this article is truly a fastidious article,
keep it up.
23win
19 Oct 25 at 7:40 pm