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=www.rudik-diplom4.ru/]куплю диплом кандидата наук[/url] .
Diplomi_caOr
5 Oct 25 at 7:52 am
как купить диплом техникума с занесением в реестр цена в [url=http://www.frei-diplom3.ru]как купить диплом техникума с занесением в реестр цена в[/url] .
Diplomi_jvKt
5 Oct 25 at 7:55 am
Обратились в Окна в СПб, чтобы заменить старые деревянные окна на новые ПВХ. Очень понравилось, что все работы сделали за один день. Монтажники были аккуратными и внимательными к деталям. Теперь окна герметичные, тихие и очень удобные в эксплуатации https://okna-v-spb.ru/
RobertPhece
5 Oct 25 at 7:55 am
купить диплом в артеме [url=https://rudik-diplom8.ru/]https://rudik-diplom8.ru/[/url] .
Diplomi_qqMt
5 Oct 25 at 7:55 am
Заказывали остекление лоджии в Окна в СПб. Всё сделали профессионально и в срок. Теперь балкон стал удобным и красивым помещением. Мы очень довольны – https://okna-v-spb.ru/
RobertPhece
5 Oct 25 at 7:55 am
купить речной диплом [url=http://rudik-diplom2.ru]купить речной диплом[/url] .
Diplomi_cmpi
5 Oct 25 at 7:56 am
купить диплом в кинешме [url=www.rudik-diplom7.ru/]купить диплом в кинешме[/url] .
Diplomi_hvPl
5 Oct 25 at 7:56 am
купить диплом техникума недорого [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_fyea
5 Oct 25 at 7:56 am
купить легальный диплом техникума [url=frei-diplom1.ru]купить легальный диплом техникума[/url] .
Diplomi_ylOi
5 Oct 25 at 7:57 am
buy amoxicillin: Buy Amoxicillin for tooth infection – Amoxicillin 500mg buy online
Glennchilt
5 Oct 25 at 8:00 am
купить диплом в орске [url=http://rudik-diplom4.ru]купить диплом в орске[/url] .
Diplomi_afOr
5 Oct 25 at 8:01 am
I constantly emailed this website post page to all
my associates, because if like to read it after that my friends will too.
web site
5 Oct 25 at 8:01 am
Watch out, Orlando, a new world theme park capital is rising in the Arabian desert
[url=https://tripscan44.cc]трипскан сайт[/url]
For decades, Orlando has reigned as the global capital of theme parks — a place where Disney, Universal, SeaWorld and countless other attractions have drawn millions of visitors.
But a challenger for the crown has emerged from an unlikely place: the deserts of the Arabian Gulf. In a destination once known more for oil wealth and camel racing than roller coasters, Abu Dhabi is building an adrenaline-charged playground that could give Orlando a run for its money.
And it just landed the ultimate weapon: Disney.
https://tripscan44.cc
tripscan top
In May 2025, when Disney announced its first new theme park in 15 years, it chose Abu Dhabi over other key theme park destinations in California, Japan and even Orlando.
There was “no question,” says Josh D’Amaro, chairman of Disney Experiences. The UAE capital, already home to Ferrari World, with the world’s fastest roller coaster; Warner Bros. World (built under license by CNN’s parent company, Warner Brothers Discovery); Yas Waterworld, an epic network of slides and pools; and more recently, SeaWorld Yas Island Abu Dhabi. It’s clear the emirate is emerging as the most serious challenger Orlando has ever faced.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride. Leisa Tyler/LightRocket/Getty Images
Disneyland Abu Dhabi, expected to open on Yas Island in the early 2030s, will be the company’s most technologically advanced park ever. Renderings show a shimmering, futuristic tower at its center — more closely resembling Abu Dhabi’s gleaming skyline than a traditional European castle. It will be the first Disney resort set on an accessible shoreline, located just 20 minutes from downtown Abu Dhabi.
Related video
What began as a shared passion between two friends has grown into the “Abu Dhabi House Movement” — a fast-growing community redefining the city’s music scene. Co-founder Tom Worton takes us inside this grassroots world, where music lovers, DJs, and cultural spaces collide.
video
House beats and hidden venues: A new sound is emerging in Abu Dhabi
The theme park will be developed, built and operated by Miral, the Abu Dhabi company behind Yas Island’s roster of other attractions. Disney Imagineers will handle creative design and operational oversight, making sure the new park is in keeping with Disney’s brand.
Miral’s CEO, Mohamed Abdalla Al Zaabi, says demand already exists: 2024 saw a 20% rise in theme park attendance on Yas Island. And expansion is already in the works — a Harry Potter–themed land at Warner Bros. World, more record-breaking rides at Ferrari World, new themed hotels, and even two beaches along Yas Bay Waterfront.
‘This isn’t about building another theme park’
disney 3.jpg
Why Disney chose Abu Dhabi for their next theme park location
7:02
Abu Dhabi’s location, a medium-haul flight away from both Europe and Asia, and relatively short hop away from India, means millions of potential visitors are within relatively easy reach.
“This isn’t about building another theme park,” Saleh Mohamed Al Geziry, Abu Dhabi’s director general of tourism, told CNN. “It’s about defining Abu Dhabi as a global destination where culture, entertainment and luxury intersect.”
QuincyNoita
5 Oct 25 at 8:02 am
купить диплом с занесением в реестр в спб [url=http://frei-diplom1.ru/]http://frei-diplom1.ru/[/url] .
Diplomi_jlOi
5 Oct 25 at 8:03 am
купить диплом учителя физической культуры [url=http://rudik-diplom2.ru]купить диплом учителя физической культуры[/url] .
Diplomi_ddpi
5 Oct 25 at 8:05 am
Выезд врача позволяет начать помощь сразу, без ожидания свободной палаты. Специалист оценит состояние, проведёт осмотр, поставит капельницу, даст рекомендации по режиму и питанию, объяснит правила безопасности. Мы оставляем подробные инструкции родственникам, чтобы дома поддерживались питьевой режим, контроль давления и спокойная обстановка. Если домашних условий недостаточно (выраженная слабость, риски осложнений, сопутствующие заболевания), мы организуем транспортировку в стационар без задержек и бюрократии.
Изучить вопрос глубже – [url=https://narkologicheskaya-klinika-balashiha0.ru/]круглосуточная наркологическая клиника[/url]
Eduardofug
5 Oct 25 at 8:06 am
купить диплом математика [url=http://rudik-diplom4.ru/]купить диплом математика[/url] .
Diplomi_shOr
5 Oct 25 at 8:06 am
купить диплом о среднем образовании [url=https://rudik-diplom8.ru]купить диплом о среднем образовании[/url] .
Diplomi_qhMt
5 Oct 25 at 8:06 am
купить диплом в великом новгороде [url=https://rudik-diplom5.ru]купить диплом в великом новгороде[/url] .
Diplomi_lvma
5 Oct 25 at 8:07 am
купить проведенный диплом красноярск [url=http://frei-diplom6.ru/]купить проведенный диплом красноярск[/url] .
Diplomi_doOl
5 Oct 25 at 8:07 am
купить техникум диплом [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_jbea
5 Oct 25 at 8:07 am
легально купить диплом о высшем образовании [url=https://frei-diplom2.ru/]легально купить диплом о высшем образовании[/url] .
Diplomi_tsEa
5 Oct 25 at 8:07 am
https://kinooco.ru/forums/topic/promokod-na-besplatnuyu-stavku-mostbet/
HenryScarp
5 Oct 25 at 8:09 am
купить диплом в архангельске [url=https://www.rudik-diplom3.ru]купить диплом в архангельске[/url] .
Diplomi_xsei
5 Oct 25 at 8:09 am
купить диплом в керчи [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .
Diplomi_poPl
5 Oct 25 at 8:10 am
кухни на заказ санкт петербург от производителя [url=www.kuhni-spb-4.ru/]www.kuhni-spb-4.ru/[/url] .
kyhni spb_wjer
5 Oct 25 at 8:11 am
Paragraph writing is also a excitement, if you be familiar
with then you can write if not it is difficult to write.
@SEO_LINKK - SEO BLACKHAT
5 Oct 25 at 8:12 am
Watch out, Orlando, a new world theme park capital is rising in the Arabian desert
[url=https://tripscan44.cc]tripscan top[/url]
For decades, Orlando has reigned as the global capital of theme parks — a place where Disney, Universal, SeaWorld and countless other attractions have drawn millions of visitors.
But a challenger for the crown has emerged from an unlikely place: the deserts of the Arabian Gulf. In a destination once known more for oil wealth and camel racing than roller coasters, Abu Dhabi is building an adrenaline-charged playground that could give Orlando a run for its money.
And it just landed the ultimate weapon: Disney.
https://tripscan44.cc
tripscan
In May 2025, when Disney announced its first new theme park in 15 years, it chose Abu Dhabi over other key theme park destinations in California, Japan and even Orlando.
There was “no question,” says Josh D’Amaro, chairman of Disney Experiences. The UAE capital, already home to Ferrari World, with the world’s fastest roller coaster; Warner Bros. World (built under license by CNN’s parent company, Warner Brothers Discovery); Yas Waterworld, an epic network of slides and pools; and more recently, SeaWorld Yas Island Abu Dhabi. It’s clear the emirate is emerging as the most serious challenger Orlando has ever faced.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride. Leisa Tyler/LightRocket/Getty Images
Disneyland Abu Dhabi, expected to open on Yas Island in the early 2030s, will be the company’s most technologically advanced park ever. Renderings show a shimmering, futuristic tower at its center — more closely resembling Abu Dhabi’s gleaming skyline than a traditional European castle. It will be the first Disney resort set on an accessible shoreline, located just 20 minutes from downtown Abu Dhabi.
Related video
What began as a shared passion between two friends has grown into the “Abu Dhabi House Movement” — a fast-growing community redefining the city’s music scene. Co-founder Tom Worton takes us inside this grassroots world, where music lovers, DJs, and cultural spaces collide.
video
House beats and hidden venues: A new sound is emerging in Abu Dhabi
The theme park will be developed, built and operated by Miral, the Abu Dhabi company behind Yas Island’s roster of other attractions. Disney Imagineers will handle creative design and operational oversight, making sure the new park is in keeping with Disney’s brand.
Miral’s CEO, Mohamed Abdalla Al Zaabi, says demand already exists: 2024 saw a 20% rise in theme park attendance on Yas Island. And expansion is already in the works — a Harry Potter–themed land at Warner Bros. World, more record-breaking rides at Ferrari World, new themed hotels, and even two beaches along Yas Bay Waterfront.
‘This isn’t about building another theme park’
disney 3.jpg
Why Disney chose Abu Dhabi for their next theme park location
7:02
Abu Dhabi’s location, a medium-haul flight away from both Europe and Asia, and relatively short hop away from India, means millions of potential visitors are within relatively easy reach.
“This isn’t about building another theme park,” Saleh Mohamed Al Geziry, Abu Dhabi’s director general of tourism, told CNN. “It’s about defining Abu Dhabi as a global destination where culture, entertainment and luxury intersect.”
QuincyNoita
5 Oct 25 at 8:12 am
captcha-kraken17at.org – Found this site while testing links, layout feels oddly polished already.
Chet Seelig
5 Oct 25 at 8:13 am
купить диплом о высшем образовании с занесением в реестр цена [url=https://www.frei-diplom3.ru]купить диплом о высшем образовании с занесением в реестр цена[/url] .
Diplomi_kxKt
5 Oct 25 at 8:13 am
купил диплом легально [url=http://frei-diplom5.ru/]купил диплом легально[/url] .
Diplomi_mtPa
5 Oct 25 at 8:14 am
купить диплом колледжа [url=http://rudik-diplom5.ru]купить диплом колледжа[/url] .
Diplomi_anma
5 Oct 25 at 8:16 am
купить диплом в мичуринске [url=https://rudik-diplom2.ru]https://rudik-diplom2.ru[/url] .
Diplomi_jdpi
5 Oct 25 at 8:16 am
Greetings! Very helpful advice within this article!
It’s the little changes which will make the greatest changes.
Thanks a lot for sharing!
informasi toto slot
5 Oct 25 at 8:16 am
Онлайн магазин – купить мефедрон, кокаин, бошки
RodneyDof
5 Oct 25 at 8:16 am
купить кухню в спб от производителя [url=kuhni-spb-4.ru]купить кухню в спб от производителя[/url] .
kyhni spb_gker
5 Oct 25 at 8:17 am
купить речной диплом [url=http://www.rudik-diplom11.ru]купить речной диплом[/url] .
Diplomi_ynMi
5 Oct 25 at 8:18 am
купить диплом московского торгово экономического техникума [url=http://www.frei-diplom9.ru]купить диплом московского торгово экономического техникума[/url] .
Diplomi_bfea
5 Oct 25 at 8:18 am
Bullish on Minotaurus ICO’s raffle prizes. $MTAUR utility in zones deepens play. Growth trajectory strong.
minotaurus presale
WilliamPargy
5 Oct 25 at 8:19 am
прогноз на хоккей сегодня [url=http://www.prognozy-na-khokkej4.ru]прогноз на хоккей сегодня[/url] .
prognozi na hokkei_ryOl
5 Oct 25 at 8:19 am
как купить проведенный диплом отзывы [url=https://www.frei-diplom5.ru]https://www.frei-diplom5.ru[/url] .
Diplomi_uuPa
5 Oct 25 at 8:21 am
кухни в спб от производителя [url=https://kuhni-spb-4.ru/]кухни в спб от производителя[/url] .
kyhni spb_vser
5 Oct 25 at 8:21 am
купить диплом ижевск с занесением в реестр [url=www.frei-diplom1.ru/]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_chOi
5 Oct 25 at 8:21 am
совет юриста Рекомендуем посетить профессиональный сайт юриста Светланы Приймак, предлагающий качественную юридическую помощь гражданам и бизнесу в Украине. Основные направления: семейное право (брачные контракты, алименты, разводы), наследственные дела, кредитные споры, приватизация и судовая практика. Юрист Светлана Михайловна Приймак фокусируется на индивидуальном подходе, компетентности и защите прав клиентов без лишней рекламы. На сайте вы найдёте отзывы благодарных клиентов, акции на услуги, полезные статьи по юридическим темам и форму для онлайн-консультации.
Kevinbow
5 Oct 25 at 8:21 am
купить диплом высшем образовании занесением реестр [url=http://frei-diplom2.ru/]купить диплом высшем образовании занесением реестр[/url] .
Diplomi_awEa
5 Oct 25 at 8:21 am
купить диплом в твери [url=http://rudik-diplom5.ru/]купить диплом в твери[/url] .
Diplomi_wama
5 Oct 25 at 8:22 am
современное медицинское оборудование [url=www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .
oborydovanie medicinskoe_iaOn
5 Oct 25 at 8:23 am
купить диплом в новоалтайске [url=https://rudik-diplom8.ru]купить диплом в новоалтайске[/url] .
Diplomi_ydMt
5 Oct 25 at 8:24 am
Купить диплом техникума в Донецк [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_pkea
5 Oct 25 at 8:24 am
Thank you, I’ve recently been looking for information approximately this topic for a long time and yours is the greatest I’ve discovered
till now. However, what concerning the conclusion? Are
you certain about the supply?
Yua Mikami
5 Oct 25 at 8:30 am