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!
https://irishpharmafinder.com/# online pharmacy
Haroldovaph
31 Oct 25 at 6:06 pm
https://prueba.enriquillodigital.com/2025/10/11/melbet-registraciya-v-1-klik-2025/
ThomasMuh
31 Oct 25 at 6:06 pm
irishpharmafinder [url=https://irishpharmafinder.com/#]best Irish pharmacy websites[/url] irishpharmafinder
Hermanengam
31 Oct 25 at 6:06 pm
рулонные шторы на пластиковые окна с электроприводом [url=http://avtomaticheskie-rulonnye-shtory77.ru/]http://avtomaticheskie-rulonnye-shtory77.ru/[/url] .
avtomaticheskie rylonnie shtori_adPa
31 Oct 25 at 6:06 pm
Code promo pour 1xBet : beneficiez un bonus de 100% pour l’inscription jusqu’a 130€. Renforcez votre solde facilement en placant des paris avec un multiplicateur de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Activez cette offre en rechargant votre compte des 1€. Decouvrez cette offre exclusive sur ce lien > https://akteon.fr/misc/pgs/le_code_promo_1xbet.html.
Marvinphike
31 Oct 25 at 6:07 pm
сделать онлайн трансляцию мероприятия [url=www.zakazat-onlayn-translyaciyu4.ru]www.zakazat-onlayn-translyaciyu4.ru[/url] .
zakazat onlain translyaciu_jeSr
31 Oct 25 at 6:07 pm
648704.com – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
Destiny Calemine
31 Oct 25 at 6:08 pm
Howdy would you mind letting me know which hosting company you’re working with?
I’ve loaded your blog in 3 completely different browsers
and I must say this blog loads a lot faster then most. Can you suggest a
good hosting provider at a fair price? Thanks a lot, I
appreciate it!
Velora Nexen
31 Oct 25 at 6:08 pm
Обратившись в «Частный Медик 24» в Ростове-на-Дону, вы получаете не только медицинскую помощь, но и всестороннюю поддержку на пути к выздоровлению.
Подробнее – [url=https://vyvod-iz-zapoya-rostov112.ru/]вывод из запоя на дому недорого[/url]
DarrenBrupe
31 Oct 25 at 6:11 pm
купить диплом в нефтекамске [url=http://www.rudik-diplom15.ru]купить диплом в нефтекамске[/url] .
Diplomi_qkPi
31 Oct 25 at 6:11 pm
https://eletik.com/2025/10/11/promokody-melbet-na-stavku-2025/
JustinAcecy
31 Oct 25 at 6:12 pm
https://liceocentenario.cl/2025/10/11/melbet-igrovye-avtomaty-2025/
RobertHindy
31 Oct 25 at 6:12 pm
тканевые электрожалюзи [url=http://elektricheskie-zhalyuzi97.ru/]http://elektricheskie-zhalyuzi97.ru/[/url] .
elektricheskie jaluzi_hdet
31 Oct 25 at 6:12 pm
Players from India can also quickly sign up for 1win using social networks 1 win india
Robinkanty
31 Oct 25 at 6:12 pm
потолочкин натяжные [url=http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_tama
31 Oct 25 at 6:13 pm
рулонные шторы с электроприводом цена [url=https://avtomaticheskie-rulonnye-shtory1.ru/]рулонные шторы с электроприводом цена[/url] .
avtomaticheskie rylonnie shtori_mdMr
31 Oct 25 at 6:13 pm
Guе dapet maxwin dari spin ini.
link slot gacor
31 Oct 25 at 6:13 pm
рулонные шторки на окна [url=www.rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторки на окна[/url] .
rylonnie shtori s elektroprivodom_esMl
31 Oct 25 at 6:13 pm
Safe Meds Guide: top rated online pharmacies – Safe Meds Guide
Johnnyfuede
31 Oct 25 at 6:14 pm
https://technic.com.vn/2025/10/11/usloviya-bonusa-melbet-2025/
ThomasMuh
31 Oct 25 at 6:15 pm
купить диплом техникума ссср в брянске [url=https://frei-diplom11.ru/]купить диплом техникума ссср в брянске[/url] .
Diplomi_epsa
31 Oct 25 at 6:15 pm
организация онлайн трансляции москва [url=https://zakazat-onlayn-translyaciyu4.ru]организация онлайн трансляции москва[/url] .
zakazat onlain translyaciu_ngSr
31 Oct 25 at 6:18 pm
купить диплом вуза [url=www.rudik-diplom15.ru/]купить диплом вуза[/url] .
Diplomi_yqPi
31 Oct 25 at 6:18 pm
https://lagrandebellezza.ro/melbet-vhod-2025-polnyj-gajd/
RobertHindy
31 Oct 25 at 6:18 pm
рулонные шторки на окна [url=https://www.avtomaticheskie-rulonnye-shtory77.ru]рулонные шторки на окна[/url] .
avtomaticheskie rylonnie shtori_raPa
31 Oct 25 at 6:19 pm
AussieMedsHubAu: AussieMedsHubAu – verified pharmacy coupon sites Australia
Johnnyfuede
31 Oct 25 at 6:21 pm
Great blog right here! Also your web site lots up fast!
What host are you the use of? Can I am getting
your affiliate link in your host? I wish my site loaded up as quickly as yours lol
stem cell treatment for anti-aging thailand
31 Oct 25 at 6:21 pm
https://suphamhanoi.edu.vn/promokod-dlya-melbet-2025-bonusy-i-prognozy
ThomasMuh
31 Oct 25 at 6:21 pm
Вывод из запоя в Ростове-на-Дону можно пройти в клинике «ЧСП№1», с возможностью вызова нарколога на дом.
Подробнее – [url=https://vyvod-iz-zapoya-rostov18.ru/]вывод из запоя на дому круглосуточно[/url]
Vernonneesy
31 Oct 25 at 6:22 pm
купить натяжные потолки в нижнем новгороде недорого [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]https://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_rgma
31 Oct 25 at 6:22 pm
Oh man, no matter if school proves atas, math іѕ tһe critical subject іn building assurance in numƄers.
Aiyah, primary mathematics educates real-ᴡorld applications ⅼike money management, therefore
mɑke sսre your youngster grasps іt rіght starting ʏoung.
Anderson Serangoon Junior College іs a lively institution born fгom the merger of 2 prestigious colleges, cultivating аn encouraging environment that emphasizes
holistic development and scholastic quality.
Ƭhe college boasts contemporary centers, including cutting-edge labs
аnd collective ɑreas, allowing students tο engage deeply in STEM and
innovation-driven projects. Ꮤith a strong focus оn management
and character structure, trainees tɑke advantage of varied ⅽο-curricular activities tһat cultivate durability аnd teamwork.
Itѕ commitment tο worldwide perspectives tһrough exchange programs widens
horizons ɑnd prepares students for an interconnected ѡorld.Graduates typically secure рlaces in leading universities, ѕhowing the
college’s dedication to nurturing confident, welⅼ-rounded individuals.
National Junior College, holding tһe distinction as Singapore’s very fіrst junior college,
offеrs unrivaled avenues fоr intellectual exploration ɑnd management growing ᴡithin a historical аnd
inspiring school thɑt mixes custom with modern educational quality.
Тhe unique boarding program promotes independence
ɑnd a sense of community,wһile advanced reseaгch study
centers and specialized laboratories enable students
fгom varied backgrounds tⲟ pursue sophisticated studies іn arts, sciences,
and liberal arts ԝith optional alternatives foг
personalized knowing paths. Innovative programs encourage deep academic immersion, ѕuch as project-based
гesearch study and interdisciplinary seminars tһat
hone analytical skills and foster creativity ɑmongst aspiring scholars.
Ꭲhrough comprehensive international partnerships, including student
exchanges, worldwide symposiums, ɑnd collaborative initiatives with
overseas universities, students establish broad networks
аnd a nuanced understanding оf worldwide prⲟblems.
Ƭhe college’ѕ alumni, who regularly assume popular roles
іn federal government, academia, аnd industry, exhibit National Junior College’ѕ enduring contribution tо nation-building and the development of visionary, impactful leaders.
Wah lao, гegardless if establishment is hіgh-еnd, maths
acts like tһe critical topic to developing poise
іn numbеrs.
Aiyah, primary mathematics teaches real-ԝorld implementations ⅼike money management, tһerefore
guarantee youг child masters this correctly starting young.
Oh, mathematics serves as the foundation block fоr primary learning, assisting children ԝith dimensional reasoning tо building paths.
Aiyo, minus robust math ⅾuring Junior College, гegardless prestigious institution kids ϲould struggle at next-level calculations, thеrefore cultivate іt noѡ leh.
Strong A-level performance leads tߋ better mental health post-exams,
knowing y᧐u’rе ѕet.
Listen uр, composed pom pi pi, math is among from the top subjects at Junior College, building groundwork fօr A-Level higher calculations.
Review mʏ web site – singapore sec school
singapore sec school
31 Oct 25 at 6:22 pm
рулонные шторы с автоматическим управлением [url=rulonnye-shtory-s-elektroprivodom7.ru]rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_qkMl
31 Oct 25 at 6:22 pm
рулонные шторы на кухню купить [url=www.avtomaticheskie-rulonnye-shtory1.ru]рулонные шторы на кухню купить[/url] .
avtomaticheskie rylonnie shtori_qyMr
31 Oct 25 at 6:23 pm
Прошу обратить внимание на кидок со стороны магазина на ~50000 рублей в Украинской ветке. https://okolo-dom.ru Принял, участие в совместке номер 3, кинг как и подобает этому магазу, все сделал со скоростью звука, прошло 5 дней после оплаты и у меня в руках лежат 50 тонн этой велеколепной вкусняшки, СПАСИБО. Я просто не понимаю как люди заказывают у других когда есть chemical
MiguelDet
31 Oct 25 at 6:23 pm
автоматические рулонные шторы на створку [url=https://avtomaticheskie-rulonnye-shtory1.ru]https://avtomaticheskie-rulonnye-shtory1.ru[/url] .
avtomaticheskie rylonnie shtori_skMr
31 Oct 25 at 6:24 pm
https://www.hoomet.com/profile/7830?tab=541
JeremyRot
31 Oct 25 at 6:25 pm
купить диплом в энгельсе [url=www.rudik-diplom9.ru/]www.rudik-diplom9.ru/[/url] .
Diplomi_srei
31 Oct 25 at 6:26 pm
http://www.google.com.et/url?q=https://amt-games.com/news/1xbet_cameroon_register_bonus_code.html
BrentKef
31 Oct 25 at 6:26 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ɗr c121,
Charlotte, NC 28273, United Տtates
+19803517882
Conversion dining bedroom to room
Conversion dining bedroom to room
31 Oct 25 at 6:28 pm
cheapest pharmacies in the USA: SafeMedsGuide – compare online pharmacy prices
Johnnyfuede
31 Oct 25 at 6:29 pm
заказать онлайн трансляцию [url=http://zakazat-onlayn-translyaciyu4.ru]заказать онлайн трансляцию[/url] .
zakazat onlain translyaciu_riSr
31 Oct 25 at 6:30 pm
горизонтальные жалюзи с электроприводом [url=www.elektricheskie-zhalyuzi97.ru]горизонтальные жалюзи с электроприводом[/url] .
elektricheskie jaluzi_dxet
31 Oct 25 at 6:30 pm
The trial of Bryan Kohberger – the man who brutally murdered four University of Idaho students inside their off-campus home – ended in July before it ever truly began when he accepted a plea deal that saw him sentenced to four consecutive life terms in prison without the possibility of an appeal or parole.
Kohberger sat impassively throughout the hearing as the loved ones of each of the four students whose lives he so callously ended repeatedly asked him the same question: Why?
[url=http://trip-skan45.cc]tripskan[/url]
And when he was finally given the opportunity to answer their questions, he said, “I respectfully decline.”
That decision further fueled the mystery around his motive for murdering Xana Kernodle, Madison Mogen, Ethan Chapin and Kaylee Goncalves.
“There’s no reason for these crimes that could approach anything resembling rationality,” Idaho District Judge Steven Hippler said during Kohberger’s sentencing. “The more we try to extract a reason, the more power and control we give to him.”
But, he added, investigators and researchers may wish to study his actions – if only to learn how to prevent similar crimes from occurring in the future.
http://trip-skan45.cc
трипскан сайт
Indeed, academics and former FBI profilers told CNN the challenge of unravelling the criminal mind of a man like Bryan Kohberger is enticing. And while his trial may be over, in many ways, the story of what can be learned from his crimes may have only just begun.
“We want to squeeze any silver lining that we can out of these tragedies,” said Molly Amman, a retired profiler who spent years leading the FBI’s Behavioral Threat Assessment Center.
“The silver lining is anything we can use to prevent another crime. It starts with learning absolutely, positively everything about the person and the crime that we possibly can.”
CNN
Only Kohberger knows
Even seasoned police officers who arrived at 1122 King Road on November 13, 2022, struggled to process the brutality of the crime scene.
All four victims had been ruthlessly stabbed to death before the attacker vanished through the kitchen’s sliding glass door and into the night.
“The female lying on the left half of the bed … was unrecognizable,” one officer would later write of the attack that killed Kaylee Goncalves. “I was unable to comprehend exactly what I was looking at while trying to discern the nature of the injuries.”
Initial interviews with the two surviving housemates gave investigators a loose timeline and a general description of the killer – an athletic, White male who wore a mask that covered most of his face – but little else.
Police later found a Ka-Bar knife sheath next to Madison’s body that would prove to be critical in capturing her killer.
One of the surviving housemates told police about a month before the attacks, Kaylee saw “a dark figure staring at her from the tree line when she took her dog Murphy out to pee.”
“There has been lighthearted talk and jokes made about a stalker in the past,” the officer noted. “All the girls were slightly nervous about it being a fact, though.”
But after years of investigating the murders, detectives told CNN they were never able to establish a connection between Kohberger and any of the victims, or a motive.
Kohberger is far from the first killer to deny families and survivors the catharsis that comes with confessing, in detail, to his crimes. But that, former FBI profilers tell CNN, is part of what makes the prospect of studying him infuriating and intriguing.
JasonHoG
31 Oct 25 at 6:31 pm
http://www.google.com.bo/url?q=https://www.greenwichodeum.com/wp-content/pages/1XBET_Cameroon_Sign_In_Bonus.html
Arnoldohaupe
31 Oct 25 at 6:31 pm
pharmacy delivery Ireland
Edmundexpon
31 Oct 25 at 6:31 pm
рулонные шторки на окна [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]рулонные шторки на окна[/url] .
rylonnie shtori s elektroprivodom_viMl
31 Oct 25 at 6:32 pm
купить электрические рулонные шторы [url=http://avtomaticheskie-rulonnye-shtory1.ru/]http://avtomaticheskie-rulonnye-shtory1.ru/[/url] .
avtomaticheskie rylonnie shtori_fjMr
31 Oct 25 at 6:32 pm
рулонные шторы жалюзи на окна [url=http://avtomaticheskie-rulonnye-shtory77.ru/]http://avtomaticheskie-rulonnye-shtory77.ru/[/url] .
avtomaticheskie rylonnie shtori_wjPa
31 Oct 25 at 6:32 pm
организация видеотрансляций [url=https://www.zakazat-onlayn-translyaciyu4.ru]организация видеотрансляций[/url] .
zakazat onlain translyaciu_glSr
31 Oct 25 at 6:34 pm
натяжные потолки нижний новгород цены [url=https://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]натяжные потолки нижний новгород цены[/url] .
natyajnie potolki nijnii novgorod_zyma
31 Oct 25 at 6:36 pm