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!
как купить аттестат за 11 класс сколько стоит [url=www.arus-diplom22.ru/]как купить аттестат за 11 класс сколько стоит[/url] .
Diplomi_jqsl
30 Aug 25 at 2:34 pm
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-665
30 Aug 25 at 2:37 pm
Luxury1288
Luxury1288
30 Aug 25 at 2:37 pm
Attractive element of content. I simply stumbled upon your web site and in accession capital to assert that I get
in fact enjoyed account your blog posts. Any way I will be subscribing on your feeds and even I achievement
you get admission to constantly rapidly.
Quantum Bextra
30 Aug 25 at 2:40 pm
Low price of wellbutrin sr vs xl , will my partner have any negative feelings? bupropion 150mg xl
ErcsFlulk
30 Aug 25 at 2:40 pm
купить диплом с реестром вуза [url=www.arus-diplom33.ru]купить диплом с реестром вуза[/url] .
Bistro i prosto kypit diplom ob obrazovanii!_tcoi
30 Aug 25 at 2:43 pm
Wealth Ancestry Prayer sounds really inspiring. I like how it connects the idea of financial abundance with spiritual grounding and ancestral blessings.
It feels more meaningful than just focusing on money—it’s about aligning with
positive energy and guidance for lasting prosperity
Wealth Ancestry Prayer
30 Aug 25 at 2:47 pm
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
JamesCic
30 Aug 25 at 2:49 pm
Hey there would you mind stating which blog platform you’re working
with? I’m looking to start my own blog in the near future
but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your layout 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 Aug 25 at 2:53 pm
купить аттестат за 11 класс в челябинске [url=https://arus-diplom22.ru]купить аттестат за 11 класс в челябинске[/url] .
Diplomi_ogsl
30 Aug 25 at 2:55 pm
Казино 1xslots
RichardKap
30 Aug 25 at 3:01 pm
Luxury1288
Luxury1288
30 Aug 25 at 3:01 pm
реально ли купить аттестат за 11 класс [url=http://arus-diplom23.ru]http://arus-diplom23.ru[/url] .
Diplomi_zeSr
30 Aug 25 at 3:02 pm
Hi there, I enjoy reading through your article post. I like to write a little comment to
support you.
FinoTraze
30 Aug 25 at 3:03 pm
Usually I don’t read article on blogs, but I would like to say that this write-up very compelled
me to try and do it! Your writing taste has been surprised
me. Thank you, very great post.
http://w5.angkakeluaran.top/
Data Sdy
30 Aug 25 at 3:06 pm
В Красноярске доступно множество услуг для лечение алкоголизма. Наркологические клиники обеспечивают медицинскую помощь, которая включает очистку организма и лечение в стационаре. Опытные наркологи осуществляют кодирование, а также предоставляют психологическую поддержку и реабилитацию. Необходимо помнить о важности консультаций для близких, чтобы обеспечить поддержку семьи; Анонимное лечение гарантирует защиту личной информации, а реабилитационные программы содействуют зависимым вернуться к нормальной жизни. Получите дополнительную информацию на сайте vivod-iz-zapoya-krasnoyarsk012.ru.
vivodkrasnoyarskNeT
30 Aug 25 at 3:10 pm
The Pineal Guardian sounds really interesting, especially with how it’s designed to support pineal gland health and overall well-being.
I like that it focuses on natural ingredients instead of synthetic solutions.
Definitely worth looking into if you’re curious about
better sleep, focus, and mental clarity.
The Pineal Guardian
30 Aug 25 at 3:11 pm
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
JamesCic
30 Aug 25 at 3:11 pm
If some one wishes to be updated with hottest technologies then he must be
pay a quick visit this site and be up to date all the time.
microsoft office activation macbook
30 Aug 25 at 3:14 pm
Близкий человек в запое? Не ждите ухудшения. Обратитесь в клинику — здесь проведут профессиональный вывод из запоя с последующим восстановлением организма.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-v-stacionare-samara14.ru/]вывод из запоя цена в самаре[/url]
Michaelplert
30 Aug 25 at 3:16 pm
Капельница от похмелья на дому: действующее лечение и восстановление организма
narkologiyatulaNeT
30 Aug 25 at 3:18 pm
Организация помощи нарколога на дому в Твери построена по строгому алгоритму, который включает несколько ключевых этапов. Такой комплексный подход позволяет не только быстро вывести токсичные вещества, но и обеспечить всестороннюю поддержку для скорейшего восстановления организма.
Узнать больше – [url=https://reabcentr-narko.ru/]вывод из запоя круглосуточно в твери[/url]
MichaelSmurn
30 Aug 25 at 3:19 pm
купить аттестат за 11 классов в новосибирске [url=http://arus-diplom22.ru/]http://arus-diplom22.ru/[/url] .
Diplomi_uysl
30 Aug 25 at 3:19 pm
Howdy! Do you know if they make any plugins to assist with
SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.
If you know of any please share. Thanks!
buy
30 Aug 25 at 3:26 pm
Luxury1288
Luxury1288
30 Aug 25 at 3:26 pm
Казино Pinco слот Admiral X Fruit Machine
Jorgegrect
30 Aug 25 at 3:27 pm
Hey! I just wanted to ask if you ever have any issues with hackers?
My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no backup.
Do you have any methods to stop hackers?
토닥이
30 Aug 25 at 3:28 pm
Этот формат позволяет пациентам получить профессиональную помощь в комфортной домашней обстановке. Такой подход не только обеспечивает удобство, но и гарантирует конфиденциальность, что особенно важно для многих людей.
Получить дополнительную информацию – [url=https://narcolog-na-dom-v-krasnoyarske55.ru/]врач нарколог на дом красноярск[/url]
CurtisUsalk
30 Aug 25 at 3:32 pm
Купить кокаин, мефедрон, гашиш, бошки, альфа-пвп
JamesCic
30 Aug 25 at 3:34 pm
сколько стоит купить диплом в киеве [url=www.educ-ua2.ru/]сколько стоит купить диплом в киеве[/url] .
Diplomi_mxOt
30 Aug 25 at 3:39 pm
I am regular visitor, how are you everybody? This paragraph posted at this web page is
actually pleasant.
kamboja lotto
30 Aug 25 at 3:39 pm
где купить аттестат 11 классов в нижнем новгороде [url=https://arus-diplom22.ru/]где купить аттестат 11 классов в нижнем новгороде[/url] .
Diplomi_sssl
30 Aug 25 at 3:40 pm
For newest information you have to pay a visit world wide web
and on the web I found this web site as a most excellent web
site for newest updates.
https://photovoltaik.b-cdn.net/die-ultimative-anleitung-zur-installation-von-photovoltaik-in-buchloe.html
30 Aug 25 at 3:41 pm
It’s an awesome paragraph for all the web viewers; they will take advantage from it I am sure.
login loket88
30 Aug 25 at 3:43 pm
???? 888starz ????? ????? ?? ????? ?? ???? ???????? . ????? ????????? ?????? ????????? ?? 888starz.
??? ????? 888starz ??????? ????? ?????? ??? ???? ???????. ???? 888starz ?????? ????? ?? ???????? ??? ?? ??? ??????? ?????????? ???????? .
????? 888starz ??????? ?????? ?????????? . ??? ??????? ?? ?????? ???????? ????? ????? .
??????? ???????? ????? ?? ???? ??????? ????? ??? ???????? . ????? ??? ???????? ?????? ????? ???????? ??? ???? 888starz .
п»ї888starz [url=https://888starz-africa.pro]https://888starz-africa.pro/[/url]
888starz_tgol
30 Aug 25 at 3:44 pm
диплом купить с занесением в реестр [url=http://arus-diplom33.ru/]диплом купить с занесением в реестр[/url] .
Kypit diplom ob obrazovanii!_igoi
30 Aug 25 at 3:46 pm
купить аттестат 11 цены дипломы челябинск ком [url=https://arus-diplom22.ru]https://arus-diplom22.ru[/url] .
Diplomi_vgsl
30 Aug 25 at 3:47 pm
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Самаре приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara17.ru/]вывод из запоя цена в самаре[/url]
Justingof
30 Aug 25 at 3:48 pm
It’s difficult to find experienced people for
this topic, but you seem like you know what you’re talking about!
Thanks
Bigcrypt Edge
30 Aug 25 at 3:53 pm
купить диплом об образовании в запорожье [url=educ-ua1.ru]купить диплом об образовании в запорожье[/url] .
Diplomi_juei
30 Aug 25 at 3:53 pm
https://baskadia.com/user/fypb
DouglasBem
30 Aug 25 at 3:56 pm
Существуют различные методы и стратегии, которые применяются для устранения зависимостей. Каждый случай уникален, поэтому важно проводить глубокую диагностику и индивидуально разрабатывать план лечения. Мы понимаем, что борьба с зависимостью — это длительный процесс, требующий как медицинской, так и психологической поддержки.
Подробнее можно узнать тут – [url=https://zavisim-alko.ru/]вывод из запоя на дому недорого в краснодаре[/url]
KennethGlolo
30 Aug 25 at 3:57 pm
Use spacers to leave a jaycitynews.com small gap (8 to 12 mm) between the wall and the laminate – this will allow the coating to “breathe” and prevent it from being damaged by changes in temperature and humidity.
DewayneCreal
30 Aug 25 at 4:06 pm
SaveTweet suporta uma ampla variedade de formatos de vídeo, incluindo MP4,
AVI e MOV, dando a você a liberdade de escolher o formato que melhor atende
às suas necessidades.
Ssstwitter extension
30 Aug 25 at 4:14 pm
kraken онион тор
RichardPep
30 Aug 25 at 4:15 pm
https://bonus1xbet.hashnode.dev/code-promotionnel-1xbet-bonus-jusqua-130
JustinRaP
30 Aug 25 at 4:18 pm
купить аттестат за 11 класс в уральске [url=https://arus-diplom22.ru/]https://arus-diplom22.ru/[/url] .
Diplomi_rtsl
30 Aug 25 at 4:18 pm
https://form.jotform.com/252402220880042
DouglasBem
30 Aug 25 at 4:19 pm
сколько стоит купить аттестат за 9 класс [url=www.educ-ua2.ru/]www.educ-ua2.ru/[/url] .
Diplomi_lpOt
30 Aug 25 at 4:19 pm
диплом проведенный купить [url=https://arus-diplom33.ru]диплом проведенный купить[/url] .
Bistro zakazat diplom ob obrazovanii!_jxoi
30 Aug 25 at 4:20 pm