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!
023rongzi.com – Bookmarked this immediately, planning to revisit for updates and inspiration.
Long Moncrieff
29 Oct 25 at 7:39 pm
Удобно ли получать медицинскую помощь дома? В Екатеринбурге служба Детокс готова выслать нарколога к вам или вашим близким просто по звонку — по телефону горячей линии, доступен вызов 24/7. Процедуры, включая капельницы, снятие синдрома абстиненции и другие меры для безопасного вывода из запоя, проводятся с использованием сертифицированных лекарств и под контролем специалиста.
Узнать больше – [url=https://narkolog-na-dom-ekaterinburg12.ru/]запой нарколог на дом в екатеринбурге[/url]
JeffreyKen
29 Oct 25 at 7:40 pm
В Ростове-на-Дону клиника «ЧСП№1» предлагает квалифицированный вывод из запоя в стационаре и на дому.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-rostov15.ru/]скорая вывод из запоя[/url]
Camerondup
29 Oct 25 at 7:41 pm
Отличная подборка инструментов для генерации изображений помогла определиться с выбором быстро. Протестировал три варианта из обзора, два использую регулярно. Качество везде профессиональное: https://vc.ru/top_rating/2301994-luchshie-besplatnye-nejroseti-dlya-generatsii-izobrazheniy
MichaelPrion
29 Oct 25 at 7:42 pm
Hi there, its pleasant piece of writing on the topic of
media print, we all be aware of media is a fantastic source of facts.
casino utan svensk licens
29 Oct 25 at 7:42 pm
Hi there, I enjoy reading all of your post.
I wanted to write a little comment to support you.
Also visit my site – растаможка электроники из китая
растаможка электроники из китая
29 Oct 25 at 7:42 pm
купить проведенный диплом весь [url=https://frei-diplom4.ru]купить проведенный диплом весь[/url] .
Diplomi_rmOl
29 Oct 25 at 7:42 pm
Apart to establishment resources, focus wіth math to stoр frequent errors ѕuch ɑs sloppy errors ԁuring exams.
Parents, fearful оf losing approach οn lah,
strong primary maths leads іn superior STEM understanding aas ᴡell as construction goals.
Yishun Innova Junior College combines strengths fοr digital literacy ɑnd
leadership excellence. Updated centers promote innovation аnd lifelong learning.
Varied programs іn media and languyages promote imagination аnd citizenship.
Neighborhood engagements construct compassion аnd skills.
Students emerge as confident, tech-savvy leaders ready fοr tһe digital age.
River Valley Ηigh School Junior College flawlessly
іncludes multilingual education ԝith a strong dedication tο ecological stewardship,
supporting eco-conscious leaders ѡһo have sharp international point of views and a dedication to sustainable practices
іn an progressively interconnected ԝorld. The school’s advanced
laboratories, green innovation centers, ɑnd environmentally friendly campus styles
support pioneering learning іn sciences, humanities, and environmental research studies,
encouraging students t᧐ participate in hands-on experiments ɑnd ingenious solutions tօ real-world
obstacles. Cultural immersion programs, ѕuch as language exchanges and heritage journeys, integrated ԝith neighborhood service
tasks focused օn conservation, improve trainees’ empathy,
cultural intelligence, ɑnd practical skills fߋr favorable social impact.
Ԝithin a unified аnd supportive community, participation іn sports teams,arts societies,
ɑnd leadership workshops promotes physical ᴡell-being, team effort, and resilience, producing healthy people аll sеt
for future undertakings. Graduates fгom River Valley High School Junior College ɑre ideally positioned f᧐r success
iin leading universities ɑnd careers, embodying
tһe school’s core values ߋf perseverance, cultural acumen, ɑnd а proactive approach
tо global sustainability.
Aiyah, primary math educates practical applications ⅼike budgeting, therefore ensure your child gets іt properly from young age.
Hey hey, steady pom ρi ρi, math remains among in the top
subjects іn Junior College, building groundwork tо A-Level advanced
math.
Eh eh, composed pom ρi pi, maths гemains among in thе leading subjects іn Junior College, establishing foundation іn A-Level higһer calculations.
Besidеs beүond establishment resources, focus ᴡith mathematics foг avoiⅾ common pitfalls including sloppy errors іn assessments.
Hey hey, Singapore folks, math proves рrobably the most importаnt
primary subject, promoting creativity іn pгoblem-solving fоr creative jobs.
Don’t play play lah, pair а excellent Junior
College alongside mathematics superiority іn ordeг to guarantee elevated Ꭺ Levels scores ɑѕ ѡell as effortless
transitions.
Math аt A-levels builds endurance for marathon study sessions.
Alas, lacking strong math аt Junior College, еven prestigious establishment youngsters could falter іn next-level
equations, tһerefore build tһat now leh.
My website; andrew tan math tuition
andrew tan math tuition
29 Oct 25 at 7:42 pm
диплом об окончании техникума купить в [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_cmea
29 Oct 25 at 7:43 pm
купить диплом товароведа [url=http://rudik-diplom6.ru]купить диплом товароведа[/url] .
Diplomi_zzKr
29 Oct 25 at 7:43 pm
купить диплом о высшем образовании с занесением в реестр [url=frei-diplom6.ru]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_szOl
29 Oct 25 at 7:43 pm
купить диплом в новочебоксарске [url=www.rudik-diplom5.ru/]www.rudik-diplom5.ru/[/url] .
Diplomi_epma
29 Oct 25 at 7:43 pm
купить диплом в самаре [url=http://www.rudik-diplom2.ru]купить диплом в самаре[/url] .
Diplomi_vhpi
29 Oct 25 at 7:43 pm
318hw.com – Navigation felt smooth, found everything quickly without any confusing steps.
Margherita Beaupre
29 Oct 25 at 7:44 pm
купить диплом инженера строителя [url=http://www.rudik-diplom8.ru]купить диплом инженера строителя[/url] .
Diplomi_jzMt
29 Oct 25 at 7:44 pm
диплом купить с занесением в реестр отзывы [url=https://frei-diplom5.ru]https://frei-diplom5.ru[/url] .
Diplomi_kbPa
29 Oct 25 at 7:44 pm
легально купить диплом о [url=http://frei-diplom1.ru]легально купить диплом о[/url] .
Diplomi_wqOi
29 Oct 25 at 7:44 pm
обучение продвижению сайтов [url=https://kursy-seo-11.ru]обучение продвижению сайтов[/url] .
kyrsi seo_dyEl
29 Oct 25 at 7:44 pm
Hello everyone, it’s my first go to see at this web page,
and paragraph is truly fruitful for me, keep up posting these articles.
buôn bán nội tạng
29 Oct 25 at 7:46 pm
диплом политехнического колледжа купить [url=http://frei-diplom8.ru]http://frei-diplom8.ru[/url] .
Diplomi_qmsr
29 Oct 25 at 7:46 pm
контекстная реклама статьи [url=statyi-o-marketinge7.ru]контекстная реклама статьи[/url] .
stati o marketinge _hjkl
29 Oct 25 at 7:46 pm
где можно купить диплом медсестры [url=http://www.frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_lxkt
29 Oct 25 at 7:47 pm
диплом медсестры с занесением в реестр купить [url=www.frei-diplom6.ru/]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_joOl
29 Oct 25 at 7:47 pm
купить диплом в рыбинске [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .
Diplomi_syei
29 Oct 25 at 7:48 pm
как купить диплом с проведением [url=https://frei-diplom4.ru/]как купить диплом с проведением[/url] .
Diplomi_wsOl
29 Oct 25 at 7:48 pm
I have been exploring for a bit for any high quality articles or weblog posts on this kind of space .
Exploring in Yahoo I finally stumbled upon this
web site. Reading this info So i’m satisfied to show that I’ve an incredibly just right uncanny feeling I found out exactly what I needed.
I so much undoubtedly will make sure to do not put out of your mind this
site and provides it a look regularly.
سمساری چیست
29 Oct 25 at 7:48 pm
где купить диплом [url=http://rudik-diplom8.ru]где купить диплом[/url] .
Diplomi_htMt
29 Oct 25 at 7:49 pm
купить диплом в омске [url=www.rudik-diplom5.ru]купить диплом в омске[/url] .
Diplomi_cgma
29 Oct 25 at 7:49 pm
Инхимтек — первый в России производитель полиэтиленовых восков: неокисленные (в т.ч. суспензионные и рафинированные), окисленные ПНД/ПВД и синтетические церезины. Собственная лаборатория, внедренные технологии микронизации и эмульсий, масштабирование мощностей (новые колонны окисления и линии деструкции) — это стабильные спецификации и поставки по всей стране, включая резервирование на складе и выпуск по ТЗ заказчика. Для выбора марки и получения проб перейти на https://xn--e1afajie1bv.xn--p1ai/ — специалисты помогут подобрать совместимость под конкретный процесс.
nogojvaw
29 Oct 25 at 7:49 pm
купить диплом с занесением в реестр в украине [url=https://frei-diplom1.ru/]https://frei-diplom1.ru/[/url] .
Diplomi_hgOi
29 Oct 25 at 7:50 pm
купить диплом сантехника [url=https://www.rudik-diplom11.ru]купить диплом сантехника[/url] .
Diplomi_zcMi
29 Oct 25 at 7:51 pm
диплом торгового техникума купить [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_mqea
29 Oct 25 at 7:51 pm
купить диплом в южно-сахалинске [url=http://rudik-diplom4.ru]купить диплом в южно-сахалинске[/url] .
Diplomi_niOr
29 Oct 25 at 7:51 pm
купить проведенный диплом весь [url=https://frei-diplom5.ru/]купить проведенный диплом весь[/url] .
Diplomi_swPa
29 Oct 25 at 7:52 pm
OMT’s concentrate on fundamental abilities develops unshakeable ѕelf-confidence, enabling Singapore trainees tо falⅼ in love wіth math’s sophistication ɑnd гeally feel motivated f᧐r exams.
Founded in 2013 by Mr. Justin Tan, OMT Math
Tuition һas helped many students ace exams ⅼike PSLE, Ο-Levels, and A-Levels witһ tested
analytical techniques.
Αs math forms the bedrock ᧐f abstract tһ᧐ught аnd crucial analytical іn Singapore’s education ѕystem,
expert math tuition supplies tһe individualized guidance required tο
turn difficulties into triumphs.
Math tuition addresses specific discovering rates, enabling primary trainees tⲟ
deepen understanding оf PSLE topics ⅼike area, boundary, аnd
volume.
Prοvided thе һigh risks of O Levels for secondary school development іn Singapore,
math tuition maximizes chances fоr leading grades and desired positionings.
Ꮤith A Levels affecting profession paths in STEM fields, math tuition reinforces fundamental abilities fоr
future university гesearch studies.
OMT’ѕ exclusive mathematics program matches
MOE criteria Ƅy highlighting theoretical proficiency оver memorizing
knowing, brіng аbout mսch deeper lasting retention.
Aⅼl natural strategy in on-lіne tuition one, supporting not simply abilities Ьut enthusiasm for math ɑnd supreme grade success.
Singapore’ѕ concentrate on holistic education is matched ƅy math tuition tһat builds abstract tһought
for long-lasting exam advantages.
Heгe is my website math questions fօr sec 1 (sefkorea.com)
sefkorea.com
29 Oct 25 at 7:52 pm
где купить дипломы медсестры [url=frei-diplom13.ru]где купить дипломы медсестры[/url] .
Diplomi_tmkt
29 Oct 25 at 7:54 pm
https://gatjuice.com/
מיץ גת מחיר
29 Oct 25 at 7:54 pm
купить диплом электромонтера [url=http://rudik-diplom3.ru]купить диплом электромонтера[/url] .
Diplomi_vfei
29 Oct 25 at 7:54 pm
купить дипломы о высшем с занесением [url=http://rudik-diplom10.ru/]купить дипломы о высшем с занесением[/url] .
Diplomi_akSa
29 Oct 25 at 7:55 pm
Does your site have a contact page? I’m having a tough time locating
it but, I’d like to send you an e-mail. I’ve got some ideas
for your blog you might be interested in hearing.
Either way, great website and I look forward to seeing it improve
over time.
chicken road slot
29 Oct 25 at 7:55 pm
купить диплом с занесением в реестр цена [url=frei-diplom4.ru]купить диплом с занесением в реестр цена[/url] .
Diplomi_hzOl
29 Oct 25 at 7:56 pm
When we breathe in, our lungs fill with oxygen, which is distributed to our red blood cells for transportation all through our our bodies.
Our bodies need quite a lot of oxygen to perform, and wholesome people have not less than 95% oxygen saturation all the time.
Conditions like asthma or COVID-19 make it more durable for bodies to absorb oxygen from the lungs.
This results in oxygen saturation percentages that drop to 90% or beneath, an indication that medical attention is needed.
In a clinic, docs monitor oxygen saturation using pulse oximeters — these clips you put over
your fingertip or ear. But monitoring oxygen saturation at dwelling a number of instances a day could assist patients keep watch over COVID
signs, for example. In a proof-of-precept research, University of Washington and University
of California San Diego researchers have proven that smartphones are
able to detecting blood oxygen saturation levels down to 70%.
That is the lowest value that pulse oximeters should be capable of measure, as advisable
by the U.S.
monitor oxygen saturation
29 Oct 25 at 7:56 pm
поисковое продвижение сайта в интернете москва [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]поисковое продвижение сайта в интернете москва[/url] .
optimizaciya i seo prodvijenie saitov moskva_mhel
29 Oct 25 at 7:56 pm
купить диплом в нефтекамске [url=https://www.rudik-diplom5.ru]купить диплом в нефтекамске[/url] .
Diplomi_ntma
29 Oct 25 at 7:57 pm
куплю диплом медсестры в москве [url=www.frei-diplom13.ru/]куплю диплом медсестры в москве[/url] .
Diplomi_fukt
29 Oct 25 at 7:57 pm
курсы seo [url=kursy-seo-11.ru]курсы seo[/url] .
kyrsi seo_hkEl
29 Oct 25 at 7:58 pm
купить диплом строительного колледжа [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .
Diplomi_bnsr
29 Oct 25 at 7:58 pm
Excelente resumen sobre las tragamonedas favoritas en Pin Up Casino México.
Sorprende lo bien que han evolucionado las tragamonedas más famosas dentro del catálogo de Pin-Up Casino.
Se nota que el artículo está pensado para quienes
realmente disfrutan de los juegos de casino online.
No te pierdas la oportunidad de leer el artículo y descubrir
por qué estos slots son los favoritos entre los jugadores mexicanos.
Muy completo, ideal para quienes quieren probar
tanto slots clásicos como opciones innovadoras.
Puedes leer el artículo completo aquí
y descubrir todos los detalles sobre los juegos
más jugados en Pin Up México.
information
29 Oct 25 at 7:59 pm
купить диплом в камышине [url=https://www.rudik-diplom3.ru]купить диплом в камышине[/url] .
Diplomi_zfei
29 Oct 25 at 7:59 pm
купить диплом швеи [url=https://rudik-diplom11.ru]купить диплом швеи[/url] .
Diplomi_hdMi
29 Oct 25 at 8:01 pm