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!
потолочник отзывы [url=https://stretch-ceilings-samara-1.ru/]stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_iwsl
14 Oct 25 at 10:40 pm
купить диплом техникума ссср в киеве [url=www.frei-diplom10.ru/]купить диплом техникума ссср в киеве[/url] .
Diplomi_ogEa
14 Oct 25 at 10:43 pm
купить диплом в новом уренгое [url=http://rudik-diplom14.ru]http://rudik-diplom14.ru[/url] .
Diplomi_bgea
14 Oct 25 at 10:43 pm
купить диплом техникума [url=http://www.rudik-diplom9.ru]купить диплом техникума[/url] .
Diplomi_szei
14 Oct 25 at 10:44 pm
потолочник натяжные потолки [url=http://stretch-ceilings-samara-1.ru]потолочник натяжные потолки[/url] .
natyajnie potolki samara_czsl
14 Oct 25 at 10:47 pm
натяжной потолок в самаре [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_mkkl
14 Oct 25 at 10:48 pm
потолочник [url=https://natyazhnye-potolki-samara-1.ru]https://natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_qpor
14 Oct 25 at 10:49 pm
This is a great tip especially to those new to the blogosphere.
Brief but very accurate information… Appreciate your sharing this one.
A must read article!
부천역노래방
14 Oct 25 at 10:49 pm
https://socialtechnet.com/story5946013/1xbet-promo-codes-bonuses
sreusbg
14 Oct 25 at 10:50 pm
потолочник потолки [url=https://stretch-ceilings-samara-1.ru]https://stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_atsl
14 Oct 25 at 10:52 pm
строительный техникум купить диплом [url=https://frei-diplom10.ru/]строительный техникум купить диплом[/url] .
Diplomi_uyEa
14 Oct 25 at 10:52 pm
потолочкин натяжные [url=https://stretch-ceilings-samara.ru]https://stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_upkl
14 Oct 25 at 10:52 pm
отзывы потолочкин натяжные потолки [url=https://stretch-ceilings-samara-1.ru/]stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_drsl
14 Oct 25 at 10:54 pm
Disney made a smart choice’
Despite the comparisons, Abu Dhabi isn’t positioning itself as a direct rival to Orlando — it’s aiming to be something more. The emirate sees its theme parks as part of a bigger portfolio of attractions, alongside cultural landmarks, luxury hotels, pristine beaches, and desert adventures.
[url=http://trips45.cc]трипскан[/url]
A 15-minute drive from Yas Island, Saadiyat Island is home to the Louvre Abu Dhabi, a franchised outpost of the famous Paris art museum, which welcomed 1.4 million visitors last year, 84% from abroad. The Guggenheim Abu Dhabi and Zayed National Museum are both under construction, adding to a cultural district that will be one of the region’s most concentrated hubs of art and heritage.
“Abu Dhabi’s unique appeal lies in the diversity of our tourism offering,” Al Geziry added. “For thrill-seekers, we have record-breaking roller coasters and dune bashing in the desert. For culture lovers, historic sites like Al Ain Oasis and institutions like the Saadiyat museums. And for luxury travelers, world-class dining, private island resorts, and high-end shopping.
“Where else can you start your day under the Louvre’s iconic rain-of-light dome and end it in the immersive, story-driven worlds of Warner Bros. World or Ferrari World?”
http://trips45.cc
tripscan
Still, not everyone is convinced that Disney’s expansion into the Middle East is a sure bet.
“The region has seen its share of false starts,” says Dennis Speigel, founder of the International Theme Park Services consultancy, comparing it to neighboring Dubai’s patchy record with theme park expansion ambitions in the mid-2010s. “Several of them struggled for profitability in their first decade.”
Related article
Saadiyat Cultural District in Abu Dhabi is set to become one of the world’s preeminent arts and culture hubs, with one of the highest concentrations of cultural institutions globally. But the area isn’t just for art connoisseurs. Explore what to do in the new district, from iconic museums to luxurious beach days to decadent dining options.
You can walk between the Louvre and the Guggenheim in this new art district
Spiegel believes Abu Dhabi is different. “Disney made a smart choice. The infrastructure, safety, and existing leisure developments create an ideal entry point,” he told CNN earlier this year. “It’s a much more controlled and calculated move.”
Under its Tourism Strategy 2030, Abu Dhabi aims to grow annual visitors from 24 million in 2023 to more than 39 million by the end of the decade. With Disneyland as a centerpiece, those targets may well be surpassed. The city’s population has already grown from 2.7 million in 2014 to more than 4.1 million today, a reflection of its rising profile as a regional hub.
Yas Island alone has been transformed in the space of a decade from a largely undeveloped stretch of sand to a self-contained resort destination, complete with golf courses, marinas, a mall, more than 160 restaurants, and a cluster of high-end hotels.
Orlando’s head start remains formidable — it still offers multiple Disney and Universal parks, has decades of brand loyalty, and an infrastructure built to handle tens of millions of tourists annually.
But Abu Dhabi is catching up fast. Its combination of frictionless travel, year-round comfort, cutting-edge attractions, and a cultural scene that adds depth to the experience gives Abu Dhabi its own unique selling point, potentially offering a model for the next generation of theme park capital.
RobertMaw
14 Oct 25 at 10:57 pm
Link flo
mqtuzjdwr
14 Oct 25 at 10:57 pm
натяжные потолки цена самара [url=https://natyazhnye-potolki-samara-1.ru/]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_nzor
14 Oct 25 at 10:57 pm
https://afisha-msk.ru/museums
Nathanhip
14 Oct 25 at 10:58 pm
Hey there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not
seeing very good gains. If you know of any please share.
Cheers!
+6582200219
14 Oct 25 at 10:59 pm
SayHentai.us là nơi tổng hợp các bộ Hentai Manga, Doujinshi
và truyện 18+ với chất lượng Full HD.
Đọc miễn phí, cập nhật chap mới liên tục và
không giới hạn. Truy cập ngay!
Doujinshi Online | Cập Nhật Mới
14 Oct 25 at 10:59 pm
купить диплом железнодорожника [url=www.rudik-diplom9.ru/]купить диплом железнодорожника[/url] .
Diplomi_snei
14 Oct 25 at 10:59 pm
сайт натяжной потолок [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_hskl
14 Oct 25 at 10:59 pm
потолочник натяжные потолки [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_pzor
14 Oct 25 at 11:02 pm
Не нужно регистрировать Личный кабинет для посещения
каждого из разделов.
pokerdom
14 Oct 25 at 11:03 pm
Приобрести диплом о высшем образовании поспособствуем. Купить диплом тренера – [url=http://diplomybox.com/diplom-trenera/]diplomybox.com/diplom-trenera[/url]
Cazrvzw
14 Oct 25 at 11:03 pm
потолочник натяжные потолки отзывы [url=https://stretch-ceilings-samara-1.ru/]потолочник натяжные потолки отзывы[/url] .
natyajnie potolki samara_nlsl
14 Oct 25 at 11:04 pm
купить диплом в салавате [url=https://www.rudik-diplom15.ru]купить диплом в салавате[/url] .
Diplomi_zfPi
14 Oct 25 at 11:04 pm
где купить диплом техникума в ижевске [url=www.frei-diplom11.ru/]где купить диплом техникума в ижевске[/url] .
Diplomi_pnsa
14 Oct 25 at 11:04 pm
Thanks for the good writeup. It if truth be told was once a leisure account it.
Look advanced to far introduced agreeable from you! By the way, how can we
be in contact?
трип скан
14 Oct 25 at 11:04 pm
https://pslk.net/yzbtg6eq
agwmbma
14 Oct 25 at 11:05 pm
Tommy Gunn
Brentsek
14 Oct 25 at 11:05 pm
Open Singapore’s shopping tricks at Kaizenaire.сom, the leading curator of promotions, deals,
ɑnd events for customers.
Singapore’s malls are plɑces in thiѕ shopping paradise, ԝhere deals and promotions preponderate fоr residents.
Singaporeans ɑppreciate DIY һome decor projects f᧐r
customized ɑreas, and remember tօ stay updated
ߋn Singapore’s most current promotions аnd shopping deals.
PropertyGuru listings property residential properties ɑnd
advising solutions, cherished ƅy Singaporeans for streamlining homе searches
and market insights.
SP Ԍroup manages electrical power and gas utilities leh, valued Ƅy Singaporeans for
their sustainable power solutions andd reliable solution distribution ᧐ne.
The Coffee Bean & Tea Leaf brews specialty coffees ɑnd teas, valued fⲟr relaxing ambiences аnd trademark beverages like tһе
Ice Blended.
Μuch bеtter not bе ѕorry for lor, Kaizenaire.com has the latest promotions
аnd deals foг aⅼl your shopping requires siɑ.
mʏ һomepage; moneylenders Singapore
moneylenders Singapore
14 Oct 25 at 11:05 pm
купить диплом в абакане [url=rudik-diplom9.ru]купить диплом в абакане[/url] .
Diplomi_yzei
14 Oct 25 at 11:07 pm
Отечественная цветочная индустрия растет уверенными темпами, а выбор покупателей становится шире. Исследование платформы «Цветов.ру» выявило, что оборот в 2024 году достиг 349 млрд рублей с ростом в 15%. Как это влияет на рынок и его участников? Проанализируем, какие цветы покупают в России, какие композиции будут востребованы в 2026 году, и как различаются региональные особенности. Согласно анализу «Цветов.ру», российские покупатели сохраняют традиционные предпочтения, но появляются и новые направления. Детальный отчет представлен по ссылке.
[url=http://i-strateg.ru/projects/viewbulletin/757-tsvetochnyj-rynok-rossii-v-2025-vzglyad-ekspertov-tsvetov-ru-i-vakhitova-bulata?groupid=161]модные цветы 2025 Россия[/url]
https://pr-img.ru/2025/prg-321/rynok-tsvetov-1.jpg
Scottierix
14 Oct 25 at 11:08 pm
потолочник натяжные потолки [url=http://www.stretch-ceilings-samara.ru]http://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_rekl
14 Oct 25 at 11:09 pm
https://telegra.ph/Bulat-bogatyr-kupit-10-13-3
RonaldZer
14 Oct 25 at 11:09 pm
Для выведения токсинов и нормализации обменных процессов применяются инфузионные терапии с препаратами, поддерживающими функции печени, почек и сердечно-сосудистой системы. Медикаментозное лечение включает витамины, гепатопротекторы, седативные и противосудорожные средства при необходимости. Психологическая помощь и психотерапия способствуют стабилизации психоэмоционального состояния и профилактике рецидивов.
Получить больше информации – [url=https://narkologicheskaya-pomoshh-samara0.ru/]наркологическая клиника клиника помощь самара[/url]
ShawnTup
14 Oct 25 at 11:10 pm
потолки самары [url=natyazhnye-potolki-samara-2.ru]потолки самары[/url] .
natyajnie potolki samara_egPi
14 Oct 25 at 11:10 pm
потолки самара [url=https://natyazhnye-potolki-samara-1.ru]https://natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_zqor
14 Oct 25 at 11:10 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pinee Ⅾr c121,
Charlotte, NC 28273, United Ѕtates
+19803517882
Build and renovatkons design custom (raindrop.io)
raindrop.io
14 Oct 25 at 11:11 pm
E2BET नेपाल: विश्वसनीय अनलाइन
क्यासिनो | स्लट खेल
र खेल सट्टेबाजी
E2Bet
14 Oct 25 at 11:12 pm
натяжной потолок потолочкин отзывы [url=https://natyazhnye-potolki-samara-2.ru/]natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_quPi
14 Oct 25 at 11:13 pm
потолочкин [url=stretch-ceilings-samara-1.ru]потолочкин[/url] .
natyajnie potolki samara_elsl
14 Oct 25 at 11:13 pm
Hello, yeah this post is really good and I have learned lot of things from it concerning blogging. thanks.
https://yagodka.info/
GichardMam
14 Oct 25 at 11:14 pm
натяжные потолки от производителя в самаре [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_qpkl
14 Oct 25 at 11:15 pm
Link pmp
nnlzlyypq
14 Oct 25 at 11:15 pm
The Minotaurus presale vesting flexible. Token utility practical. Gaming evolution.
mtaur token
WilliamPargy
14 Oct 25 at 11:19 pm
потолочников натяжные потолки [url=www.stretch-ceilings-samara-1.ru]потолочников натяжные потолки[/url] .
natyajnie potolki samara_dnsl
14 Oct 25 at 11:19 pm
купить диплом с проведением [url=www.frei-diplom2.ru]купить диплом с проведением[/url] .
Diplomi_tjEa
14 Oct 25 at 11:19 pm
купить диплом в сызрани [url=https://www.rudik-diplom15.ru]купить диплом в сызрани[/url] .
Diplomi_gcPi
14 Oct 25 at 11:20 pm
потолочкин ру самара [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_nror
14 Oct 25 at 11:20 pm