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=http://gidroizolyaciya-cena-3.ru]http://gidroizolyaciya-cena-3.ru[/url] .
gidroizolyaciya cena_xdSi
13 Aug 25 at 9:34 am
рулонные жалюзи на пульте управления стоимость [url=www.elektricheskie-zhalyuzi.ru]www.elektricheskie-zhalyuzi.ru[/url] .
elektricheskie jaluzi_faki
13 Aug 25 at 9:34 am
В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
Детальнее – https://www.cpaccontracting.com/pf/nancy-rd
MichaelEpipt
13 Aug 25 at 9:34 am
авиатор игра на деньги [url=www.1win1169.ru]www.1win1169.ru[/url]
1win_kg_tspn
13 Aug 25 at 9:35 am
гидроизоляция цена [url=gidroizolyaciya-cena-2.ru]gidroizolyaciya-cena-2.ru[/url] .
gidroizolyaciya cena_yeMr
13 Aug 25 at 9:36 am
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Смотри, что ещё есть – http://www.aacaninecountryclub.com
MauriceEvila
13 Aug 25 at 9:38 am
gorlovkaler.ru
JacobNit
13 Aug 25 at 9:41 am
best india pharmacy: world pharmacy india – Indian Meds One
JamesHeelo
13 Aug 25 at 9:42 am
https://makeevkatop.ru
CharlesVaX
13 Aug 25 at 9:43 am
гидроизоляция цена [url=https://gidroizolyaciya-cena-1.ru/]https://gidroizolyaciya-cena-1.ru/[/url] .
gidroizolyaciya cena_cwmt
13 Aug 25 at 9:44 am
автоматические жалюзи цена [url=https://elektricheskie-zhalyuzi.ru]автоматические жалюзи цена[/url] .
elektricheskie jaluzi_ahki
13 Aug 25 at 9:44 am
гидроизоляция цена [url=https://gidroizolyaciya-cena-3.ru/]gidroizolyaciya-cena-3.ru[/url] .
gidroizolyaciya cena_goSi
13 Aug 25 at 9:44 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Выяснить больше – https://www.kalinlights.co.in/manual-rotating-search-light-udca-mounted-for-fixing-over-watch-towers-roof
Jasonrhini
13 Aug 25 at 9:46 am
Indian Meds One: Indian Meds One – indian pharmacies safe
RoccoaritA
13 Aug 25 at 9:49 am
Mexican Pharmacy Hub [url=https://mexicanpharmacyhub.shop/#]tadalafil mexico pharmacy[/url] Mexican Pharmacy Hub
Houstonfloma
13 Aug 25 at 9:50 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Не пропусти важное – https://estrellasbakeryus.com/product/caracol
Alvinbounk
13 Aug 25 at 9:50 am
гидроизоляция цена [url=https://gidroizolyaciya-cena-2.ru]https://gidroizolyaciya-cena-2.ru[/url] .
gidroizolyaciya cena_lhMr
13 Aug 25 at 9:50 am
I every time spent my half an hour to read this
web site’s posts all the time along with a cup of coffee.
Yupoo Fendi
13 Aug 25 at 9:54 am
This is my first time go to see at here and
i am really happy to read all at single place.
Paito Hongkong
13 Aug 25 at 9:54 am
MediDirect USA: pharmacy online usa – MediDirect USA
RoccoaritA
13 Aug 25 at 9:55 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Детальнее – https://defartv.com/nurturing-the-bond-between-humans-and-nature
JesseBeaug
13 Aug 25 at 9:56 am
Прокат авто Краснодар на месяц
MarvinJak
13 Aug 25 at 9:59 am
гидроизоляция цена [url=https://www.gidroizolyaciya-cena-2.ru]https://www.gidroizolyaciya-cena-2.ru[/url] .
gidroizolyaciya cena_vxMr
13 Aug 25 at 10:00 am
Mexican Pharmacy Hub: Mexican Pharmacy Hub – cheap cialis mexico
RoccoaritA
13 Aug 25 at 10:02 am
В «ВладЗдоровье» применяется комплексный подход, сочетающий медикаментозное лечение, психотерапию и реабилитацию. Врач-нарколог подбирает препараты индивидуально, с учётом анамнеза, переносимости компонентов и текущего состояния организма. Психотерапевтический блок включает когнитивно-поведенческую терапию, мотивационные интервью, семейную терапию и работу с посттравматическими реакциями.
Разобраться лучше – [url=https://narkologicheskaya-pomoshh-vladimir0.ru/]срочная наркологическая помощь в владимире[/url]
FloydAbary
13 Aug 25 at 10:02 am
aplicația 1win [url=https://1win40014.ru/]https://1win40014.ru/[/url]
1win_md_lxpr
13 Aug 25 at 10:02 am
https://dokuchaevskul.ru
CharlesVaX
13 Aug 25 at 10:04 am
https://sqrgloballogistics.com.my/2025/07/18/stpka-v-verde-casino-50-free-spins-sschnostta-na-prijatno-i-nadezhdno-izzhivjavane-za-zalaganija/
Robertpef
13 Aug 25 at 10:10 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Провести детальное исследование – https://d2ride.com/hello-world
Josephsib
13 Aug 25 at 10:12 am
Have you ever thought about creating an e-book or guest authoring
on other websites? I have a blog based upon on the same subjects you discuss and would really like to
have you share some stories/information. I know my subscribers would enjoy your
work. If you are even remotely interested, feel free to shoot me an email.
Order MDMA online in bulk,
13 Aug 25 at 10:12 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Более подробно об этом – https://espigaoalerta.com.br/2023/05/14/agencia-minas-gerais-liminar-obtida-pela-age-mg-evita-risco-de-o-estado-perder-cerca-de-r-20-milhoes
Waltersop
13 Aug 25 at 10:14 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Практические советы ждут тебя – https://physiomentor.co/functional-sequence-of-balance-training-exercises
Jasonrhini
13 Aug 25 at 10:16 am
yasinovatayate.ru
JacobNit
13 Aug 25 at 10:16 am
Hi, Neat post. There is an issue together with your web site
in web explorer, would check this? IE still is the market chief and
a good component of other folks will pass over
your great writing because of this problem.
Visit here
13 Aug 25 at 10:18 am
Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
Обратитесь за информацией – https://dach-wand-langenau.de/hello-world
Bobbykig
13 Aug 25 at 10:19 am
перлит
Michaelcoomy
13 Aug 25 at 10:20 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Погрузиться в детали – http://kominki-stanpol.pl/jak-powstaje-pellet
Alvinbounk
13 Aug 25 at 10:24 am
https://antracitfel.ru
CharlesVaX
13 Aug 25 at 10:24 am
저희는 사이트 기술 진단부터 키워드 분석,
콘텐츠 최적화, 내부 링크 구조 개선 및 백링크 구축까지 종합적인
SEO 솔루션을 제공합니다.
구글상위노출
13 Aug 25 at 10:25 am
Эта статья предлагает живое освещение актуальной темы с множеством интересных фактов. Мы рассмотрим ключевые моменты, которые делают данную тему важной и актуальной. Подготовьтесь к насыщенному путешествию по неизвестным аспектам и узнайте больше о значимых событиях.
Продолжить изучение – https://tentazionidisicilia.it/prodotto/bacetti-piccanti-peperoncini-rossi-ripieni
MichaelEpipt
13 Aug 25 at 10:32 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Почему это важно? – https://heartb.foundation/infopost/no-covid-19-precautions-are-being-taken-on-gas-stations
JoshuaVat
13 Aug 25 at 10:34 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Полная информация здесь – https://ryananddenise.com/amanda-and-jordan-the-farm-at-agritopia-engagement-session
BrianStymn
13 Aug 25 at 10:37 am
Hi there, i read your blog occasionally and i own a
similar one and i was just curious if you get a lot of spam feedback?
If so how do you prevent it, any plugin or anything you can suggest?
I get so much lately it’s driving me crazy so any assistance is very much appreciated.
m98.pages.dev
13 Aug 25 at 10:40 am
вывод из запоя круглосуточно минск
vivod-iz-zapoya-minsk004.ru
лечение запоя
vivodminskNeT
13 Aug 25 at 10:43 am
1win скачать на ios [url=http://1win40014.ru/]http://1win40014.ru/[/url]
1win_md_czpr
13 Aug 25 at 10:43 am
https://gorlovkarel.ru
CharlesVaX
13 Aug 25 at 10:44 am
драгон мани официальный сайт
KevinDreta
13 Aug 25 at 10:46 am
Fantastic beat ! I wish to apprentice whilst you amend your
site, how can i subscribe for a blog web site? The account helped
me a appropriate deal. I had been tiny bit familiar of this your broadcast offered vivid transparent concept
nagasaon sgp sabtu
13 Aug 25 at 10:47 am
I have fun with, cause I found just what I was having a
look for. You have ended my 4 day lengthy hunt!
God Bless you man. Have a nice day. Bye
data keluaran hk dan tanggalnya
13 Aug 25 at 10:48 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Секреты успеха внутри – http://www.photodim.ru/index.php?values
JesseBeaug
13 Aug 25 at 10:50 am