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!
I’m not sure why but this weblog is loading extremely slow for me.
Is anyone else having this problem or is it a problem on my end?
I’ll check back later on and see if the problem still exists.
123win
12 Sep 25 at 8:28 pm
1xbet авиатор [url=https://aviator-igra-4.ru]1xbet авиатор[/url] .
aviator igra_ecpr
12 Sep 25 at 8:29 pm
https://www.effectiveratecpm.com/cdf10j95?key=9d84a2498fb6af60cb82f0df204577f6/2025/08/11/codice-promozionale-verde-casino-la-tua-destinazione-finale-per-il-casino-e-leccellenza-delle-scommesse/
JeffreyThota
12 Sep 25 at 8:31 pm
Joint Genesis looks like a great option for anyone struggling with
stiff or achy joints. I like that it’s formulated to support cartilage health
and improve mobility instead of just masking the discomfort.
If it really helps reduce inflammation and restore flexibility,
it could be a game-changer for people who want to stay active and
maintain strong joint health as they age.
Joint Genesis
12 Sep 25 at 8:32 pm
купить диплом о высшем образовании в украине [url=www.educ-ua2.ru]купить диплом о высшем образовании в украине[/url] .
Diplomi_bnOt
12 Sep 25 at 8:32 pm
заказать перепланировку квартиры [url=https://www.proekt-pereplanirovki-kvartiry9.ru]заказать перепланировку квартиры[/url] .
proekt pereplanirovki kvartiri_nxpa
12 Sep 25 at 8:32 pm
Medicines information. Short-Term Effects.
how to buy cheap allegra without dr prescription
All trends of medicine. Read here.
how to buy cheap allegra without dr prescription
12 Sep 25 at 8:33 pm
1win crash [url=https://www.aviator-igra-4.ru]https://www.aviator-igra-4.ru[/url] .
aviator igra_vxpr
12 Sep 25 at 8:34 pm
где сделать проект перепланировки квартирым [url=http://proekt-pereplanirovki-kvartiry9.ru/]http://proekt-pereplanirovki-kvartiry9.ru/[/url] .
proekt pereplanirovki kvartiri_yxpa
12 Sep 25 at 8:36 pm
купить диплом занесенный реестр [url=https://russian-trader.com/threads/77489]купить диплом занесенный реестр[/url] .
Zakazat diplom o visshem obrazovanii!_kwkt
12 Sep 25 at 8:37 pm
купить диплом о высшем образовании бакалавр [url=http://educ-ua17.ru/]купить диплом о высшем образовании бакалавр[/url] .
Diplomi_lgSl
12 Sep 25 at 8:37 pm
проект после перепланировки [url=http://proekt-pereplanirovki-kvartiry9.ru/]http://proekt-pereplanirovki-kvartiry9.ru/[/url] .
proekt pereplanirovki kvartiri_rppa
12 Sep 25 at 8:40 pm
https://4nb.19e.myftpupload.com/2025/08/11/app-verde-casino-la-tua-destinazione-principale-per-casino-e-qualita-delle-scommesse/
JeffreyThota
12 Sep 25 at 8:41 pm
Drug information for patients. Short-Term Effects.
prilosec famotidine together
All news about medicament. Get here.
prilosec famotidine together
12 Sep 25 at 8:43 pm
If you wish for to take a great deal from this article then you have to
apply these methods to your won website.
Yupoo Celine
12 Sep 25 at 8:43 pm
aviator gioco [url=https://www.aviator-igra-4.ru]https://www.aviator-igra-4.ru[/url] .
aviator igra_fnpr
12 Sep 25 at 8:44 pm
мостбет вход регистрация [url=http://mostbet12003.ru]http://mostbet12003.ru[/url]
mostbet_wret
12 Sep 25 at 8:45 pm
https://nutrianajuribeiro.com.br/2025/08/25/verde-casino-app-la-tua-destinazione-principale-per-il-casino-e-la-qualita-delle-scommesse/
JeffreyThota
12 Sep 25 at 8:47 pm
СЏ РѕС‚ данного сэллера так ничего Рё РЅРµ получил. заказывал 6 февраля, месяц тянул продаван резину, Р° РІ марте выслал повторно , РЅРѕ посылку арестовали еще РІ РјРѕСЃРєРІРµ, итог:РіСЂСѓР·Р° нет, денег нет. мотайте РЅР° СѓСЃ, СЏ СЃ такими БАРЫГАМРдел иметь РЅРµ хочу…
https://form.jotform.com/252487979162069
товар 9\10 хорошее качество, 9 потому что ожидал чуть большего.
Davidabrar
12 Sep 25 at 8:49 pm
aviator money [url=http://www.aviator-igra-4.ru]http://www.aviator-igra-4.ru[/url] .
aviator igra_cupr
12 Sep 25 at 8:51 pm
купить диплом магистра [url=https://educ-ua2.ru/]купить диплом магистра[/url] .
Diplomi_sxOt
12 Sep 25 at 8:53 pm
There is definately a lot to know about this subject.
I love all the points you’ve made.
сервисные центры candy в москве
12 Sep 25 at 8:55 pm
aviator игра 1win [url=http://aviator-igra-4.ru/]aviator игра 1win[/url] .
aviator igra_jtpr
12 Sep 25 at 8:55 pm
https://teatherapy.in/verde-casino-la-tua-destinazione-principale-per-la-perfezione-da-casino-e-scommesse/
JeffreyThota
12 Sep 25 at 8:57 pm
игра авиатор в 1xbet [url=aviator-igra-4.ru]игра авиатор в 1xbet[/url] .
aviator igra_okpr
12 Sep 25 at 9:00 pm
Услуга “Нарколог на дом” в Мариуполе, Донецкая область, предусматривает оперативное оказание медицинской помощи при запое. После получения вызова специалист незамедлительно выезжает к пациенту, проводит детальный осмотр, измеряет жизненно важные показатели и собирает анамнез. На основе полученных данных разрабатывается индивидуальный план терапии, включающий медикаментозную детоксикацию, инфузионную терапию и психологическую поддержку. Такой комплексный подход позволяет эффективно вывести токсины из организма и предотвратить развитие осложнений.
Исследовать вопрос подробнее – http://narcolog-na-dom-mariupol00.ru/narkolog-na-dom-czena-mariupol/
Shawnram
12 Sep 25 at 9:03 pm
This text is invaluable. When can I find out more?
google blog
12 Sep 25 at 9:04 pm
Wonderful goods from you, man. I’ve understand your stuff previous
to and you’re just extremely wonderful. I really like what you’ve acquired here, certainly
like what you are stating and the way in which you
say it. You make it entertaining and you still care
for to keep it sensible. I can not wait to read much more from you.
This is actually a great website.
best bitcoin gambling sites
12 Sep 25 at 9:06 pm
купить проведенный диплом спб [url=https://www.astrotime.ru/forum/ac-pro-file.php?mode=viewprofile&u=54749]купить проведенный диплом спб[/url] .
Zakazat diplom ob obrazovanii!_gokt
12 Sep 25 at 9:06 pm
как отыграть бонус 1win [url=https://1win12008.ru]https://1win12008.ru[/url]
1win_nnsn
12 Sep 25 at 9:07 pm
I think the admin of this site is really working hard for his
website, because here every material is quality based material.
Quite a few insightful
12 Sep 25 at 9:07 pm
Every weekend i used to pay a quick visit this site, for the reason that i want enjoyment,
aas this this web site conations actually fastidious funny information too.
Best Vapor
12 Sep 25 at 9:10 pm
I like the valuable info you provide in your articles.
I will bookmark your blog and check again here regularly.
I am quite sure I’ll learn many new stuff right here!
Best of luck for the next!
en-suite rooms
12 Sep 25 at 9:11 pm
Лечение начинается с короткой оценки рисков и выбора безопасной точки старта. Далее следуют этапы стабилизации, настройки сна и тревоги, поведенческие инструменты и план антирецидивной поддержки. Ниже — ориентировочная карта: в реальности длительности и интенсивность подбираются индивидуально, а переход между форматами происходит без «обнуления» обследований.
Получить больше информации – [url=https://narkologicheskaya-klinika-v-spb14.ru/]лечение в наркологической клинике[/url]
Anthonygom
12 Sep 25 at 9:11 pm
My brother recommended I might like this website. He used to
be entirely right. This publish actually made my
day. You can not imagine simply how so much time I had spent for this info!
Thank you!
OkoraVisitPro
12 Sep 25 at 9:12 pm
Sweet blog! I found it while browsing on Yahoo News.
Do you have any suggestions on how to get listed in Yahoo
News? I’ve been trying for a while but I never seem to get there!
Appreciate it
toto slot
12 Sep 25 at 9:12 pm
Woah! I’m really digging the template/theme of this blog.
It’s simple, yet effective. A lot of times it’s very difficult to get
that “perfect balance” between user friendliness and visual appearance.
I must say that you’ve done a very good job with this.
In addition, the blog loads super quick for me on Opera.
Superb Blog!
state disclosures
12 Sep 25 at 9:13 pm
оплачивай лучше через киви.самый лучший способ во всех магазах.и перевод идёт в секунду.только обрати внимание на комисию чтоб небыло недоплаты.обычно 2% от суммы перевода
https://www.divephotoguide.com/user/jauufugidtda
С Новым Годом всех поздравляю,очень рад сотрудничеству с данным магазином,желаю только хорошего!
Davidabrar
12 Sep 25 at 9:13 pm
купить диплом в сумах [url=educ-ua2.ru]educ-ua2.ru[/url] .
Diplomi_ihOt
12 Sep 25 at 9:15 pm
Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m undoubtedly enjoying your blog and look forward to new posts.
lee bet регистрация
StephenGlona
12 Sep 25 at 9:15 pm
купить аттестат 9 класс с реестром [url=educ-ua2.ru]educ-ua2.ru[/url] .
Diplomi_nzOt
12 Sep 25 at 9:21 pm
https://dev-braided-gamer.pantheonsite.io/2025/08/04/fii-ca-acas-la-verde-casino-free-spins-retragerea/
JeffreyThota
12 Sep 25 at 9:22 pm
https://dev-conceptservices.pantheonsite.io/prezentarea-verde-casino-no-deposit-bonus-hotspot/
JeffreyThota
12 Sep 25 at 9:28 pm
https://www.youtube.com/@candetoxblend/about
Afrontar un test preocupacional ya no tiene que ser una incertidumbre. Existe un suplemento de última generación que responde en horas.
El secreto está en su combinación, que estimula el cuerpo con nutrientes esenciales, provocando que la orina oculte los rastros químicos. Esto asegura parámetros adecuados en solo 2 horas, con ventana segura para rendir tu test.
Lo mejor: no se requieren procesos eternos, diseñado para trabajadores en evaluaciones.
Miles de clientes confirman su efectividad. Los envíos son 100% discretos, lo que refuerza la tranquilidad.
Si no quieres dejar nada al azar, esta alternativa es la respuesta que estabas buscando.
JuniorShido
12 Sep 25 at 9:28 pm
https://emilioipae656.timeforchangecounselling.com/state
Superar una prueba de orina puede ser complicado. Por eso, existe una alternativa confiable desarrollada en Canada.
Su composicion eficaz combina minerales, lo que ajusta tu organismo y disimula temporalmente los metabolitos de alcaloides. El resultado: un analisis equilibrado, lista para cumplir el objetivo.
Lo mas destacado es su accion rapida en menos de 2 horas. A diferencia de metodos caseros, no promete resultados permanentes, sino una herramienta puntual que funciona cuando lo necesitas.
Miles de personas en Chile ya han comprobado su efectividad. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si no deseas dejar nada al azar, esta formula te ofrece confianza.
JuniorShido
12 Sep 25 at 9:30 pm
Greetings! I just came across this fantastic article on virtual
gambling and simply resist the chance to share it.
If you’re someone who’s looking to explore more about the world of online casinos,
this article is absolutely.
I have always been fascinated in online gaming,
and after reading this, I gained so much about the various types of
casino games.
The article does a wonderful job of explaining everything
from game strategies. If you’re new to the whole scene, or even if
you’ve been gambling for years, this article is
an essential read. I highly recommend it
for anyone who needs to get informed with online gambling options.
Not only, the article covers some great advice about selecting a safe online casino, which I think
is extremely important. So many people overlook
this aspect, but this post clearly shows you the best ways to stay safe.
What I liked most was the section on how bonuses work in casinos, which I think is
crucial when choosing a site to play on. The insights here are priceless for anyone looking to
make the most out of every bet.
In addition, the strategies about limiting your losses were
very useful. The advice is clear and actionable, making it easy for players
to take control of their gambling habits and avoid pitfalls.
The advantages and disadvantages of online gambling were also thoroughly discussed.
If you’re thinking about trying your luck at an online casino, this article
is a great starting point to understand both the
excitement and the risks involved.
If you’re into blackjack, you’ll find tons
of valuable tips here. They really covers all the popular
games in detail, giving you the tools you need to boost
your skill level. Whether you’re into competitive games like poker or just enjoy a casual round of slots,
this article has something for everyone.
I personally appreciated the discussion about online casino
security. It’s crucial to know that you’re using a platform that’s safe and secure.
This article really helps you make sure your personal information is in good hands
when you play online.
In case you’re wondering where to start, I highly recommend reading this guide.
It’s clear, informative, and packed with valuable insights.
Without a doubt, one of the best articles I’ve come across in a while on this topic.
If you haven’t yet, I strongly suggest checking
it out and seeing for yourself. You won’t regret it! Trust me,
you’ll finish reading feeling like a more informed player in the online casino
world.
If you’re an experienced gambler, this post is an excellent resource.
It helps you avoid common mistakes and teaches you how to maximize your experience.
Definitely worth checking out!
I really liked how well-researched and thorough this article is.
I’ll definitely be coming back to it whenever I need tips
on casino games.
Has anyone else read it yet? What do you think?
Feel free to share!
url
12 Sep 25 at 9:32 pm
https://kingstechconsulting.com/va-prezentam-verde-casino-registration-bonus-cea-mai-buna-escapada-la-jocurile-de-noroc-digitale/
JeffreyThota
12 Sep 25 at 9:33 pm
Chemical-mix.com, а где от 50гр, там надо 40 тон сразу запулить:rastakur: яж не барон нах:LSD:
https://www.betterplace.org/en/organisations/68400
как дела друзья?
Davidabrar
12 Sep 25 at 9:37 pm
Helllo there! Thiis iss my first comment here
so I just wanted to give a quick shout out and tell you I genuinely enjoy reading yourr posts.
Can you recommend any other blogs/websites/forums that cover the same
topics? Thank you so much!
Look at my web-site; сервисный центр candy в москве
сервисный центр candy в москве
12 Sep 25 at 9:39 pm
1 win зеркало [url=http://1win12006.ru/]http://1win12006.ru/[/url]
1win_hdkn
12 Sep 25 at 9:40 pm