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!
Драгон Мани – идеальный выбор для азарта! Захватывающие игры,
бонусы и быстрые выплаты. Получи максимум эмоций и выигрывай с удовольствием!
драгон мани вход
Jordanpiony
28 Oct 25 at 7:02 pm
заказать продвижение сайта в москве [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]заказать продвижение сайта в москве[/url] .
optimizaciya i seo prodvijenie saitov moskva_loel
28 Oct 25 at 7:04 pm
Казино Mellstroy – это море азарта и удачи! Яркие игры,
щедрые акции и быстрые выплаты. Погрузитесь в мир азартных
эмоций и наслаждайтесь каждым моментом
слоты мелстроя
Sammyfag
28 Oct 25 at 7:04 pm
Драгон Мани казино – азарт и удача! Увлекательные игры,
щедрые бонусы, мгновенные выплаты. Погрузись в мир эмоций и выигрывай!
драгон мани вход
Alvinlor
28 Oct 25 at 7:07 pm
If you are going for finest contents like me, only go to see this
site daily for the reason that it offers feature contents, thanks
ANDREW'S E-STORE IRELAND,
28 Oct 25 at 7:08 pm
кракен
кракен vk5
Henryamerb
28 Oct 25 at 7:08 pm
kraken РФ
kraken сайт
Henryamerb
28 Oct 25 at 7:09 pm
блог про продвижение сайтов [url=http://www.statyi-o-marketinge6.ru]блог про продвижение сайтов[/url] .
stati o marketinge _evkn
28 Oct 25 at 7:09 pm
Казино Mellstroy – это море азарта и удачи! Яркие игры,
щедрые акции и быстрые выплаты. Погрузитесь в мир азартных
эмоций и наслаждайтесь каждым моментом
казино мелстрой
Sammyfag
28 Oct 25 at 7:10 pm
I have been browsing on-line more than three hours as of late, yet I never found any interesting article like yours.
It is beautiful worth enough for me. In my opinion, if all webmasters
and bloggers made just right content material as you probably did,
the net will likely be a lot more useful than ever before.
Veneers Thailand Price
28 Oct 25 at 7:12 pm
urbanwearstudio – Customer contact or support info appears accessible, which builds trust.
Joyce Harwood
28 Oct 25 at 7:12 pm
Драгон Мани – ваш надежный партнер в мире азарта!
Увлекательные игры, щедрые бонусы и моментальные выплаты!
промокоды и фриспины dragon money
Aaronbrume
28 Oct 25 at 7:13 pm
блог про seo [url=statyi-o-marketinge7.ru]блог про seo[/url] .
stati o marketinge _wtkl
28 Oct 25 at 7:14 pm
кракен 2025
кракен 2025
Henryamerb
28 Oct 25 at 7:14 pm
Промокод – небольшая цифробуквенная комбинация, которая дает право на получение каких-то привилегий и бонусов. Система промокодов позволяет букмекерским конторам привлекать новых пользователей, поощрять их регистрацию и пополнение счета, поэтому эта схема удобна как букмекерам, так и пользователям. Вводя промокод мелбет на сегодня 2026 и другие бонусы для первых ставок. Обычно ввод промокода не представляет особой сложности. На сайте букмекера при регистрации будет отведено специальное поле для ввода кодовой комбинации. При выполнении всех условий компании, предоставляющей бонус, код начинает действовать сразу после ввода. Дополнительная активация не требуется. В этом случае есть свои особенности, о которых будет рассказано далее.
Georgeduh
28 Oct 25 at 7:15 pm
купить диплом штукатура [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .
Diplomi_twPl
28 Oct 25 at 7:16 pm
AU88️Link Đăng Ký – Đăng Nhập AU88.com Uy Tín An Toàn +88K
AU88 là sân chơi cá cược trực tuyến đẳng cấp.
Được cấp phép hoạt động bởi PAGCOR – tổ chức quản lý uy tín tại Philippines.
Sở hữu nền tảng công nghệ hiện đại, giao diện thân thiện, thao tác
dễ dàng cùng kho trò chơi đa dạng như cá cược thể
thao, casino online, xổ số, đá gà, nổ hũ… Và hàng nghìn game hấp dẫn khác.
AU88 cam kết mang đến cho người chơi trải nghiệm an toàn tuyệt đối.
https://sdwi.sa.com/
au88
28 Oct 25 at 7:16 pm
https://t.me/s/Official_mellstroy_casino/7
Calvindreli
28 Oct 25 at 7:17 pm
imaginelearnexplore – Navigation seems smooth and product categories appear well organized.
Denny Hawf
28 Oct 25 at 7:18 pm
https://t.me/s/Official_mellstroy_casino/18
Calvindreli
28 Oct 25 at 7:18 pm
Драгон Мани – ваш надежный партнер в мире азарта!
Увлекательные игры, щедрые бонусы и моментальные выплаты!
драгон мани зеркало рабочее
Aaronbrume
28 Oct 25 at 7:18 pm
Hello my family member! I want to say that this post is amazing, great
written and include approximately all vital infos. I would like to see extra posts like
this .
teslabahis giriş adresleri
28 Oct 25 at 7:18 pm
I don’t even know the way I stopped up right here,
however I believed this post used to be good. I don’t realize who you might be but certainly you are going to
a famous blogger for those who aren’t already. Cheers!
tech for dog training
28 Oct 25 at 7:20 pm
kraken tor
kraken сайт
Henryamerb
28 Oct 25 at 7:20 pm
Оптические нивелиры – это геодезические инструменты, предназначенные для определения превышений между точками на земной поверхности и создания горизонтальных линий визирования. Они широко используются в строительстве, геодезии,
землеустройстве и других областях, где требуется точное измерение высот. Подскажите каким должен быть качественный [url=https://crimeaguide.com/forum/viewtopic.php?f=5&t=16278]оптический нивелир[/url]
Tanyalig
28 Oct 25 at 7:23 pm
блог seo агентства [url=https://www.statyi-o-marketinge6.ru]https://www.statyi-o-marketinge6.ru[/url] .
stati o marketinge _jhkn
28 Oct 25 at 7:24 pm
купить диплом в ессентуках [url=https://rudik-diplom7.ru/]купить диплом в ессентуках[/url] .
Diplomi_kdPl
28 Oct 25 at 7:25 pm
материалы по маркетингу [url=http://statyi-o-marketinge6.ru]http://statyi-o-marketinge6.ru[/url] .
stati o marketinge _rrkn
28 Oct 25 at 7:26 pm
мелбет букмекерская контора [url=http://melbetofficialsite.ru]мелбет букмекерская контора[/url] .
bk melbet_qdEa
28 Oct 25 at 7:27 pm
Chơi tại BJ39 Việt Nam và trải nghiệm cờ bạc
trực tuyến tốt nhất: slot, casino trực tiếp, sportsbook và
tiền thưởng hấp dẫn hàng ngày.
BJ39 – Trang web cờ bạc trực tuyến số 1 tại Việt Nam
28 Oct 25 at 7:28 pm
кракен маркет
kraken vk3
Henryamerb
28 Oct 25 at 7:29 pm
kraken marketplace
кракен сайт
Henryamerb
28 Oct 25 at 7:30 pm
продвижение в google [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_ctel
28 Oct 25 at 7:30 pm
Nice blog here! Also your web site loads up very fast! What web
host are you using? Can I get your affiliate link to your host?
I wish my web site loaded up as fast as yours lol
Velzomerinex Review
28 Oct 25 at 7:31 pm
официальный сайт бк мелбет [url=www.melbetofficialsite.ru/]официальный сайт бк мелбет[/url] .
bk melbet_dsEa
28 Oct 25 at 7:32 pm
discoverandcreate – I’ll bookmark this store for when I’m looking for creative, unique finds.
Rudy Solonar
28 Oct 25 at 7:32 pm
материалы по seo [url=https://statyi-o-marketinge6.ru/]материалы по seo[/url] .
stati o marketinge _glkn
28 Oct 25 at 7:32 pm
https://amunragiochi.com/
1go casino
28 Oct 25 at 7:32 pm
ts ровный беру уже давно унего но 35ф реально слабый эфект трафы сделал 10к1 неочом в итоги из 50г сделал 300гр основ нармально вышло по качиству пока ещё ещё некто не рыгал( но вопщем неплохо цена соответствует качиству 400р за грам норм https://mediclever.ru Закупал я рег у Тс конечно качество пацаны просто бомба:good: Я токого не когда не пробывал!!!
JasonBoomi
28 Oct 25 at 7:33 pm
купить диплом с реестром [url=https://rudik-diplom7.ru/]купить диплом с реестром[/url] .
Diplomi_tqPl
28 Oct 25 at 7:33 pm
куплю диплом цена [url=http://www.rudik-diplom13.ru]куплю диплом цена[/url] .
Diplomi_rjon
28 Oct 25 at 7:33 pm
Lightening agents that lighten your teeth can frequently momentarily aggravate the
periodontals.
Hildred
28 Oct 25 at 7:33 pm
radio with cd player and alarm clock [url=https://alarm-radio-clocks.com/]https://alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_ibOa
28 Oct 25 at 7:34 pm
блог seo агентства [url=http://www.statyi-o-marketinge6.ru]http://www.statyi-o-marketinge6.ru[/url] .
stati o marketinge _xqkn
28 Oct 25 at 7:35 pm
купить диплом электрика [url=http://www.rudik-diplom6.ru]купить диплом электрика[/url] .
Diplomi_bnKr
28 Oct 25 at 7:37 pm
кракен маркет
кракен
Henryamerb
28 Oct 25 at 7:37 pm
Обожаю сайт казино онлайн, он очень понятный
в использовании!
рейтинг онлайн казино
рейтинг онлайн казино
28 Oct 25 at 7:38 pm
web site menyediakan layanan link daftar
akun slot gacor dengan sistem cepat dan aman. Situs ini
sudah dikenal luas sebagai tempat terbaik untuk bermain slot online gampang maxwin, karena
menghadirkan berbagai game dengan RTP tinggi dan tingkat kemenangan yang stabil.
web site
28 Oct 25 at 7:39 pm
В процессе лечения используются проверенные методики, которые в комплексе обеспечивают положительный эффект и снижают риск рецидива.
Исследовать вопрос подробнее – [url=https://lechenie-alkogolizma-omsk0.ru/]принудительное лечение от алкоголизма в омске[/url]
BradleyGeali
28 Oct 25 at 7:39 pm
Такая структура делает лечение последовательным и предсказуемым, повышая шансы на положительный исход.
Подробнее тут – https://narkologicheskaya-klinika-v-omske0.ru/chastnaya-narkologicheskaya-klinika-omsk
FloydVop
28 Oct 25 at 7:39 pm