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!
It’s truly very difficult in this full of activity life to listen news on TV, so
I just use world wide web for that reason, and get the newest information.
https://livedrawlaos.life/
Keluaran Laos
30 Aug 25 at 11:55 pm
купить аттестаты за 11 класс москва цена [url=https://arus-diplom23.ru]купить аттестаты за 11 класс москва цена[/url] .
Diplomi_cwSr
30 Aug 25 at 11:57 pm
напольные цветочные горшки купить [url=http://kashpo-napolnoe-moskva.ru]http://kashpo-napolnoe-moskva.ru[/url] .
kashpo napolnoe _trOi
30 Aug 25 at 11:59 pm
Заказать диплом под заказ в Москве возможно через сайт компании. [url=http://zador.flybb.ru/viewtopic.php?f=1&t=4113&sid=e87418e24740da22f4561c0427720448/]zador.flybb.ru/viewtopic.php?f=1&t=4113&sid=e87418e24740da22f4561c0427720448[/url]
Sazrsyn
31 Aug 25 at 12:00 am
купить диплом младшего специалиста [url=https://educ-ua4.ru]купить диплом младшего специалиста[/url] .
Diplomi_dhPl
31 Aug 25 at 12:01 am
https://bio.site/aibyohubugm
Josephpef
31 Aug 25 at 12:05 am
купить диплом с занесением в реестр в мурманске [url=arus-diplom32.ru]купить диплом с занесением в реестр в мурманске[/url] .
Zakazat diplom ob obrazovanii!_svEn
31 Aug 25 at 12:10 am
купить диплом о высшем образовании [url=www.educ-ua5.ru]купить диплом о высшем образовании[/url] .
Diplomi_ouKl
31 Aug 25 at 12:19 am
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to more added agreeable from
you! However, how can we communicate?
https://play.google.com/store/apps/details?id=com.slots.casinobangladesh.glory
31 Aug 25 at 12:20 am
What’s up, its nice paragraph about media print, we all be familiar with media is a impressive source of data.
Stop by my blog post; امداد خودرو
امداد خودرو
31 Aug 25 at 12:21 am
как купить аттестат за 11 класс [url=http://arus-diplom21.ru]как купить аттестат за 11 класс[/url] .
Zakazat diplom yniversiteta!_iepn
31 Aug 25 at 12:23 am
magnificent points altogether, you simply received a new
reader. What could you suggest about your submit that you simply made a few days ago?
Any sure?
Here is my website آموزش فارکس
آموزش فارکس
31 Aug 25 at 12:23 am
Hey! Someone in my Facebook group shared this
website with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
Fantastic blog and outstanding design and style.
clean-label respiratory ritual
31 Aug 25 at 12:24 am
Hi there, I found your blog via Google whilst looking for a related topic, your website got
here up, it appears to be like great. I’ve bookmarked it in my google bookmarks.
Hi there, just became aware of your blog through Google, and found that it’s really informative.
I am going to watch out for brussels. I’ll be grateful if you proceed this in future.
Numerous people will be benefited from your writing. Cheers!
buôn bán nội tạng
31 Aug 25 at 12:24 am
https://wirtube.de/a/cemekadanger7/video-channels
Josephpef
31 Aug 25 at 12:27 am
Meds information leaflet. Short-Term Effects.
can i buy generic inderal without prescription
Actual trends of drugs. Read now.
can i buy generic inderal without prescription
31 Aug 25 at 12:29 am
Very nice write-up. I definitely love this site.
Thanks!
Danny
31 Aug 25 at 12:30 am
tipobet casino siteleri ali musaoğulları
grandpashabet
31 Aug 25 at 12:33 am
I used to be recommended this web site via my cousin. I am not positive whether or not this post is written by him as nobody else realize such unique approximately my difficulty.
You’re incredible! Thank you!
RapidoCripto24
31 Aug 25 at 12:33 am
Купить диплом под заказ в Москве возможно через сайт компании. [url=http://obozrevatelevents.ru/kupit-diplom-srochno-v-techenie-3-dney/]obozrevatelevents.ru/kupit-diplom-srochno-v-techenie-3-dney[/url]
Sazrodj
31 Aug 25 at 12:41 am
Awesome post.
best hosting
31 Aug 25 at 12:41 am
best online casinos for 81 JokerX
RichardKap
31 Aug 25 at 12:42 am
Hello there, just became alert to your blog through Google, and found that it’s really informative.
I’m going to watch out for brussels. I will be grateful if you continue this in future.
Many people will be benefited from your writing. Cheers!
services
31 Aug 25 at 12:42 am
Vertigenics seems like a really helpful supplement for
anyone struggling with dizziness or balance issues.
I like that it’s made with natural ingredients aimed at
supporting inner ear health and circulation, which are often linked to vertigo symptoms.
It could be a great option for people looking for a more
natural and supportive way to feel steady and confident again.
Vertigenics
31 Aug 25 at 12:43 am
купить диплом с занесением в реестр в мурманске [url=https://arus-diplom32.ru/]купить диплом с занесением в реестр в мурманске[/url] .
Priobresti diplom yniversiteta!_egEn
31 Aug 25 at 12:44 am
купить аттестат об окончании 11 классов в новосибирске [url=www.arus-diplom23.ru/]купить аттестат об окончании 11 классов в новосибирске[/url] .
Diplomi_joSr
31 Aug 25 at 12:47 am
With havin so much content and articles do you ever run into any problems of plagorism or copyright
violation? My blog has a lot of completely unique content I’ve either created myself or outsourced but it seems
a lot of it is popping it up all over the web without my authorization. Do you know
any solutions to help stop content from being stolen? I’d really appreciate it.
Fyronex Driftor GPT
31 Aug 25 at 12:47 am
https://hoo.be/idtybefyh
Josephpef
31 Aug 25 at 12:49 am
Проблемы зависимости — актуальная тема для современного общества. Эти состояния оказывают серьезное влияние на личность, семью и общественные связи. Наркологическая клиника “Перезагрузка” предлагает широкий спектр услуг для людей, страдающих от различных зависимостей, таких как алкоголизм, наркомания и игромания. Наша задача заключается в комплексном подходе к лечению, что обеспечивает успешные результаты для наших пациентов.
Узнать больше – http://zavisim-alko.ru
KennethGlolo
31 Aug 25 at 12:54 am
What’s up, its good article on the topic of media print,
we all understand media is a impressive source of facts.
situs slot88
31 Aug 25 at 12:58 am
When someone writes an piece of writing he/she keeps the image of a user in his/her mind that how a user can know it.
Therefore that’s why this article is outstdanding.
Thanks!
https://hafenapp.thyssenkrupp-steel.com
31 Aug 25 at 12:59 am
аттестаты за 11 класс купить в спб [url=www.arus-diplom21.ru]аттестаты за 11 класс купить в спб[/url] .
Priobresti diplom ob obrazovanii!_uqpn
31 Aug 25 at 1:00 am
Target is in trouble. And while it’s easy to get lost in the company’s recent (poor) handling of American culture war narratives that cast it as too “woke” or too willing to cave to online fascists, the root of Target’s problems runs deep.
[url=https://tripscan39.org]трипскан[/url]
Don’t get me wrong – the massive consumer boycotts from Black organizers have done damage. And there are probably folks on the far right who think even Target’s toned-down, overwhelmingly beige Pride merch this year was still too loud.
https://tripscan39.org
трипскан
But its stock is in the gutter and sales have been falling for two years because of good ol’ business fundamentals. It overstocked. It lost the pulse of its customers. It went up against Amazon Prime with… actually, does anyone know what Target’s Amazon Prime competitor is called?
The brand we petite bourgeoisie once playfully referred to as Tar-zhay has lost its spark. The company reported a decline in sales for a third-straight quarter, part of a broader trend of falling or flat sales for two years. Employees have lost confidence in the company’s direction. And 2025 has been a particularly rough financially, as Black shoppers organized a boycott over Target’s decision to cave to right-wing pressure on diverse hiring goals.
Shares were down 10% Wednesday.
It’s not to say the new guy, Michael Fiddelke, is unqualified. He’s been at Target since he started as an intern more than 20 years ago, after all. But Wall Street is clearly concerned that Target’s leadership is underestimating the severity of the need for a significant change— just as President Donald Trump’s tariffs on imported goods threaten the entire retail industry.
Appointing a company lifer “does not necessarily remedy the problems of entrenched groupthink and the inward-looking mindset that have plagued Target for years,” Neil Saunders, an analyst at GlobalData Retail, said in a note to clients Wednesday.
Missing the mark
In its 2010s heyday, Target became a go-to for consumers who liked a bargain but didn’t necessarily like bargain-hunting. The shelves felt well-curated. You’d go to Target because it had one thing you needed and 12 things you didn’t know you needed. It was stocked with Millennial cringe long before Gen Z gave us the term Millennial cringe.
Target’s sales held strong through the pandemic as remote workers set up home offices and stocked up on essentials. Months of lockdown also benefited the store as people began refreshing their spaces because they didn’t really have much else to do and they were staring at the same walls all the time.
MichaelPeS
31 Aug 25 at 1:03 am
купить диплом спб занесением реестр [url=http://qooh.me/vadyymemelnvv/]купить диплом спб занесением реестр[/url] .
Kypit diplom VYZa!_xxkt
31 Aug 25 at 1:03 am
Каждое обращение рассматривается индивидуально, и лечение начинается с первичной консультации — по телефону или онлайн. Врач-нарколог подробно расспрашивает о длительности запоя, общем состоянии, наличии хронических заболеваний, симптомах. Это необходимо для быстрого реагирования и подготовки медикаментов.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-shchelkovo6.ru/]вывод из запоя цена[/url]
JarvisStove
31 Aug 25 at 1:08 am
Hiya! I know this is kinda off topic but I’d figured I’d ask.
Would you be interested in exchanging links or
maybe guest writing a blog post or vice-versa? My blog discusses
a lot of the same topics as yours and I believe we could greatly
benefit from each other. If you’re interested feel free to send me an e-mail.
I look forward to hearing from you! Great blog by the way!
Christopher
31 Aug 25 at 1:08 am
Greetings! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly?
My weblog looks weird when viewing from my iphone 4.
I’m trying to find a theme or plugin that might be able to
fix this problem. If you have any suggestions, please share.
With thanks!
my web site :: آموزشگاه برق خودرو
آموزشگاه برق خودرو
31 Aug 25 at 1:10 am
Thanks a lot for sharing this with all folks you really realize what you’re speaking approximately!
Bookmarked. Please also talk over with my website =).
We could have a link alternate arrangement
among us
Immutable Azopt
31 Aug 25 at 1:10 am
купить вкладыш к аттестату 11 [url=www.arus-diplom23.ru]купить вкладыш к аттестату 11[/url] .
Diplomi_khSr
31 Aug 25 at 1:11 am
https://www.openlibhums.org/profile/f465289c-2701-43ce-81e9-3934da083e61/
Josephpef
31 Aug 25 at 1:12 am
кашпо для комнатных растений напольные [url=www.kashpo-napolnoe-moskva.ru]www.kashpo-napolnoe-moskva.ru[/url] .
kashpo napolnoe _izOi
31 Aug 25 at 1:22 am
Hi to every one, the contents existing at this web page are in fact awesome for people knowledge, well, keep up the good work fellows.
소액결제현금화
31 Aug 25 at 1:23 am
Купить диплом на заказ в Москве возможно через официальный портал компании. [url=http://mcn-kw.com/employer/education-ua/]mcn-kw.com/employer/education-ua[/url]
Sazriic
31 Aug 25 at 1:24 am
hi!,I like your writing very much! proportion we keep in touch extra approximately your article on AOL?
I require an expert on this area to resolve my problem.
Maybe that’s you! Having a look forward to look you.
Orthodontics near me
31 Aug 25 at 1:29 am
https://airprotectauto.com/1xbet-promo-code-list-today-1x200big-updates-inventories-including-seasonal-offers-for-holidays/
JustinRaP
31 Aug 25 at 1:30 am
This blog was… how do you say it? Relevant!!
Finally I have found something that helped me. Thank you!
toto
31 Aug 25 at 1:31 am
It’s truly very complex in this active life to listen news on TV, therefore I simply use world wide web for that
purpose, and get the most up-to-date news.
sneaky redirects seo
31 Aug 25 at 1:32 am
Самостоятельно выйти из запоя — почти невозможно. В Самаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara11.ru/]вывод из запоя капельница на дому[/url]
ThomasKex
31 Aug 25 at 1:33 am
купить аттестат за 10 и 11 классы [url=http://arus-diplom23.ru]купить аттестат за 10 и 11 классы[/url] .
Diplomi_vcSr
31 Aug 25 at 1:33 am
Организация помощи нарколога на дому в Твери построена по строгому алгоритму, который включает несколько ключевых этапов. Такой комплексный подход позволяет не только быстро вывести токсичные вещества, но и обеспечить всестороннюю поддержку для скорейшего восстановления организма.
Исследовать вопрос подробнее – https://reabcentr-narko.ru
MichaelSmurn
31 Aug 25 at 1:34 am