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!
You need to take part in a contest for one of the
highest quality websites on the web. I am going to highly recommend this site!
Learn More Here
23 Oct 25 at 2:44 pm
куплю диплом младшей медсестры [url=http://frei-diplom14.ru]http://frei-diplom14.ru[/url] .
Diplomi_cwoi
23 Oct 25 at 2:49 pm
1xBet промокод на приветственный бонус в 2026 — примените промокод и получите приветственный подарок в размере 100% до 100$. Этот бонусный код даёт возможность получить акционный бонус от БК 1xBet во время регистрации.Промокод 1xBet можно найти на официальной странице — https://belygorod.ru/vote/pgs/?1xbet-promokod.html.
WilliamFaw
23 Oct 25 at 2:49 pm
J’ai une affection pour Impressario Casino, on ressent une ambiance delicate. La selection de jeux est somptueuse, proposant des jeux de table raffines. Amplifiant le plaisir de jeu. Le support client est impeccable, offrant des reponses claires. Les retraits sont fluides comme la Seine, cependant quelques tours gratuits supplementaires seraient bien venus. Pour conclure, Impressario Casino est un incontournable pour les amateurs pour ceux qui aiment parier en crypto ! Ajoutons que la navigation est simple et gracieuse, donne envie de prolonger l’experience. Un plus les paiements securises en crypto, propose des avantages personnalises.
Entrer sur le site|
ToulouseTwistY9zef
23 Oct 25 at 2:50 pm
in hard-to-reach regions, code to her personally happens is limited due to local regulations. registration is available via desktop, page registration in [url=https://home.mile-tech.com/?p=152556]https://home.mile-tech.com/?p=152556[/url] or this application.
Cynthiahunse
23 Oct 25 at 2:50 pm
Je suis ebloui par Monte Cryptos Casino, c’est une plateforme qui pulse comme un reseau blockchain. La selection de jeux est astronomique, offrant des sessions en direct immersives. Avec des depots crypto rapides. Le support client est irreprochable, avec une aide rapide et fiable. Les retraits sont rapides comme une transaction, mais des offres plus genereuses ajouteraient du charme. En resume, Monte Cryptos Casino vaut une exploration virtuelle pour les joueurs en quete d’innovation ! Par ailleurs la plateforme est visuellement eblouissante, facilite une immersion totale. Egalement cool les tournois reguliers pour la competition, renforce la communaute.
Découvrir l’histoire complète|
CryptoPulseW7zef
23 Oct 25 at 2:51 pm
mystylecorner – Highly recommend for anyone who loves trendy urban clothing online.
Haywood Kalina
23 Oct 25 at 2:53 pm
кракен vk2
кракен qr код
JamesDaync
23 Oct 25 at 2:53 pm
скачать ван вин [url=https://www.1win5518.ru]скачать ван вин[/url]
1win_kg_flkl
23 Oct 25 at 2:54 pm
kraken ссылка tor
kraken ссылка
23 Oct 25 at 2:55 pm
https://www.bangladeshnews.net/newsr/15774
codfpdc
23 Oct 25 at 2:55 pm
купить диплом программиста [url=www.rudik-diplom6.ru]купить диплом программиста[/url] .
Diplomi_vyKr
23 Oct 25 at 2:56 pm
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Прочесть всё о… – https://worldcryptoupdate.com/tetraguard-the-financial-safe
DennisRog
23 Oct 25 at 2:57 pm
бонус на спорт 1win [url=https://1win5519.ru/]бонус на спорт 1win[/url]
1win_kg_lwEr
23 Oct 25 at 2:58 pm
рейтинг seo [url=http://reiting-seo-kompaniy.ru/]рейтинг seo[/url] .
reiting seo kompanii_yxon
23 Oct 25 at 2:58 pm
1 xbet giri? [url=https://1xbet-giris-5.com/]1xbet-giris-5.com[/url] .
1xbet giris_vsSa
23 Oct 25 at 2:58 pm
Tipp sportwetten anbieter neu
Tipp sportwetten
23 Oct 25 at 2:59 pm
1xbet resmi sitesi [url=www.1xbet-giris-8.com/]www.1xbet-giris-8.com/[/url] .
1xbet giris_xxPn
23 Oct 25 at 2:59 pm
купить диплом охранника [url=https://rudik-diplom9.ru/]купить диплом охранника[/url] .
Diplomi_ixei
23 Oct 25 at 2:59 pm
seo агентство топ [url=https://reiting-seo-kompaniy.ru]https://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_cion
23 Oct 25 at 3:00 pm
1win app [url=https://www.1win5519.ru]https://www.1win5519.ru[/url]
1win_kg_fiEr
23 Oct 25 at 3:01 pm
Je suis ensorcele par Monte Cryptos Casino, ca transporte dans un univers virtuel. Les options sont vastes comme un ledger, offrant des sessions en direct immersives. Elevant l’experience de jeu. Le suivi est d’une efficacite absolue, toujours pret a decoder. Les transferts sont fiables, neanmoins plus de promos regulieres dynamiseraient l’experience. Dans l’ensemble, Monte Cryptos Casino garantit un plaisir constant pour les adeptes de jeux modernes ! Par ailleurs le site est rapide et futuriste, amplifie le plaisir de jouer. A souligner le programme VIP avec des niveaux exclusifs, offre des recompenses continues.
Ouvrir le site|
NeonHashJ4zef
23 Oct 25 at 3:01 pm
My brother suggested I might like this blog. He was totally
right. This post actually made my day. You can not imagine just how much time I had spent for this information! Thanks!
Also visit my web blog :: детейлинг студия в Москве
детейлинг студия в Москве
23 Oct 25 at 3:03 pm
1xbet giri? 2025 [url=https://1xbet-giris-5.com/]1xbet giri? 2025[/url] .
1xbet giris_nvSa
23 Oct 25 at 3:03 pm
Кроме лавы на поверхность выбрасывается вулканический пепел и бомбы.
казино вулкан казастан
23 Oct 25 at 3:04 pm
1xbet giri? g?ncel [url=https://1xbet-giris-1.com/]1xbet-giris-1.com[/url] .
1xbet giris_lvkt
23 Oct 25 at 3:05 pm
где купить дипломы медсестры [url=https://frei-diplom14.ru/]где купить дипломы медсестры[/url] .
Diplomi_jooi
23 Oct 25 at 3:06 pm
Как купить Гашиш в Долгопрудном?Смотрите, что нашел – https://avartv.ru
. Цены приличные, есть доставка. Кто-то покупал у них? Как у них с надежностью?
Stevenref
23 Oct 25 at 3:07 pm
cryptocurrencynews.pw – The color scheme fits perfectly with the topic, gives a credible vibe.
Rolf Perino
23 Oct 25 at 3:09 pm
https://www.arabherald.com/newsr/15865
ppavxnl
23 Oct 25 at 3:09 pm
Hello, I think your site might be having browser compatibility
issues. When I look at your blog in Safari, it looks fine but when opening in Internet Explorer,
it has some overlapping. I just wanted to give you a quick heads up!
Other then that, wonderful blog!
klebefolie küche arbeitsplatte
23 Oct 25 at 3:09 pm
Список бесплатных предложений и типов бонусов: отдельный обзор промо-акций для новичков и постоянных игроков; в середине абзаца приводим ссылку на промокод при регистрации 1xBet как источник подробной информации о том, куда вводить данные и какие условия ожидать. Также рассказываем про порядок валидации аккаунта.
Petercet
23 Oct 25 at 3:11 pm
I constantly emailed this weblog post page to all my associates, for the reason that if like
to read it after that my links will too.
68win
23 Oct 25 at 3:13 pm
seo agency ranking [url=http://reiting-seo-kompaniy.ru]http://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_gwon
23 Oct 25 at 3:13 pm
1xbet g?ncel giri? [url=1xbet-giris-6.com]1xbet g?ncel giri?[/url] .
1xbet giris_gosl
23 Oct 25 at 3:17 pm
I blog frequently and I truly appreciate your content.
The article has truly peaked my interest. I will bookmark your site and keep checking for new details about
once per week. I opted in for your Feed as well.
SN독학기숙학원
23 Oct 25 at 3:18 pm
J’aime l’aura futuriste de Monte Cryptos Casino, il offre une epopee chiffree. La gamme des titres est eclatante, avec des slots aux designs innovants. Le bonus d’entree est scintillant. Les agents repondent comme un algorithme, garantissant un service de pointe. Les transferts sont fiables, parfois plus de promos dynamiseraient l’aventure. Au final, Monte Cryptos Casino est un must pour les fans de blockchain pour les amateurs de casino en ligne ! Par ailleurs la navigation est simple comme un wallet, ce qui rend chaque session plus immersive. Egalement cool les options de paris variees, qui booste l’engagement.
Essayer tout de suite|
ByteRogueF9zef
23 Oct 25 at 3:18 pm
1win kg [url=https://1win5519.ru/]https://1win5519.ru/[/url]
1win_kg_joEr
23 Oct 25 at 3:19 pm
https://kraken-zone.com market
kraken vk6
23 Oct 25 at 3:20 pm
1 win вход [url=1win5519.ru]1win5519.ru[/url]
1win_kg_pqEr
23 Oct 25 at 3:21 pm
Howdy I am so grateful I found your website, I really found you by accident, while I was looking on Digg for something else, Nonetheless I am
here now and would just like to say thanks a lot for a marvelous post and a all round
thrilling blog (I also love the theme/design),
I don’t have time to go through it all at the minute but I have book-marked it and also added in your RSS feeds, so
when I have time I will be back to read a lot
more, Please do keep up the great job.
memek basah
23 Oct 25 at 3:21 pm
Регистрация в 2026 г. — подробно о бонусам и акциям. Узнайте, как корректно активировать приветственные предложения, а также в середине процесса обратите внимание на https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html как вариант получения дополнительного вознаграждения. Часто задаваемые вопросы помогут быстро разобраться с верификацией и получением бонусов.
Petercet
23 Oct 25 at 3:22 pm
1xbet com giri? [url=www.1xbet-giris-6.com]www.1xbet-giris-6.com[/url] .
1xbet giris_cqsl
23 Oct 25 at 3:23 pm
1xbet guncel [url=http://1xbet-giris-9.com/]1xbet guncel[/url] .
1xbet giris_yuon
23 Oct 25 at 3:23 pm
J’adore l’energie de BassBet Casino, il offre une experience de club. Il y a un flot de jeux captivants, comprenant des jeux adaptes aux cryptos. Amplifiant l’excitation du jeu. L’assistance est rapide et pro, toujours pret a mixer. Les gains arrivent sans attendre, parfois des offres plus genereuses seraient un banger. En resume, BassBet Casino est un must pour les joueurs pour les fans de casino en ligne ! De plus l’interface est fluide comme un mix, ajoute une touche de neon. Particulierement cool les paiements securises en crypto, assure des transactions fiables.
bassbetcasinobonus777fr.com|
NeonRiffG4zef
23 Oct 25 at 3:23 pm
1xbet spor bahislerinin adresi [url=https://1xbet-giris-8.com/]1xbet spor bahislerinin adresi[/url] .
1xbet giris_wrPn
23 Oct 25 at 3:24 pm
1xbet guncel [url=www.1xbet-giris-5.com]1xbet guncel[/url] .
1xbet giris_ymSa
23 Oct 25 at 3:27 pm
Medi Uomo: miglior sito per acquistare Sildenafil online – Viagra generico con pagamento sicuro
RandySkync
23 Oct 25 at 3:28 pm
Где купить Габапентин в Салехарде?Обнаружил сайт https://zagadkigotovki.ru
– адекватные цены и отзывы. Есть доставка. Кто-то уже пользовался их услугами? Интересует качество?
Stevenref
23 Oct 25 at 3:29 pm
Профессионалы своего дела, сопровождение поставок проходит чётко и без лишней бюрократии https://dmebroker.ru/
Brianovalt
23 Oct 25 at 3:30 pm