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://zaimy-25.ru/]https://zaimy-25.ru/[/url] .
zaimi_sioa
19 Sep 25 at 10:29 pm
https://xn--krken23-bn4c.com
Howardreomo
19 Sep 25 at 10:29 pm
все займы онлайн на карту [url=www.zaimy-23.ru]www.zaimy-23.ru[/url] .
zaimi_iuSl
19 Sep 25 at 10:30 pm
Farmasi Nutriplus România oferă suplimente și produse de wellness care îmbină inovația, calitatea și accesibilitatea.
Descoperă o gamă variată pentru un stil de
viață sănătos, cu beneficii reale, prețuri atractive
și garanția unei mărci de încredere.
Farmasi Nutriplus
19 Sep 25 at 10:31 pm
купить диплом в ельце [url=https://rudik-diplom1.ru]https://rudik-diplom1.ru[/url] .
Diplomi_moer
19 Sep 25 at 10:31 pm
купить диплом в архангельске с занесением в реестр [url=frei-diplom2.ru]купить диплом в архангельске с занесением в реестр[/url] .
Diplomi_dhEa
19 Sep 25 at 10:32 pm
диплом купить с занесением в реестр рязань [url=www.frei-diplom3.ru/]www.frei-diplom3.ru/[/url] .
Diplomi_zsKt
19 Sep 25 at 10:32 pm
купить диплом медсестры с занесением в реестр [url=frei-diplom6.ru]купить диплом медсестры с занесением в реестр[/url] .
Diplomi_pjOl
19 Sep 25 at 10:33 pm
If some one wants to be updated with newest technologies
after that he must be pay a quick visit this web site and be up to
date all the time.
Opulatrix Scam
19 Sep 25 at 10:33 pm
Discover the rise of Farmasi International, a global leader in cosmetics and wellness.
Explore its strong European roots, signature vegan-friendly products, and worldwide success.
Learn why Farmasi is a trusted brand in beauty,
skincare, and health across continents.
Farmasi Europe
19 Sep 25 at 10:34 pm
диплом купить с занесением в реестр москва [url=http://www.frei-diplom1.ru]диплом купить с занесением в реестр москва[/url] .
Diplomi_iiOi
19 Sep 25 at 10:35 pm
Wow, this article is fastidious, my sister is analyzing these things,
so I am going to inform her.
Margin Rivou
19 Sep 25 at 10:35 pm
где и как купить диплом колледжа [url=frei-diplom9.ru]frei-diplom9.ru[/url] .
Diplomi_voea
19 Sep 25 at 10:36 pm
That is very interesting, You’re a very professional blogger.
I have joined your rss feed and look forward to looking for more of your excellent post.
Also, I’ve shared your web site in my social networks
roof repair Centerton
19 Sep 25 at 10:36 pm
I don’t even know the way I finished up here, however I thought this
submit was great. I do not recognize who
you are but certainly you’re going to a well-known blogger if you happen to
aren’t already. Cheers!
درمان سرفه های شدید آنفولانزا
19 Sep 25 at 10:37 pm
Получить диплом о высшем образовании мы поможем. Купить диплом бакалавра в Кирове – [url=http://diplomybox.com/kupit-diplom-bakalavra-v-kirove/]diplomybox.com/kupit-diplom-bakalavra-v-kirove[/url]
Cazrhpj
19 Sep 25 at 10:39 pm
Incredible story there. What happened after?
Thanks!
ремонт стиральных машин вднх
19 Sep 25 at 10:40 pm
I am not sure where you arе gеtting youг info, Ƅut great topic.
I neеds to spend ѕome time learning morе or understanding moгe.
Τhanks for excellent info Ӏ ᴡas looкing for thiѕ info foг my mission.
my web page – site
site
19 Sep 25 at 10:41 pm
где купить диплом с занесением реестр [url=http://www.frei-diplom4.ru]где купить диплом с занесением реестр[/url] .
Diplomi_udOl
19 Sep 25 at 10:42 pm
купить диплом о среднем образовании в реестр [url=https://www.frei-diplom5.ru]купить диплом о среднем образовании в реестр[/url] .
Diplomi_wuPa
19 Sep 25 at 10:43 pm
накрутка подписчиков в тг смм накрутка
MatthewRow
19 Sep 25 at 10:44 pm
https://www.supercarbeds.com/blog/kids-racing-to-bed
JamesGrilE
19 Sep 25 at 10:44 pm
https://yamap.com/users/4818934
PeterRox
19 Sep 25 at 10:47 pm
купить диплом в екатеринбург реестр [url=http://frei-diplom3.ru/]купить диплом в екатеринбург реестр[/url] .
Diplomi_xyKt
19 Sep 25 at 10:47 pm
диплом с занесением в реестр купить [url=http://www.frei-diplom2.ru]диплом с занесением в реестр купить[/url] .
Diplomi_ryEa
19 Sep 25 at 10:47 pm
купить проведенный диплом кого [url=http://frei-diplom6.ru]купить проведенный диплом кого[/url] .
Diplomi_zuOl
19 Sep 25 at 10:47 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 10:48 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 10:49 pm
екатеринбург купить диплом в реестр [url=http://frei-diplom1.ru/]екатеринбург купить диплом в реестр[/url] .
Diplomi_oiOi
19 Sep 25 at 10:49 pm
Hi my family member! I want to say that this article is awesome, great written and
come with almost all vital infos. I’d like to see more posts like
this .
situs scam
19 Sep 25 at 10:49 pm
купить диплом в киселевске [url=http://rudik-diplom1.ru/]купить диплом в киселевске[/url] .
Diplomi_scer
19 Sep 25 at 10:50 pm
диплом автотранспортного техникума купить [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_qvea
19 Sep 25 at 10:51 pm
In today’s fast-evolving financial landscape,
it’s rare to find a platform that seamlessly bridges both crypto and fiat operations,
especially for large-scale operations. However, I came across this discussion that dives deep into a website which supports
everything from buying Bitcoin to managing fiat payments, and it’s
especially recommended for enterprise clients.
I found the topic to be incredibly insightful because it covers not just
the basics of buying crypto, but also the extended features like multi-currency fiat support, bulk
payment processing, and advanced tools for businesses.
What’s particularly valuable is the level of detail provided in the forum topic, including the
pros and cons, user reviews, and case studies
showing how enterprises have integrated the platform into their operations.
I’ve rarely come across such a balanced discussion that addresses both
crypto-savvy users and traditional finance professionals, especially in the context of
business-scale needs.
It’s a long read, but this forum topic offers some of
the most detailed opinions on using crypto platforms for corporate and fiat operations alike.
Definitely worth digging into this website.
post2
19 Sep 25 at 10:52 pm
[…] лиц, крановое электр&… закупающих […]
крановое электрооборудование – Best Marketing Agency in Vancouver
19 Sep 25 at 10:56 pm
медсестра которая купила диплом врача [url=https://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_qskt
19 Sep 25 at 10:57 pm
купить диплом в калуге [url=https://rudik-diplom1.ru/]купить диплом в калуге[/url] .
Diplomi_rver
19 Sep 25 at 10:58 pm
It’s a pity you don’t have a donate button! I’d without a doubt donate to this
excellent blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
I look forward to fresh updates and will share this blog with my Facebook group.
Talk soon!
중고화물차매매
19 Sep 25 at 11:02 pm
можно ли купить диплом в реестре [url=http://frei-diplom1.ru/]можно ли купить диплом в реестре[/url] .
Diplomi_rhOi
19 Sep 25 at 11:03 pm
In fact no matter if someone doesn’t understand afterward its up to other people that they will assist, so here
it occurs.
آمبولانس خصوصی تهران
19 Sep 25 at 11:03 pm
What’s a Pussyhat™ and why put on one? King first obtained cost for his writing
from adult magazines like Playboy and Cavalier “I don’t assume you have to penalize the unborn little one when one thing like that occurs,” he mentioned.
BUY VIAGRA
19 Sep 25 at 11:05 pm
диплом техникума купить дешево [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_nlea
19 Sep 25 at 11:06 pm
‘V’ Is for Viagra. The Remixes was created in 2007.
cialis tablet price
19 Sep 25 at 11:07 pm
wonderful publish, very informative. I ponder why the opposite specialists of this sector do not understand
this. You must continue your writing. I’m confident, you have
a great readers’ base already!
uu888
19 Sep 25 at 11:09 pm
купить диплом в черногорске [url=www.rudik-diplom8.ru/]www.rudik-diplom8.ru/[/url] .
Diplomi_wqMt
19 Sep 25 at 11:11 pm
диплом купить медицинского техникума [url=https://www.frei-diplom12.ru]диплом купить медицинского техникума[/url] .
Diplomi_qjPt
19 Sep 25 at 11:11 pm
купить диплом в выборге [url=https://rudik-diplom10.ru/]https://rudik-diplom10.ru/[/url] .
Diplomi_acSa
19 Sep 25 at 11:11 pm
официальные займы онлайн на карту бесплатно [url=http://zaimy-22.ru/]http://zaimy-22.ru/[/url] .
zaimi_twKi
19 Sep 25 at 11:12 pm
I absolutely love your website.. Pleasant colors & theme.
Did you build this web site yourself? Please reply back as
I’m trying to create my very own website and would like to learn where you
got this from or just what the theme is named. Appreciate
it!
비아그라 구입
19 Sep 25 at 11:12 pm
Hmm is anyone else experiencing 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.
co88
19 Sep 25 at 11:12 pm
VitalEdgePharma: VitalEdge Pharma – online ed pills
Dennisted
19 Sep 25 at 11:12 pm