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!
Ich bin suchtig nach Lowen Play Casino, es verstromt eine Spielstimmung, die wie eine Savanne tobt. Die Casino-Optionen sind vielfaltig und kraftvoll, mit einzigartigen Casino-Slotmaschinen. Die Casino-Mitarbeiter sind schnell wie ein Gepard, ist per Chat oder E-Mail erreichbar. Auszahlungen im Casino sind schnell wie ein Raubkatzen-Sprint, trotzdem mehr regelma?ige Casino-Boni waren ein Volltreffer. Kurz gesagt ist Lowen Play Casino ein Casino, das man nicht verpassen darf fur Fans moderner Casino-Slots! Zusatzlich die Casino-Oberflache ist flussig und strahlt wie ein Sonnenaufgang, was jede Casino-Session noch wilder macht.
lГ¶wen play meppen Г¶ffnungszeiten|
zappysquirrel3zef
21 Oct 25 at 9:13 pm
Где купить Лирику в Жукове?Смотрите, что нашел – сайт https://myturtime.ru
. Цены приличные, есть доставка. Может, кто-то тестил у них? Как с качеством?
Stevenref
21 Oct 25 at 9:15 pm
агентство seo [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]агентство seo[/url] .
agentstvo poiskovogo prodvijeniya_lcKt
21 Oct 25 at 9:17 pm
продвижение сайтов топ агентство [url=www.seo-prodvizhenie-reiting.ru/]www.seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_qeEa
21 Oct 25 at 9:17 pm
cloudfiles.tech – The site has a sleek, modern layout and the navigation is intuitive and smooth.
Ali Brisbone
21 Oct 25 at 9:17 pm
сео продвижение москва [url=www.seo-prodvizhenie-reiting-kompanij.ru/]сео продвижение москва[/url] .
seo prodvijenie reiting kompanii_onst
21 Oct 25 at 9:17 pm
как купить легальный диплом [url=https://www.frei-diplom2.ru]https://www.frei-diplom2.ru[/url] .
Diplomi_uyEa
21 Oct 25 at 9:17 pm
shop-in.tech – Just visited the website, the layout is clean and browsing was quite smooth.
Marge Hauswald
21 Oct 25 at 9:18 pm
buildyourdreambrand – Loved the examples of branding projects—they made things much more tangible.
Robbin Rochell
21 Oct 25 at 9:18 pm
Клиника «Детокс» в Сочи предлагает услугу вывода из запоя в стационаре. Под наблюдением профессиональных врачей пациент получит необходимую медицинскую помощь и поддержку. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-sochi22.ru/]наркология вывод из запоя сочи[/url]
MichaelMak
21 Oct 25 at 9:18 pm
Мы обеспечиваем быстрое и безопасное восстановление после длительного употребления алкоголя.
Получить дополнительную информацию – http://vyvod-iz-zapoya-nizhnij-novgorod13.ru
StevenLat
21 Oct 25 at 9:20 pm
Hello my friend! I want to say that this post is awesome,
nice written and come with approximately all vital infos.
I would like to look extra posts like this .
AYUTOGEL
21 Oct 25 at 9:21 pm
промокод 1xBet все актуальные акции и бонусы собраны на одной странице
Aaronawads
21 Oct 25 at 9:22 pm
seo москва [url=http://www.reiting-seo-agentstv-moskvy.ru]seo москва[/url] .
reiting seo agentstv moskvi_peMl
21 Oct 25 at 9:23 pm
топ seo продвижение низкие цены [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/[/url] .
agentstvo poiskovogo prodvijeniya_mjKt
21 Oct 25 at 9:23 pm
Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
minotaurus token
WilliamPargy
21 Oct 25 at 9:25 pm
диджитал агентства москвы [url=www.luchshie-digital-agencstva.ru]диджитал агентства москвы[/url] .
lychshie digital agentstva_ggoi
21 Oct 25 at 9:26 pm
сео оптимизация заказать [url=https://reiting-runeta-seo.ru/]сео оптимизация заказать[/url] .
reiting ryneta seo_lrma
21 Oct 25 at 9:27 pm
Sildenafil side effects and safe dosage: Blue Peak Meds – how generic Viagra works in the body
AnthonySep
21 Oct 25 at 9:27 pm
seo agents [url=https://reiting-seo-kompanii.ru/]seo agents[/url] .
reiting seo kompanii_ctsn
21 Oct 25 at 9:29 pm
рейтинг компаний по продвижению сайтов [url=www.luchshie-digital-agencstva.ru/]рейтинг компаний по продвижению сайтов[/url] .
lychshie digital agentstva_dboi
21 Oct 25 at 9:29 pm
medtronik.ru подборка бонусов и акций для новых пользователей
Aaronawads
21 Oct 25 at 9:30 pm
https://medivertraut.shop/# Viagra Generika online kaufen ohne Rezept
LanceHek
21 Oct 25 at 9:30 pm
лучший seo продвижение [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_rlsa
21 Oct 25 at 9:31 pm
russian seo [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_fxsa
21 Oct 25 at 9:33 pm
Промокод 1xBet на сегодня актуален, бонус будет зачислен сразу после первого пополнения счета. Временные коды. Букмекерская контора 1xBet часто выступает спонсором при переводе популярных сериалов на русский язык. Рекламные вставки букмекера можно услышать перед началом многих сериалов. Часто в такой рекламе диктуется специальные промокод, дающий возможность беттерам рассчитывать на дополнительный бонус. Максимальный бонус при регистрации составляется 32500 рублей. Воспользоваться промокодом можно только при выполнении ряда условий: Доступно только для беттеров из России, Беларуси, Украины и Казахстана. Возврат игрока – от 18 лет. промокод для 1xbet на сегодня. Промокод 1xBet сегодня найти в интернете не так сложно, достаточно воспользоваться любой поисковой системой. Но обращайте внимание на профессиональность ресурса, откуда будет скопирован промокод. Многие сайты предлагают неактуальные бонусные коды, которые не дадут никакого повышенного депозита после регистрации. На нашем сайте представлен актуальный промокод 1xBet на 2026 год. Вводите промокод, чтобы получить 100% сверху после первого пополнения. Минимальная сумма депозита для использования промокода – 1000 рублей. Ограничивается бонус 1хБет суммой в 32500 рублей.
Stanleyvonna
21 Oct 25 at 9:34 pm
https://baidak.ru/
Eugenioves
21 Oct 25 at 9:36 pm
продвижение сайта в топ 10 профессионалами [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_woKt
21 Oct 25 at 9:38 pm
«Частный Медик 24» — это медицинский контроль, поддержка и лечение на всех этапах вывода из запоя.
Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]вывод из запоя в стационаре нижний новгород[/url]
Jordanwrive
21 Oct 25 at 9:39 pm
Galera, quero deixar registrado sobre o Bingoemcasa porque me ganhou de verdade. O site tem um jeito leve que lembra um barzinho cheio de risadas. As salas de bingo sao movimentadas, e ainda testei alguns caca-niqueis modernos, todos vieram com graficos bonitos. O atendimento no chat foi respondeu em segundos, o que ja me deixou bem a vontade. As retiradas foram instantaneas, inclusive testei cripto e super tranquilo. Se pudesse apontar algo, diria que senti falta de ofertas extras, mas nada que estrague a experiencia. Enfim, o Bingoemcasa foi uma otima descoberta. Eu mesmo ja voltei varias vezes
bingoemcasa net|
mysticotter71zef
21 Oct 25 at 9:40 pm
рейтинг seo компаний [url=https://seo-prodvizhenie-reiting.ru/]рейтинг seo компаний[/url] .
seo prodvijenie reiting_scEa
21 Oct 25 at 9:41 pm
Где купить Альфу в Покачие?Друзья, расскажите – вот нашел https://hostel-loft.ru
. Цены нормальные, доставка есть. Кто-нибудь сталкивался с ними? Насколько качественно?
Stevenref
21 Oct 25 at 9:41 pm
рейтинг агентств по рекламе [url=http://www.luchshie-digital-agencstva.ru]http://www.luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_vpoi
21 Oct 25 at 9:41 pm
топ 10 сео продвижение [url=https://seo-prodvizhenie-reiting.ru/]топ 10 сео продвижение[/url] .
seo prodvijenie reiting_ibEa
21 Oct 25 at 9:44 pm
seo раскрутка продвижение [url=http://reiting-runeta-seo.ru]seo раскрутка продвижение[/url] .
reiting ryneta seo_yrma
21 Oct 25 at 9:44 pm
продвижение сайтов топ 10 [url=reiting-kompanii-po-prodvizheniyu-sajtov.ru]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_cnKt
21 Oct 25 at 9:44 pm
заказать seo продвижение сайта в топ 10 [url=http://www.seo-prodvizhenie-reiting-kompanij.ru]заказать seo продвижение сайта в топ 10[/url] .
seo prodvijenie reiting kompanii_dist
21 Oct 25 at 9:46 pm
seo продвижение сайта россия [url=https://reiting-seo-agentstv.ru/]seo продвижение сайта россия[/url] .
reiting seo agentstv_drsa
21 Oct 25 at 9:46 pm
лучшие seo агентства [url=http://reiting-seo-kompanii.ru]лучшие seo агентства[/url] .
reiting seo kompanii_xrsn
21 Oct 25 at 9:49 pm
Joined $MTAUR token hunt—presale bonuses stacking. Maze treasures and creature fights immersive. This project’s viral potential high.
mtaur token
WilliamPargy
21 Oct 25 at 9:52 pm
Play safely at Joy Palace, a PAGCOR licensed online casino in the Philippines.
Enjoy hundreds of slot games, live baccarat, and more.
Register now to claim your free welcome bonus!
Joy Palace Philippines - PAGCOR Licensed Online Casino & Slots
21 Oct 25 at 9:52 pm
everythingyouneedtoday – Content feels fresh and well-organized, making it easy to consume.
Boyce Gonales
21 Oct 25 at 9:53 pm
продвижение сайта топ 1 [url=https://www.seo-prodvizhenie-reiting.ru]продвижение сайта топ 1[/url] .
seo prodvijenie reiting_deEa
21 Oct 25 at 9:53 pm
creativityneverends – Found some fantastic ideas here for creative routines and daily inspiration.
Ayako Bahun
21 Oct 25 at 9:54 pm
Здравствуйте!
Vitebsk State University named after P.M. Masherov, one of the oldest universities in Belarus, invites you to get the education of European quality! Undoubted advantages of studying in VSU are affordability, high level of the quality of the educational process, great experience in training foreign students.
Полная информация по ссылке – https://vsu.by/inostrannym-abiturientam/vypuskniki.html
foreign student, Магистрантура, вторая ступень образования, й«з‰иЃЊдёљжЉЂжњЇе’Ње†Ќеџ№и®е¦й™ў
онлайн обучение, [url=https://vsu.by/studentam/vakantnye-byudzhetnye-mesta.html]sale[/url], university olympiad
Удачи и успехов в учебе!
KeithAligo
21 Oct 25 at 9:56 pm
seo оптимизация москва [url=www.reiting-seo-agentstv-moskvy.ru/]www.reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_ozMl
21 Oct 25 at 9:58 pm
Вывод из запоя в стационаре — это шанс начать путь к трезвой жизни, и в Самаре этот шанс предоставляет «Частный Медик 24».
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]вывод из запоя в стационаре клиника[/url]
Jerryrip
21 Oct 25 at 10:00 pm
прокладка трассы для кондиционера Установка Кондиционеров Под Ключ в Москве: Полный Спектр Услуг от Проектирования до Обслуживания Мы предлагаем установку кондиционеров под ключ в Москве, избавляя вас от необходимости поиска различных подрядчиков. Наша команда берет на себя все этапы работ: проектирование системы кондиционирования, подбор оборудования, доставку, монтаж, пуско-наладку и последующее обслуживание. Вы получаете готовое решение, полностью соответствующее вашим требованиям.
Johnniemuh
21 Oct 25 at 10:00 pm
Госпитализация в стационар помогает быстрее и надежнее справиться с последствиями запоя.
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]стационар вывод из запоя в нижний новгороде[/url]
Eduardonibre
21 Oct 25 at 10:01 pm
сео продвижение заказать москва [url=www.reiting-seo-agentstv-moskvy.ru]www.reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_frMl
21 Oct 25 at 10:01 pm