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!
«Частный Медик 24» в стационаре помогает начать жизнь заново — с чистого листа, без последствий запоя.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-v-stacionare22.ru/]стационар вывод из запоя нижний новгород[/url]
GordonGok
8 Oct 25 at 2:35 am
Minotaurus presale is my top watch for 2025—blockchain gaming market is exploding at $14B+. $MTAUR’s balanced distribution prevents dumps, smart move. Eager to customize my minotaur avatar soon.
mtaur token
WilliamPargy
8 Oct 25 at 2:36 am
купить диплом университета [url=http://rudik-diplom10.ru/]купить диплом университета[/url] .
Diplomi_esSa
8 Oct 25 at 2:37 am
купить диплом техникума настоящий [url=https://frei-diplom12.ru]купить диплом техникума настоящий[/url] .
Diplomi_jbPt
8 Oct 25 at 2:37 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
трипскан
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.”
RichardIncah
8 Oct 25 at 2:40 am
новости легкой атлетики [url=https://sportivnye-novosti-2.ru/]новости легкой атлетики[/url] .
sportivnie novosti_ldma
8 Oct 25 at 2:40 am
I blog often and I truly thank you for your information. This great article has truly peaked my
interest. I am going to book mark your website and keep checking for new information about once
a week. I opted in for your RSS feed too.
C4A file program
8 Oct 25 at 2:40 am
обзор спортивных событий [url=https://sport-novosti-2.ru]https://sport-novosti-2.ru[/url] .
sport novosti_uemn
8 Oct 25 at 2:45 am
пансионат для пожилых с инсультом
pansionat-tula012.ru
пансионат для престарелых
pansionattulaNeT
8 Oct 25 at 2:46 am
новости олимпиады [url=sportivnye-novosti-2.ru]новости олимпиады[/url] .
sportivnie novosti_cfma
8 Oct 25 at 2:47 am
купить диплом в белогорске [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_mgSa
8 Oct 25 at 2:48 am
отзывы купить диплом колледжа [url=www.frei-diplom12.ru/]www.frei-diplom12.ru/[/url] .
Diplomi_tcPt
8 Oct 25 at 2:48 am
Пациенты «Частного Медика 24» получают не только лечение, но и внимание к психологическому состоянию.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]вывод из запоя в стационаре клиника нижний новгород[/url]
CharlesElage
8 Oct 25 at 2:50 am
новости футбола [url=www.sport-novosti-2.ru]новости футбола[/url] .
sport novosti_gvmn
8 Oct 25 at 2:50 am
новости спорта россии [url=https://sportivnye-novosti-1.ru/]новости спорта россии[/url] .
sportivnie novosti_nzpi
8 Oct 25 at 2:51 am
В Краснодаре клиника «Детокс» предоставляет услугу вызова нарколога на дом. Специалисты приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Подробнее – [url=https://narkolog-na-dom-krasnodar28.ru/]вызов врача нарколога на дом краснодар[/url]
Bobbyevoma
8 Oct 25 at 2:51 am
лечение запоя челябинск
vivod-iz-zapoya-chelyabinsk012.ru
лечение запоя
zapojchelyabinskNeT
8 Oct 25 at 2:52 am
Программа вывода из запоя в Воронеже от «Частного Медика 24» включает не только устранение физической зависимости, но и работу по восстановлению сна, гидратацию, лекарственную поддержку, а также психотерапию, чтобы помочь справиться не просто с запоем, но и с причинами, которые к нему привели.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре анонимно[/url]
Stevennom
8 Oct 25 at 2:54 am
спорт онлайн [url=https://www.sport-novosti-2.ru]https://www.sport-novosti-2.ru[/url] .
sport novosti_dqmn
8 Oct 25 at 2:56 am
мясо кости для собак Говяжья нога – это натуральное и долгоиграющее лакомство, особенно подходящее для крупных собак. Она помогает очистить зубы от налета, укрепляет челюсти и занимает питомца на длительное время. Важно следить за тем, чтобы собака не отгрызала слишком большие куски, которые могут представлять опасность для пищеварительной системы. Рекомендуется давать говяжью ногу под присмотром.
DannyBow
8 Oct 25 at 2:58 am
обзор спортивных событий [url=https://www.sportivnye-novosti-2.ru]обзор спортивных событий[/url] .
sportivnie novosti_czma
8 Oct 25 at 3:00 am
https://us.community.sony.com/s/profile/005Dp000004fKxo?language=en_US
Thomasbip
8 Oct 25 at 3:06 am
как купить диплом в колледже [url=http://frei-diplom12.ru/]как купить диплом в колледже[/url] .
Diplomi_mpPt
8 Oct 25 at 3:08 am
купить диплом в люберцах [url=http://rudik-diplom10.ru/]купить диплом в люберцах[/url] .
Diplomi_wcSa
8 Oct 25 at 3:08 am
новости мирового спорта [url=https://sportivnye-novosti-2.ru/]новости мирового спорта[/url] .
sportivnie novosti_hmma
8 Oct 25 at 3:10 am
you are actually a just right webmaster. The web site
loading speed is incredible. It sort of feels that you are doing any distinctive
trick. Furthermore, The contents are masterpiece.
you have done a great activity in this topic!
Football
8 Oct 25 at 3:12 am
В «Частном Медике 24» работают круглосуточно, чтобы помощь при запое всегда была рядом.
Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]наркология вывод из запоя в стационаре в нижний новгороде[/url]
Jeffreyneink
8 Oct 25 at 3:14 am
люстры Каждый дом начинается со света. Именно свет создает атмосферу уюта, роскоши и комфорта. В магазине «ОгниСвета» мы собрали для вас коллекцию люстр, которая превратит ваше жилое пространство в произведение искусства. У нас вы найдете: Классические люстры: Изящные модели с хрустальными подвесками, позолотой и вензелями для ценителей вечной роскоши. Они станут центральным элементом вашей гостиной или столовой. Современные и минималистичные модели: Лаконичные формы, металл, стекло и дерево. Идеальное решение для интерьеров в стиле лофт, хай-тек или сканди. Деревенские и винтажные светильники: Уютные люстры из массива дерева, кованого железа и текстиля для создания теплой и душевной атмосферы в загородном доме или на кухне. Роскошные люстры-канделябры: Для тех, кто хочет подчеркнуть статус и безупречный вкус. Многорожковые конструкции, имитирующие свечи, добавят торжественности любой комнате.
JamesInsom
8 Oct 25 at 3:14 am
Prednisone tablets online USA [url=http://predniwellonline.com/#]Prednisone without prescription USA[/url] Prednisone tablets online USA
Michaelriz
8 Oct 25 at 3:15 am
спортивные трансляции [url=https://sportivnye-novosti-2.ru/]спортивные трансляции[/url] .
sportivnie novosti_fima
8 Oct 25 at 3:16 am
спортивные прогнозы на сегодня [url=www.prognozy-ot-professionalov5.ru]спортивные прогнозы на сегодня[/url] .
prognozi ot professionalov_sfSt
8 Oct 25 at 3:16 am
новости хоккея [url=http://www.sport-novosti-2.ru]новости хоккея[/url] .
sport novosti_tzmn
8 Oct 25 at 3:19 am
Hi there, You’ve done an incredible job. I will definitely digg it and personally suggest to my friends.
I am sure they’ll be benefited from this site.
download ebook
8 Oct 25 at 3:21 am
новости тенниса [url=https://www.sportivnye-novosti-2.ru]новости тенниса[/url] .
sportivnie novosti_awma
8 Oct 25 at 3:23 am
купить диплом в новочеркасске [url=rudik-diplom10.ru]rudik-diplom10.ru[/url] .
Diplomi_crSa
8 Oct 25 at 3:24 am
купить диплом техникума настоящий [url=https://frei-diplom12.ru/]купить диплом техникума настоящий[/url] .
Diplomi_xfPt
8 Oct 25 at 3:24 am
прогнозы на спорт с описанием [url=http://prognozy-ot-professionalov5.ru/]http://prognozy-ot-professionalov5.ru/[/url] .
prognozi ot professionalov_mrSt
8 Oct 25 at 3:25 am
точный прогноз на футбол [url=www.kompyuternye-prognozy-na-futbol23.ru/]www.kompyuternye-prognozy-na-futbol23.ru/[/url] .
komputernie prognozi na fytbol_ynPi
8 Oct 25 at 3:26 am
спорт 24 часа [url=http://sport-novosti-2.ru]http://sport-novosti-2.ru[/url] .
sport novosti_yvmn
8 Oct 25 at 3:26 am
Thank you a bunch for sharing this with all of us you actually understand what
you’re speaking approximately! Bookmarked. Kindly also talk over with my website =).
We can have a link alternate contract among us
schweizer online casinos
8 Oct 25 at 3:26 am
новости мирового спорта [url=https://sport-novosti-2.ru/]https://sport-novosti-2.ru/[/url] .
sport novosti_dymn
8 Oct 25 at 3:30 am
wagisonsncompany – Their site feels solid, visuals are clean and structure looks professional.
Frederick Matzke
8 Oct 25 at 3:31 am
где купить диплом медсестры колледжа [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_yePt
8 Oct 25 at 3:32 am
купить диплом в феодосии [url=http://rudik-diplom10.ru]http://rudik-diplom10.ru[/url] .
Diplomi_ytSa
8 Oct 25 at 3:32 am
В Самаре в «Частном Медике 24» пациент получает детоксикацию, восстановительное лечение и круглосуточное наблюдение врачей.
Исследовать вопрос подробнее – https://vyvod-iz-zapoya-v-stacionare-samara24.ru
Jamessor
8 Oct 25 at 3:34 am
прогнозы на кхл сегодня от профессионалов [url=https://prognozy-ot-professionalov5.ru/]прогнозы на кхл сегодня от профессионалов[/url] .
prognozi ot professionalov_zvSt
8 Oct 25 at 3:34 am
номер наркологии [url=narkologicheskaya-klinika-19.ru]narkologicheskaya-klinika-19.ru[/url] .
narkologicheskaya klinika _uami
8 Oct 25 at 3:38 am
I’m not that much of a online reader to be honest but your blogs really
nice, keep it up! I’ll go ahead and bookmark your site
to come back later on. Cheers
Cheers
8 Oct 25 at 3:42 am
купить диплом техникума недорого [url=https://frei-diplom12.ru/]купить диплом техникума недорого[/url] .
Diplomi_ewPt
8 Oct 25 at 3:43 am
купить диплом в йошкар-оле [url=www.rudik-diplom10.ru]купить диплом в йошкар-оле[/url] .
Diplomi_blSa
8 Oct 25 at 3:43 am