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=https://zakazat-onlajn-translyaciyu7.ru/]онлайн трансляции мероприятий[/url] .
zakazat onlain translyaciu _rspt
3 Aug 25 at 12:45 pm
Hmm is anyone else encountering problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if
it’s the blog. Any feedback would be greatly
appreciated.
Best Mental Hospital in Chennai
3 Aug 25 at 12:46 pm
игровые пк [url=http://www.kupit-igrovoj-kompyuter10.ru]игровые пк[/url] .
kypit igrovoi komputer_opMt
3 Aug 25 at 12:47 pm
купить диплом о среднем образовании 11 классов [url=http://arus-diplom8.ru]http://arus-diplom8.ru[/url] .
Zakazat diplom o visshem obrazovanii!_neol
3 Aug 25 at 12:48 pm
мелбет партнерка [url=http://melbet1035.ru]http://melbet1035.ru[/url]
melbet_slKt
3 Aug 25 at 12:50 pm
https://www.manaolahawaii.com/
Richardboubs
3 Aug 25 at 12:51 pm
купить игровой компьютер [url=https://kupit-igrovoj-kompyuter10.ru]купить игровой компьютер[/url] .
kypit igrovoi komputer_piMt
3 Aug 25 at 12:52 pm
RelaxMeds USA: safe online source for Tizanidine – RelaxMedsUSA
Jessieopins
3 Aug 25 at 12:54 pm
Длительный запой приводит к нарастанию интоксикации, истощению нервной системы, серьёзным нарушениям в работе печени, почек и сердца. Могут возникнуть тяжёлые психозы (белая горячка), судороги, развитие алкогольной энцефалопатии, панкреатит, обострение хронических болезней. Самостоятельные попытки выйти из запоя с помощью «народных средств», внезапного отказа от алкоголя, промывания желудка или лекарств из домашней аптечки часто только усугубляют состояние.
Подробнее тут – https://vyvod-iz-zapoya-orekhovo-zuevo4.ru/vyvod-iz-zapoya-na-domu-v-orekhovo-zuevo/
Richardbor
3 Aug 25 at 12:59 pm
диплом купить с занесением в реестр отзывы [url=https://arus-diplom33.ru/]https://arus-diplom33.ru/[/url] .
Diplomi_nfSa
3 Aug 25 at 1:05 pm
I know this website presents quality depending articles and other stuff, is there any other web site which provides such information in quality?
my webpage – iskender
iskender
3 Aug 25 at 1:08 pm
купить аттестат в барнауле [url=http://arus-diplom8.ru]купить аттестат в барнауле[/url] .
Zakazat diplom instityta!_afol
3 Aug 25 at 1:11 pm
I couldn’t resist commenting. Exceptionally well written!
Yupoo Celine
3 Aug 25 at 1:16 pm
купить игровой пк [url=http://www.kupit-igrovoj-kompyuter9.ru]купить игровой пк[/url] .
kypit igrovoi komputer_qpPl
3 Aug 25 at 1:19 pm
Hello every one, here every person is sharing these experience, so it’s good to read this weblog, and I used to pay a quick visit this weblog everyday.
https://www.google.com.iq/url?sa=t&url=https://cabseattle.com/
Timsothydet
3 Aug 25 at 1:23 pm
1 win baixar [url=http://1win40003.ru/]http://1win40003.ru/[/url]
1win_kvKl
3 Aug 25 at 1:23 pm
Having read this I believed it was really enlightening.
I appreciate you finding the time and effort to put this short article together.
I once again find myself spending a significant amount of time both reading and posting comments.
But so what, it was still worthwhile!
essentials pharmacy
3 Aug 25 at 1:24 pm
Thank you Calming treats for Pets the good
writeup. It in fact was a amusement account it. Look advanced
to more added agreeable from you! By the way,
how can we communicate?
Calming treats for Pets
3 Aug 25 at 1:26 pm
https://www.locafilm.com
https://www.locafilm.com
3 Aug 25 at 1:26 pm
купить диплом с занесением в реестр в кемерово [url=http://www.arus-diplom34.ru]http://www.arus-diplom34.ru[/url] .
Diplomi_fuer
3 Aug 25 at 1:26 pm
https://victor-habitat.com/
GeorgeInise
3 Aug 25 at 1:26 pm
игровые пк [url=https://www.kupit-igrovoj-kompyuter10.ru]игровые пк[/url] .
kypit igrovoi komputer_nsMt
3 Aug 25 at 1:27 pm
игровые пк [url=https://kupit-igrovoj-kompyuter9.ru/]игровые пк[/url] .
kypit igrovoi komputer_pyPl
3 Aug 25 at 1:29 pm
можно ли купить аттестат 11 классов [url=https://arus-diplom25.ru/]можно ли купить аттестат 11 классов[/url] .
Diplomi_elot
3 Aug 25 at 1:29 pm
E2BET có giấy phép cho phép cung cấp dịch vụ cá
cược thể thao và cờ bạc trực tuyến cho
người dùng trong phạm vi quyền hạn do Malta
quản lý. Chứng nhận này đảm
E2BET Vietnam: Đá Gà Thomo Trực Tiếp Uy Tín Hàng Đầu
3 Aug 25 at 1:32 pm
купить аттестат за 11 класс в калининграде [url=www.arus-diplom23.ru]купить аттестат за 11 класс в калининграде[/url] .
Diplomi_mbSr
3 Aug 25 at 1:33 pm
Uncover the most captivating places in Slovenia with our expert
online tourist guide. From iconic landmarks to hidden gems, experience the finest places to visit.
Our Slovenia travel guide offers tips for an unforgettable journey.
top places in slovenia
3 Aug 25 at 1:34 pm
Вывод из запоя на дому является необходимым мероприятием при возникновении тяжелых форм алкогольной интоксикации, когда самостоятельное прекращение употребления алкоголя становится невозможным. Если наблюдаются такие симптомы, как спутанность сознания, учащенный пульс, гипертония или снижение артериального давления, срочная помощь нарколога необходима для предотвращения серьезных осложнений. При раннем вмешательстве можно не только вывести токсины, но и стабилизировать работу жизненно важных органов, что существенно повышает шансы на полное восстановление.
Подробнее – [url=https://vyvod-iz-zapoya-yaroslavl0.ru/]вывод из запоя на дому в ярославле[/url]
Williamdah
3 Aug 25 at 1:34 pm
We’re a gaggle of volunteers and opening a brand new scheme in our
community. Your site offered us with valuable info to work on. You’ve done a formidable job and our entire community will
probably be thankful to you.
deneme bonusu veren siteler
3 Aug 25 at 1:35 pm
Hello, I enjoy reading through your article.
I like to write a little comment to support you.
my web-site Calming treats for Pets
Calming treats for Pets
3 Aug 25 at 1:38 pm
провайдеры интернета челябинск
chelyabinsk-domashnij-internet006.ru
подключить интернет
internetchelyabelini
3 Aug 25 at 1:40 pm
пк игровой [url=http://www.kupit-igrovoj-kompyuter10.ru]http://www.kupit-igrovoj-kompyuter10.ru[/url] .
kypit igrovoi komputer_dcMt
3 Aug 25 at 1:41 pm
My spouse and I absolutely love your blog and find the
majority of your post’s to be exactly I’m looking for.
can you offer guest writers to write content in your
case? I wouldn’t mind writing a post or elaborating on some of
the subjects you write with regards to here. Again, awesome web
log!
My blog post … купить квартиру в турции
купить квартиру в турции
3 Aug 25 at 1:42 pm
Sehr informativ, danke dafür! Ich teste momentan verschiedene Plinko-Apps und bin überrascht – vor allem mobil macht
es richtig Spaß. Am Anfang habe ich mit squidwebhosting.com und ich war positiv überrascht.
Mit etwas Erfahrung versteht man dann die Mechanik besser.
Ich mag vor allem die kurzen Ladezeiten und Extras. Man weiß
nie, wo die Kugel landet – das ist das Geile. Wer’s noch nie gezockt hat, sollte es mal testen – Plinko lohnt sich.
Und wer mehr will, sollte auch mal die Echtgeld-Variante checken. Top Content – bitte mehr zu solchen Themen!
JT
3 Aug 25 at 1:42 pm
how to get cheap zithromax price
Petercog
3 Aug 25 at 1:42 pm
Сильная тошнота, рвота, дезориентация и судорожные сокращения мышц свидетельствуют о критическом уровне алкоголя в крови. В этих ситуациях промедление повышает риск острого панкреатита, комы и сердечных аритмий.
Разобраться лучше – http://vivod-iz-zapoya-chelyabinsk13.ru/
Charlesjek
3 Aug 25 at 1:43 pm
купить аттестат в санкт петербурге [url=www.arus-diplom8.ru]купить аттестат в санкт петербурге[/url] .
Kypit diplom VYZa!_beol
3 Aug 25 at 1:43 pm
https://muskaanhindi.org
https://muskaanhindi.org
3 Aug 25 at 1:45 pm
В клинике применяются инновационные методы диагностики, включая лабораторные анализы и аппаратные исследования, которые позволяют выявить степень зависимости и сопутствующие патологии. Важным этапом является комплексный подход к лечению, включающий детоксикацию организма, психотерапию и медикаментозную поддержку.
Разобраться лучше – [url=https://narkologicheskaya-klinika-krasnodar00.ru/]бесплатная наркологическая клиника[/url]
Danielkeype
3 Aug 25 at 1:48 pm
туры в абхазию
AlvinFup
3 Aug 25 at 1:50 pm
Heya i am for the primary time here. I found this board and I in finding It really helpful & it
helped me out much. I am hoping to offer one thing back
and aid others such as you aided me.
my web page: judi slot88
judi slot88
3 Aug 25 at 1:51 pm
https://alltranslations.ru/
https://alltranslations.ru/
3 Aug 25 at 1:55 pm
красивый игровой пк [url=kupit-igrovoj-kompyuter9.ru]kupit-igrovoj-kompyuter9.ru[/url] .
kypit igrovoi komputer_krPl
3 Aug 25 at 1:55 pm
https://buttkarahibarkiroad.com/2025/07/28/verde-casino-app-download-la-tua-destinazione-2/
JulioMug
3 Aug 25 at 1:56 pm
Stay updated with the latest news, trending events, and fascinating stories from Bangladesh on Bangla-X.News.
Fast, accurate, and diverse updates across all sectors!
Indonesia
3 Aug 25 at 1:56 pm
организация онлайн трансляций мероприятий [url=zakazat-onlajn-translyaciyu6.ru]zakazat-onlajn-translyaciyu6.ru[/url] .
zakazat onlain translyaciu _oikt
3 Aug 25 at 1:59 pm
buy Zanaflex online USA: affordable Zanaflex online pharmacy – affordable Zanaflex online pharmacy
Antonionek
3 Aug 25 at 2:05 pm
May I simply just say what a comfort to uncover someone who truly knows what they are talking about on the internet.
You actually realize how to bring a problem to light and make
it important. More and more people must read this and understand this side of your story.
I was surprised you are not more popular given that you most certainly have the gift.
Stop by my web blog: iskender
iskender
3 Aug 25 at 2:05 pm
красивый игровой пк [url=http://kupit-igrovoj-kompyuter9.ru/]http://kupit-igrovoj-kompyuter9.ru/[/url] .
kypit igrovoi komputer_jzPl
3 Aug 25 at 2:05 pm
игровые пк москва [url=http://kupit-igrovoj-kompyuter9.ru]игровые пк москва[/url] .
kypit igrovoi komputer_bnPl
3 Aug 25 at 2:08 pm