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!
Does your website have a contact page? I’m having problems locating it but, I’d like to shoot
you an email. I’ve got some recommendations for your blog you might be interested in hearing.
Either way, great site and I look forward to seeing it improve over time.
Trenqor Logic AI
30 Jul 25 at 4:16 pm
кайт школа Аренда кайта: плюсы и минусы
RamonLiata
30 Jul 25 at 4:25 pm
NeuroRelief Rx [url=https://neuroreliefrx.com/#]NeuroRelief Rx[/url] NeuroRelief Rx
JamesAmola
30 Jul 25 at 4:31 pm
фільми як 2025 нові фільми 2025 в Україні
ua-bay-239
30 Jul 25 at 4:31 pm
Воспользуйтесь капельницей от запоя в стационаре в Частном Медике?24 (Коломна) — подробнее по ссылке.
Детальнее – [url=https://kapelnica-ot-zapoya-kolomna.ru/]капельница от запоя выезд[/url]
Eddiedrell
30 Jul 25 at 4:40 pm
Узнайте про выведение из запоя в стационаре в Частном Медике 24 (Балашиха) по ссылке.
Осуществить глубокий анализ – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha12.ru/]вывод из запоя недорого город балашиха[/url]
ElbertCox
30 Jul 25 at 4:43 pm
кайт Обучение кайтсёрфингу
RamonLiata
30 Jul 25 at 4:44 pm
В Коломне клиника Частный Медик?24 предлагает капельницу от запоя в стационаре — подробности на сайте клиники.
Подробнее тут – [url=https://kapelnica-ot-zapoya-kolomna14.ru/]капельница от запоя клиника в коломне[/url]
HenryFem
30 Jul 25 at 4:50 pm
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Получить дополнительные сведения – https://quick-vyvod-iz-zapoya-1.ru/
Darrellcex
30 Jul 25 at 4:53 pm
When choosing a crypto casino, look for those that emphasize provably fair gaming to
enhance your trust and confidence in the platform.
Candra
30 Jul 25 at 4:55 pm
Надёжная капельница от запоя в стационаре в клинике Частный Медик?24 (Коломна) — полный курс лечения, узнайте больше.
Получить дополнительную информацию – [url=https://kapelnica-ot-zapoya-kolomna16.ru/]kapelnicza-ot-zapoya kolomna[/url]
AlbertEsold
30 Jul 25 at 4:55 pm
We have been helping Canadians Borrow Money Against Their Car Title Since March 2009 and
are among the very few Completely Online Lenders in Canada.
With us you can obtain a Loan Online from anywhere in Canada as long as
you have a Fully Paid Off Vehicle that is 8 Years old or newer.
We look forward to meeting all your financial needs.
borrow money with my car in ottawa
30 Jul 25 at 5:02 pm
Hello would you mind sharing which blog platform you’re using?
I’m planning to start my own blog soon but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I’m looking for something
unique. P.S Apologies for being off-topic but I had to ask!
взломать аккаунт
30 Jul 25 at 5:08 pm
Hello! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Fluxor Beam AI
30 Jul 25 at 5:16 pm
прогнозы на спорт бесплатно от профессионалов на сегодня [url=www.prognoz-na-segodnya-na-sport10.ru/]www.prognoz-na-segodnya-na-sport10.ru/[/url] .
prognoz na segodnya na sport_ftEn
30 Jul 25 at 5:17 pm
https://sp-banki.ru/zaymy-onlayn-zaymy-i-kredity-dlya-chastnyh-lits-i-biznesa/
MartinShale
30 Jul 25 at 5:18 pm
ClearMeds Direct: ClearMeds Direct – buy amoxicillin 500mg capsules uk
BrianTub
30 Jul 25 at 5:18 pm
Very informative, I found it very useful. Can’t wait to read more. Cheers.
Scarlett Podolsky
30 Jul 25 at 5:21 pm
аренда большой яхты [url=https://yachts-charter-dubai.com/]https://yachts-charter-dubai.com/[/url] .
arenda yaht dybai_ymSr
30 Jul 25 at 5:26 pm
Join millions of traders worldwide with the pocketoptionmobileapp.app. Open trades in seconds, track market trends in real time, and access over 100 assets including forex, stocks, crypto, and commodities. Enjoy fast deposits and withdrawals, clear charts, and a beginner-friendly interface. Perfect for both new and experienced traders – trade on the go with confidence
Robertaxodo
30 Jul 25 at 5:26 pm
My family every time say that I am wasting my time here at web, except I know I am getting experience all the time by reading
such pleasant content.
Here is my site :: Hungary home WiFi easy setup
Hungary home WiFi easy setup
30 Jul 25 at 5:28 pm
прогнозы на спорт онлайн [url=https://prognoz-na-segodnya-na-sport10.ru]https://prognoz-na-segodnya-na-sport10.ru[/url] .
prognoz na segodnya na sport_lyEn
30 Jul 25 at 5:28 pm
Клиника Частный Медик 24 в Балашихе — профессиональный стационарный вывод из запоя, подробности на сайте.
Хочу знать больше – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha11.ru/]наркология вывод из запоя[/url]
RichardBut
30 Jul 25 at 5:30 pm
кайтсёрфинг “Храм знаний”: кайт школа, где рождается уверенность, где страх уступает место восторгу
RamonLiata
30 Jul 25 at 5:33 pm
скачать 1win на андроид с официального сайта [url=1win1140.ru]1win1140.ru[/url]
1win_egMi
30 Jul 25 at 5:36 pm
сколько стоит аренда яхты в дубае [url=https://www.yachts-charter-dubai.com]https://www.yachts-charter-dubai.com[/url] .
arenda yaht dybai_uvSr
30 Jul 25 at 5:37 pm
ставки прогнозы на теннис сегодня [url=www.prognoz-na-segodnya-na-sport9.ru/]www.prognoz-na-segodnya-na-sport9.ru/[/url] .
prognoz na segodnya na sport_jbpl
30 Jul 25 at 5:37 pm
Hello There. I found your blog using msn. This is an extremely well written article.
I’ll make sure to bookmark it and come back to
read more of your useful information. Thanks for the post.
I will certainly return.
slot gacor
30 Jul 25 at 5:39 pm
фільми 2025 року фільми без реклами та реєстрації
uakino-702
30 Jul 25 at 5:40 pm
прогнозы на спорт онлайн [url=https://www.prognoz-na-segodnya-na-sport10.ru]https://www.prognoz-na-segodnya-na-sport10.ru[/url] .
prognoz na segodnya na sport_lxEn
30 Jul 25 at 5:42 pm
order amoxicillin without prescription [url=https://clearmedsdirect.com/#]order amoxicillin without prescription[/url] Clear Meds Direct
JamesAmola
30 Jul 25 at 5:44 pm
Когда организм на пределе, важна срочная помощь в Ростове-На-Дону — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Изучите внимательнее – http://vyvod-iz-zapoya-rostov11.ru/
Gregorysunda
30 Jul 25 at 5:44 pm
Mega onion
RichardPep
30 Jul 25 at 5:46 pm
супер прогнозы на футбол [url=https://kompyuternye-prognozy-na-futbol8.ru]https://kompyuternye-prognozy-na-futbol8.ru[/url] .
komputernie prognozi na fytbol_agsi
30 Jul 25 at 5:47 pm
Пациенты, которые обращаются в нашу клинику, получают целый комплекс преимуществ, благодаря которым лечение проходит максимально эффективно и комфортно:
Детальнее – http://narcolog-na-dom-novosibirsk0.ru/narkolog-na-dom-czena-novosibirsk/
Jameshit
30 Jul 25 at 5:48 pm
прогнозы на спорт с описанием [url=https://prognoz-na-segodnya-na-sport9.ru/]https://prognoz-na-segodnya-na-sport9.ru/[/url] .
prognoz na segodnya na sport_qtpl
30 Jul 25 at 5:50 pm
фільми 2025 року фільми з українським дубляжем онлайн
uakino-740
30 Jul 25 at 5:51 pm
прогнозы на спорт [url=https://prognoz-na-segodnya-na-sport10.ru/]прогнозы на спорт[/url] .
prognoz na segodnya na sport_ayEn
30 Jul 25 at 5:53 pm
https://i38.ru/dengi-obichnie/kak-otkazatsya-ot-strachovki-pri-oformlenii-zayma-shagi-i-soveti
MartinShale
30 Jul 25 at 5:53 pm
مرکز بلیچینگ اسمایل هوم کلینیک
بلیچینگ دندان برای سفیدی دندان ها
30 Jul 25 at 5:53 pm
20
Углубиться в тему – [url=https://kapelnica-ot-zapoya-kolomna15.ru/]капельница от запоя[/url]
MatthewNouff
30 Jul 25 at 5:54 pm
прогноз профессионалов на баскетбол на сегодня [url=http://prognoz-na-segodnya-na-sport10.ru/]http://prognoz-na-segodnya-na-sport10.ru/[/url] .
prognoz na segodnya na sport_wvEn
30 Jul 25 at 5:56 pm
обучение кайтсёрфингу Кайт лагерь: каникулы с адреналином
RamonLiata
30 Jul 25 at 5:57 pm
Hello! I know this is somewhat off topic but I
was wondering if you knew where I could get a captcha plugin for
my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one?
Thanks a lot!
Also visit my page … internet zonder Hongaars adres
internet zonder Hongaars adres
30 Jul 25 at 5:57 pm
Купить диплом о высшем образовании поспособствуем. Купить диплом тренера – [url=http://diplomybox.com/diplom-trenera/]diplomybox.com/diplom-trenera[/url]
Cazrhbv
30 Jul 25 at 6:02 pm
Thanks for the good writeup. It in truth used to be a enjoyment account it. Look complex to more delivered agreeable from you! By the way, how could we keep up a correspondence?
https://www.google.com.tn/url?q=https://seattlelimorates.com/
StephenGlona
30 Jul 25 at 6:02 pm
Наши специалисты используют проверенные медикаменты, которые подбираются индивидуально для каждого пациента:
Углубиться в тему – [url=https://narcolog-na-dom-voronezh0.ru/]выезд нарколога на дом[/url]
ArthurVes
30 Jul 25 at 6:02 pm
обучение кайтсёрфингу “Покупка кайта”: Что нужно знать при покупке кайта
RamonLiata
30 Jul 25 at 6:03 pm
Клиника в Балашихе — Частный Медик 24: стационарный вывод из запоя с комфортом и медицинским сопровождением.
Расширить кругозор по теме – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha13.ru/]срочный вывод из запоя[/url]
DonaldGueni
30 Jul 25 at 6:05 pm
Современные методы лечения при выводе из запоя включают как медикаментозную детоксикацию, так и психологическую реабилитацию. В Уфе наркологи используют капельничное введение лекарственных средств, которые помогают быстро вывести токсины, нормализовать обмен веществ и стабилизировать работу внутренних органов. Одновременно с этим проводится психологическая поддержка для снижения эмоционального стресса, связанного с запоем.
Выяснить больше – https://narcolog-na-dom-ufa0.ru/narkolog-na-dom-czena-ufa
Williamtathy
30 Jul 25 at 6:05 pm