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!
Uk Meds Guide [url=https://ukmedsguide.com/#]non-prescription medicines UK[/url] non-prescription medicines UK
Hermanengam
2 Nov 25 at 1:57 pm
купить диплом с проводкой одно [url=www.frei-diplom4.ru]купить диплом с проводкой одно[/url] .
Diplomi_juOl
2 Nov 25 at 1:59 pm
рейтинг сео агентств [url=www.reiting-seo-kompaniy.ru]рейтинг сео агентств[/url] .
reiting seo kompanii_xron
2 Nov 25 at 2:00 pm
диплом медсестры с аккредитацией купить [url=https://www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_iykt
2 Nov 25 at 2:00 pm
купить диплом в ельце [url=http://www.rudik-diplom8.ru]http://www.rudik-diplom8.ru[/url] .
Diplomi_eyMt
2 Nov 25 at 2:00 pm
https://hallwayis.edu.sg/in-reprehenderit-in-voluptate-velit-esse-cillum-dolore-eu-fugiat-nulla-pariatur/#comment-78948
Bruceruh
2 Nov 25 at 2:01 pm
купить диплом в ельце [url=https://rudik-diplom13.ru/]https://rudik-diplom13.ru/[/url] .
Diplomi_seon
2 Nov 25 at 2:03 pm
рейтинг seo студий [url=https://reiting-seo-kompaniy.ru/]рейтинг seo студий[/url] .
reiting seo kompanii_mzon
2 Nov 25 at 2:03 pm
By incorporating real-ᴡorld applications іn lessons, OMT reveals Singapore trainees еxactly һow math
powers daily innovations, sparking passion аnd drive fοr examination excellence.
Open yⲟur kid’s full potential in mathematics ԝith OMT Math Tuition’ѕ expert-led classes, customized tߋ Singapore’s MOE syllabus
fߋr primary school, secondary, аnd JC trainees.
In a system where math education hаs actualⅼy evolved to promote innovation ɑnd international competitiveness, enrolling іn math tuition maқes
sure trainees гemain ahead by deepening tһeir understanding and application οf
essential principles.
Ꮃith PSLE mathematics developing t᧐ incⅼude more interdisciplinary
elements, tuition ҝeeps students updated on incorporated questions mixing math ᴡith science contexts.
Secondary math tuition overcomes tһe limitations of largе classroom dimensions, ɡiving concentrated attention tһat enhances understanding fօr O Level prep ѡork.
In ɑ competitive Singaporean education аnd learning system, junior college math tuition оffers students the side to attain hіgh qualities
neеded for university admissions.
OMT’ѕ personalized math curriculum stands аpaгt by connecting MOE content wіtһ innovative theoretical links, aiding pupils connect ideas
ɑcross vaгious math subjects.
OMT’s online community οffers support leh, ᴡherе you can аsk inquiries ɑnd improve your learning for muϲһ better grades.
Math tuition inspires ѕelf-confidence via success іn smalⅼ turning points,
pushing Singapore students towards ɡeneral exam victories.
Мy blog post tuition center male teachers maths serangoon
tuition center male teachers maths serangoon
2 Nov 25 at 2:04 pm
купить диплом медсестры [url=https://www.frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_mfkt
2 Nov 25 at 2:04 pm
купить диплом занесением реестр [url=https://www.frei-diplom4.ru]купить диплом занесением реестр[/url] .
Diplomi_dsOl
2 Nov 25 at 2:04 pm
лучшие агентства seo продвижения [url=http://reiting-seo-kompaniy.ru]http://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_vson
2 Nov 25 at 2:05 pm
купить диплом в биробиджане [url=https://rudik-diplom8.ru/]купить диплом в биробиджане[/url] .
Diplomi_ngMt
2 Nov 25 at 2:06 pm
online pharmacy
Edmundexpon
2 Nov 25 at 2:07 pm
When I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive four emails with
the same comment. Is there a means you can remove
me from that service? Cheers!
офиопогон
2 Nov 25 at 2:07 pm
где купить диплом с занесением реестр [url=www.frei-diplom4.ru]где купить диплом с занесением реестр[/url] .
Diplomi_luOl
2 Nov 25 at 2:08 pm
Здравствуйте!
Владельцев коммерческого транспорта в России интересуют двигатели Cummins и китайская спецтехника. Cummins известны надежностью, а китайская техника — доступной ценой. Получение качественной информации по этим темам может быть сложной задачей. Блог https://specteh.blog/ предлагает систематизированные данные, собранные специалистами. Здесь можно найти советы по обслуживанию и ремонту, экономя время на поиск информации по разрозненным источникам. Ресурс будет полезен как механикам, так и владельцам автопарков.
Проблемы двигателя Cummins типичные, Cummins турбина проверка, Номер двигателя Cummins ISF 3.8 Валдай инструкция
Cummins датчик температуры, [url=https://specteh.blog/garantiya-na-kitayskuyu-spetstehniku-chto-pokryvaet-i-kak-ispolzovat/]Гарантия на китайскую спецтехнику[/url], Shacman дилеры в России обзор
Удачи и комфортной езды!
Cumminsmt
2 Nov 25 at 2:08 pm
купить диплом оценщика [url=www.rudik-diplom7.ru/]купить диплом оценщика[/url] .
Diplomi_mvPl
2 Nov 25 at 2:09 pm
人形 エロin his nursery.He told his sister,
セックス ドール
2 Nov 25 at 2:09 pm
каталог seo агентств [url=https://reiting-seo-kompaniy.ru/]https://reiting-seo-kompaniy.ru/[/url] .
reiting seo kompanii_tcon
2 Nov 25 at 2:12 pm
купить дипломы о высшем цены [url=http://rudik-diplom6.ru/]купить дипломы о высшем цены[/url] .
Diplomi_cuKr
2 Nov 25 at 2:12 pm
dubna.ru [url=http://dubna.ru/article/2025/09/kak-vybrat-shkolu-angliyskogo-yazyka-dlya-detey-i-podrostkov]http://dubna.ru/article/2025/09/kak-vybrat-shkolu-angliyskogo-yazyka-dlya-detey-i-podrostkov[/url] .
shkoli angliiskogo yazika_tisn
2 Nov 25 at 2:13 pm
vkirove.ru [url=https://vkirove.ru/news/2025/09/28/kak_vybrat_shkolu_angliyskogo_yazyka_prakticheskie_sovety.html]https://vkirove.ru/news/2025/09/28/kak_vybrat_shkolu_angliyskogo_yazyka_prakticheskie_sovety.html[/url] .
shkoli angliiskogo yazika_papi
2 Nov 25 at 2:15 pm
купить диплом в кирове [url=www.rudik-diplom14.ru/]купить диплом в кирове[/url] .
Diplomi_uvea
2 Nov 25 at 2:17 pm
купить аттестаты за 9 [url=https://rudik-diplom13.ru]купить аттестаты за 9[/url] .
Diplomi_dqon
2 Nov 25 at 2:18 pm
где купить дипломы медсестры [url=https://www.frei-diplom13.ru]где купить дипломы медсестры[/url] .
Diplomi_uikt
2 Nov 25 at 2:18 pm
каталог seo агентств [url=https://reiting-seo-kompaniy.ru]https://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_epon
2 Nov 25 at 2:18 pm
Хотите играть, как ваши кумиры? Наши учителя покажут, с чего начать и как добиться успеха. https://shkola-vocala.ru/shkola-igry-na-gitare.php
https://shkola-vocala.ru/shkola-igry-na-gitare.php
2 Nov 25 at 2:18 pm
компания seo [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_cnKt
2 Nov 25 at 2:20 pm
Link flm
hskahrkii
2 Nov 25 at 2:21 pm
сео фирмы [url=https://www.reiting-seo-kompaniy.ru]сео фирмы[/url] .
reiting seo kompanii_poon
2 Nov 25 at 2:22 pm
https://ukmedsguide.shop/# safe place to order meds UK
Haroldovaph
2 Nov 25 at 2:22 pm
купить диплом с занесением в реестр [url=https://www.frei-diplom4.ru]купить диплом с занесением в реестр[/url] .
Diplomi_bjOl
2 Nov 25 at 2:22 pm
seo продвижение агентство услуга [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo продвижение агентство услуга[/url] .
agentstvo poiskovogo prodvijeniya_fjKt
2 Nov 25 at 2:23 pm
trusted online pharmacy UK: affordable medications UK – cheap medicines online UK
HaroldSHems
2 Nov 25 at 2:26 pm
1xbet resmi [url=https://1xbet-giris-4.com/]https://1xbet-giris-4.com/[/url] .
1xbet giris_wiSa
2 Nov 25 at 2:26 pm
seo agencies ranking [url=www.reiting-seo-kompaniy.ru/]seo agencies ranking[/url] .
reiting seo kompanii_qdon
2 Nov 25 at 2:27 pm
Fantastic items from you, man. I have take into account your stuff prior to and you’re just extremely wonderful.
I really like what you’ve received here, really like what you are stating and
the best way through which you say it. You are making it enjoyable and you still take care of to stay
it smart. I can not wait to learn much more from you.
This is really a tremendous site.
Support vegan movement
2 Nov 25 at 2:28 pm
In adⅾition frⲟm institution resources, emphasize ѡith maths
іn ⲟrder to prevent common mistakes ⅼike sloppy errors аt exams.
Parents, fearful ⲟf losing approach activated lah,
robust primary maths guides fߋr improved STEM understanding and
engineering goals.
Ѕt. Andrew’s Junior College promotes Anglican values ɑnd
holistic growth, building principled individuals
ѡith strong character.Modern features support
quality іn academics, sports, and arts. Neighborhood
service аnd management programs impart empathy ɑnd responsibility.
Diverse сo-curricular activities promote team effort ɑnd self-discovery.
Alumni emerge аs ethical leaders, contributing meaningfully tߋ society.
Temasek Junior College motivates ɑ generation of
trendsetters Ƅy fusing time-honored customs wіth cutting-edge innovation,
offering rigorous academic programs infused ѡith ethical
worths thаt assist trainees tοwards meaningful and impactful futures.
Advanced proving ground, language labs, аnd optional courses іn global languages аnd performing arts offer platforms fօr deep intellectual
engagement, vital analysis, ɑnd creative exploration ᥙnder the mentorship օf prominent teachers.
Тһе lively сo-curricular landscape, including competitive sports, creative societies, аnd entrepreneurship сlubs, cultivates
teamwork, management, ɑnd a spirit of development tһat complements classroom knowing.
International partnerships, ѕuch as joint reseаrch
jobs ԝith abroad instiitutions ɑnd cultural exchange programs, improve
students’ global proficiency, cultural sensitivity, ɑnd networking capabilities.
Alumni from Temasek Junior College grow іn elite college institutions аnd diverse professional fields, personifying tһe school’s dedication to
quality, service-oriented management, аnd tһe pursuit ᧐f personal аnd social improvement.
Apɑrt beyond school amenities, concentrate ⲟn math for аvoid typical errors including
inattentive errors ɑt exams.
Folks, fearful οf losing approach ᧐n lah, solid primary mathematics гesults іn bеtter science comprehension аs well as construction dreams.
Օh mаn, no matter thоugh school proves һigh-end,
mathematics serves ɑs the critical subject fⲟr developing confidence in figures.
Hey hey, steady pom ρi pi, math remains among
of the hіghest disciplines in Junior College, establishing foundation fоr A-Level advanced
math.
Beѕides to institution amenities, emphasize սpon mathematics tߋ stop common errors lіke inattentive mistakes in tests.
Kiasu mindset іn JC pushes ʏou to conquer Math,
unlocking doors tо data science careers.
Ɗ᧐ not mess around lah, link а good Junior College alongside math superiority fߋr guarantee һigh A Levels marks and
smooth transitions.
Ꭺlso visit mү һomepage sec school
sec school
2 Nov 25 at 2:30 pm
купить диплом в волгодонске [url=www.rudik-diplom14.ru/]купить диплом в волгодонске[/url] .
Diplomi_ggea
2 Nov 25 at 2:30 pm
купить диплом инженера электрика [url=http://www.rudik-diplom6.ru]купить диплом инженера электрика[/url] .
Diplomi_aoKr
2 Nov 25 at 2:31 pm
https://dubna.ru/article/2025/09/kak-vybrat-shkolu-angliyskogo-yazyka-dlya-detey-i-podrostkov [url=https://dubna.ru/article/2025/09/kak-vybrat-shkolu-angliyskogo-yazyka-dlya-detey-i-podrostkov/]https://dubna.ru/article/2025/09/kak-vybrat-shkolu-angliyskogo-yazyka-dlya-detey-i-podrostkov/[/url] .
shkoli angliiskogo yazika_nksn
2 Nov 25 at 2:31 pm
компания продвижение сайтов [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/[/url] .
agentstvo poiskovogo prodvijeniya_yvKt
2 Nov 25 at 2:31 pm
английская языковая школа [url=http://www.vkirove.ru/news/2025/09/28/kak_vybrat_shkolu_angliyskogo_yazyka_prakticheskie_sovety.html]http://www.vkirove.ru/news/2025/09/28/kak_vybrat_shkolu_angliyskogo_yazyka_prakticheskie_sovety.html[/url] .
shkoli angliiskogo yazika_wcpi
2 Nov 25 at 2:32 pm
https://textpesni2.ru/
https://textpesni2.ru/
2 Nov 25 at 2:32 pm
сео фирмы [url=reiting-seo-kompaniy.ru]сео фирмы[/url] .
reiting seo kompanii_qoon
2 Nov 25 at 2:33 pm
1xbet resmi giri? [url=http://www.1xbet-giris-2.com]http://www.1xbet-giris-2.com[/url] .
1xbet giris_xcPt
2 Nov 25 at 2:34 pm
купить диплом с проведением в [url=www.frei-diplom4.ru]купить диплом с проведением в[/url] .
Diplomi_uwOl
2 Nov 25 at 2:34 pm
купить диплом медсестры [url=frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_cikt
2 Nov 25 at 2:35 pm
сео продвижение сайтов топ [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_rvKt
2 Nov 25 at 2:37 pm