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!
Fastidious response in return of this question with firm arguments
and telling all regarding that.
Independence day images proud to be an indian
20 Aug 25 at 1:56 pm
This is the right blog for anyone who hopes to understand this topic.
You realize a whole lot its almost tough to
argue with you (not that I really would want to…HaHa). You certainly put a
new spin on a subject which has been discussed for years.
Great stuff, just wonderful!
https://stannesjacksonville.ecdio.org/
20 Aug 25 at 1:58 pm
http://www.medlinks.ru/article.php?sid=110930
DennisseK
20 Aug 25 at 1:58 pm
Hello to every body, it’s my first visit of this weblog; this web site
consists of remarkable and actually good information designed for
readers.
8kbetgov.com
20 Aug 25 at 1:58 pm
Hi, i think that i saw you visited my weblog so i came to “return the favor”.I’m trying to find things to enhance my web site!I suppose its ok to use some of your ideas!!
با رتبه ۵۰۰۰ تجربی چی قبول میشم ۱۴۰۳
20 Aug 25 at 2:00 pm
Pretty! This was an extremely wonderful post. Thanks for
providing this information.
نتایج کنکور فرهنگیان ۱۴۰۴ کی اعلام میشود
20 Aug 25 at 2:00 pm
Il vous suffit d’utiliser la fonction de chat en direct, qui est disponible 24 heures sur 24, 7 jours sur 7.
web page
20 Aug 25 at 2:03 pm
plinko [url=https://plinko3001.ru]https://plinko3001.ru[/url]
plinko_kz_itEr
20 Aug 25 at 2:06 pm
https://wanderlog.com/view/tvzdejmmcz/купить-экстази-кокаин-амфетамин-финляндия/shared
Chriszek
20 Aug 25 at 2:06 pm
Does your site have a contact page? I’m having a tough time locating
it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing.
Either way, great website and I look forward to seeing
it develop over time.
truc tiep bong da keo nha cai
20 Aug 25 at 2:07 pm
Hi! Would you mind if I share your blog with my zynga group?
There’s a lot of people that I think would really appreciate your
content. Please let me know. Cheers
Stærk Paycore
20 Aug 25 at 2:07 pm
как купить легальный диплом [url=http://arus-diplom31.ru/]http://arus-diplom31.ru/[/url] .
Kypit diplom lubogo yniversiteta!_riOl
20 Aug 25 at 2:07 pm
Heya i am for the primary time here. I found this board and I find It really useful & it helped me out much.
I’m hoping to present something again and help others such
as you helped me.
مصاحبه تخصصی فرهنگیان
20 Aug 25 at 2:11 pm
This information is priceless. Where can I find out more?
igtoto
20 Aug 25 at 2:13 pm
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Более подробно об этом – http://wheelchair.airwheeltech.com/2021/04/11/what-is-great-about-the-airwheel-h3pc-automatic-folding-wheelchair
NormanCow
20 Aug 25 at 2:16 pm
This quiz made me see the basics of color theory
in fashion. It’s fascinating how subtle differences in hue can change
how you look. I’m eager to use this knowledge in my fashion and makeup
decisions. Truly an invaluable experience!
color-analysis-quiz.org
20 Aug 25 at 2:16 pm
Давно слежу за этой темой, хочу поделиться находкой:
Для тех, кто ищет информацию по теме “raregreen.ru”, нашел много полезного.
Вот, можете почитать:
[url=https://raregreen.ru]https://raregreen.ru[/url]
Спасибо, что дочитали до конца.
rusPoito
20 Aug 25 at 2:16 pm
https://wanderlog.com/view/yxyeiqkrsb/купить-экстази-кокаин-амфетамин-страсбург/shared
Chriszek
20 Aug 25 at 2:27 pm
Your method of explaining all in this article is genuinely good, every one can effortlessly
know it, Thanks a lot.
valuable
20 Aug 25 at 2:31 pm
Aqua Tower looks really impressive! I like how it combines modern design with a practical way to store and dispense clean water.
It’s space-saving, stylish, and super convenient for everyday use.
Definitely a smart addition for anyone who wants
easy access to fresh water at home or in the office.
Aqua Tower
20 Aug 25 at 2:31 pm
1win регистрация на официальном сайте [url=http://1win22097.ru/]http://1win22097.ru/[/url]
1win_hypr
20 Aug 25 at 2:32 pm
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Санкт-Петербурге приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-v-sankt-peterburge15.ru/]помощь вывод из запоя санкт-петербург[/url]
Jessekew
20 Aug 25 at 2:32 pm
В Санкт-Петербурге решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Детальнее – [url=https://vyvod-iz-zapoya-v-sankt-peterburge18.ru/]вывод из запоя с выездом[/url]
JoshuaBen
20 Aug 25 at 2:36 pm
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Все материалы собраны здесь – https://studio-crece.com/information/%E3%80%90%E6%96%B0%E5%9E%8B%E3%82%B3%E3%83%AD%E3%83%8A%E3%82%A6%E3%82%A4%E3%83%AB%E3%82%B9%E3%81%AE%E6%84%9F%E6%9F%93%E6%8B%A1%E5%A4%A7%E3%81%AB%E5%AF%BE%E3%81%97%E3%81%A6%E3%81%AE%E5%AF%BE%E7%AD%96
NormanCow
20 Aug 25 at 2:36 pm
If some one needs to be updated with most recent technologies
afterward he must be go to see this website and be up to date daily.
casino
20 Aug 25 at 2:39 pm
Its like you read my mind! You appear to know so much about this, like
you wrote the book in it or something. I think that you could do with some
pics to drive the message home a bit, but other than that,
this is wonderful blog. An excellent read. I’ll certainly be back.
https://ax8855.com/
20 Aug 25 at 2:40 pm
Attractive part of content. I just stumbled upon your blog and in accession capital to claim that I get actually enjoyed account your weblog posts.
Anyway I’ll be subscribing on your feeds
or even I success you access constantly fast.
charge solar lights without sun
20 Aug 25 at 2:40 pm
When someone writes an piece of writing he/she keeps the idea of a user in his/her brain that
how a user can be aware of it. Thus that’s why this article is great.
Thanks!
nhà cái uy tín
20 Aug 25 at 2:41 pm
You ought to be a part of a contest for one of
the highest quality blogs on the internet.
I’m going to recommend this website!
Hermes Kelly Depeches 25 Pouch in Taupe Epsom Calf Hermes Kelly Depeches 25 Pouch in Taupe Epsom Calfskin price 674 AUD
20 Aug 25 at 2:48 pm
https://www.themeqx.com/forums/users/ickcbofpf/
Chriszek
20 Aug 25 at 2:48 pm
плинко [url=https://www.plinko-kz2.ru]плинко[/url]
plinko_kz_pber
20 Aug 25 at 2:52 pm
Психолог
zsqxow7984
20 Aug 25 at 2:52 pm
Very descriptive article, I liked that bit. Will there be a part 2?
perencanaandinaskesehatan.id
20 Aug 25 at 2:54 pm
What we’re covering
• Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra37.org]kraken36[/url]
• Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kra33at.com]kra36[/url]
• On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
kra38 at
https://kra-34cc.com
RichardJek
20 Aug 25 at 2:59 pm
https://odysee.com/@Ludvikseaac00lp
Howardhib
20 Aug 25 at 3:03 pm
Men’s Growth is a supplement aimed at boosting
vitality, energy, and overall male performance. Its natural formula is designed to support stamina and confidence,
helping men feel stronger and more active in daily life. Many users like it because it offers
a safe, effective way to enhance wellness without relying on harsh or synthetic options.
Men's Growth
20 Aug 25 at 3:03 pm
Wow, wonderful weblog structure! How long have you been running a
blog for? you made blogging look easy. The overall look of your website
is great, as well as the content!
chất kích thích
20 Aug 25 at 3:04 pm
Одним из популярных вариантов считается 10000 Wolves 10K Ways играть в 1хбет.
GerardBeaby
20 Aug 25 at 3:06 pm
Amazing! This blog looks just like my old one! It’s on a entirely different
topic but it has pretty much the same page layout and design. Wonderful choice of colors!
GO8
20 Aug 25 at 3:09 pm
https://muckrack.com/person-27486746
Chriszek
20 Aug 25 at 3:09 pm
tadalafil 20 mg directions: Tadalify – how many 5mg cialis can i take at once
PeterTEEFS
20 Aug 25 at 3:11 pm
I don’t even know how I ended up here, but I thought this post was good.
I don’t know who you are but certainly you’re going
to a famous blogger if you aren’t already 😉 Cheers!
https://69vning.me/
20 Aug 25 at 3:12 pm
Близкий человек в запое? Не ждите ухудшения. Обратитесь в клинику — здесь проведут профессиональный вывод из запоя с последующим восстановлением организма.
Углубиться в тему – [url=https://vyvod-iz-zapoya-chelyabinsk11.ru/]вывод из запоя недорого[/url]
TimothyKam
20 Aug 25 at 3:25 pm
NewEra Protect is designed to strengthen the immune system and support overall
well-being with its natural blend of ingredients.
It helps the body stay resilient, boosts energy, and promotes
daily health balance. Many users appreciate it
as an easy and reliable way to protect themselves
and maintain vitality year-round.
NewEra Protect
20 Aug 25 at 3:25 pm
Приложение позволяет пользователям наслаждаться всеми играми и функциями казино в удобном мобильном формате без потери качества.
максбет
20 Aug 25 at 3:28 pm
https://hoo.be/ygacudahicec
Chriszek
20 Aug 25 at 3:31 pm
Tadalify: teva generic cialis – Tadalify
ElijahKic
20 Aug 25 at 3:31 pm
блэкспрут дакрнет
RichardPep
20 Aug 25 at 3:33 pm
Greetings I am so excited I found your blog page, I really found you
by mistake, while I was browsing on Askjeeve
for something else, Anyways I am here now and would just like to say many thanks for a marvelous post and a all
round enjoyable blog (I also love the theme/design), I
don’t have time to go through it all at the moment but I
have saved it and also added your RSS feeds, so when I have time I will be back
to read a great deal more, Please do keep up the fantastic work.
Eleganckie
20 Aug 25 at 3:34 pm
На сайте https://xn--e1anbce0ah.xn--p1ai/nizniy_novgorod вы сможете произвести обмен криптовалюты: Ethereum, Bitcoin, BNB, XRP, Litecoin, Tether. Миссия сервиса заключается в том, чтобы предоставить пользователям доступ ко всем функциям, цифровым активам, независимо от того, в каком месте вы находитесь. Заполните графы для того, чтобы сразу узнать, какую сумму вы получите на руки. Также следует обозначить и личные данные, контакты, чтобы с вами связались, а также город. Все происходит строго конфиденциально.
JuxanhMof
20 Aug 25 at 3:36 pm