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!
Unquestionably believe that which you stated. Your favorite reason seemed to be on the
internet the easiest thing to be aware of. I say to you, I definitely get irked while people consider
worries that they plainly do not know about.
You managed to hit the nail upon the top as well as defined out the whole
thing without having side effect , people could take a signal.
Will likely be back to get more. Thanks
Trueflip Casino
20 Aug 25 at 3:37 pm
диплом о среднем образовании купить легально [url=http://arus-diplom31.ru]http://arus-diplom31.ru[/url] .
Diplomi_dwpl
20 Aug 25 at 3:38 pm
It’s the best time to make some plans for the long run and it’s time to be happy.
I have read this submit and if I could I wish to recommend you some attention-grabbing issues or
tips. Perhaps you can write subsequent articles referring to this article.
I want to read even more things about it!
phim con heo
20 Aug 25 at 3:39 pm
Нey There. I found your weblog uѕing msn. That іs
a very well written artiсle. I will be sure tօ ƅookmarқ it and return to read extrа
of your helpful informatіon. Thank you for thе post.
I will certainly comеback.
my web site … uniform Apparel companies
uniform Apparel companies
20 Aug 25 at 3:41 pm
https://pxlmo.com/AudreyMcrae5751
Howardhib
20 Aug 25 at 3:42 pm
Generally I don’t read post on blogs, however I would like to say that this write-up very pressured me to take a look at and do
it! Your writing taste has been surprised me. Thank you, quite nice post.
danske spil casino
20 Aug 25 at 3:42 pm
viagra 100 coupon: sildenafil uk best price – sildenafil 100mg canada
PeterTEEFS
20 Aug 25 at 3:51 pm
https://beteiligung.stadtlindau.de/profile/%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%91%D0%BE%D1%88%D0%BA%D0%B8%20%D0%9C%D0%B0%D1%80%D0%B8%D1%85%D1%83%D0%B0%D0%BD%D1%83%20%D0%93%D0%B0%D1%88%D0%B8%D1%88%20%D0%90%D0%B1%D1%83-%D0%94%D0%B0%D0%B1%D0%B8/
Chriszek
20 Aug 25 at 3:53 pm
Excellent write-up. I certainly love this website.
Stick with it!
Lizoradex
20 Aug 25 at 4:00 pm
Valuable info. Fortunate me I found your website by accident, and I’m
shocked why this twist of fate didn’t took place earlier!
I bookmarked it.
Thanks
20 Aug 25 at 4:01 pm
There іs certainly а lot to know aƄout thiѕ subject.
Ι love аll of the points you’ve made.
Taкe a look at my webpage … scrub suits
scrub suits
20 Aug 25 at 4:01 pm
Very nice write-up. I definitely love this website.
Thanks!
sump pump installation
20 Aug 25 at 4:05 pm
Wow! At last I got a blog from where I can actually get useful facts concerning
my study and knowledge.
https://zrzutka.pl/profile/bmw55-login-266438
20 Aug 25 at 4:09 pm
оценка ценных бумаг москва https://ocenochnaya-kompaniya1.ru
ocenochnaya-kompaniya-166
20 Aug 25 at 4:10 pm
Kamagra oral jelly USA availability: Online sources for Kamagra in the United States – Online sources for Kamagra in the United States
RichardTit
20 Aug 25 at 4:13 pm
горшок для растений с автополивом [url=http://kashpo-s-avtopolivom-spb.ru/]горшок для растений с автополивом[/url] .
gorshok s avtopolivom_kgsr
20 Aug 25 at 4:14 pm
https://rant.li/ucydabvacubu/kupit-amfetamin-kokain-ekstazi-dubrovnik
Chriszek
20 Aug 25 at 4:14 pm
Hey I know this is off topic but I was wondering if you
knew of any widgets I could add to my blog
that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time and was
hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new
updates.
które zapiera dech w piersiach!
20 Aug 25 at 4:16 pm
plinko kz [url=www.plinko-kz2.ru]plinko kz[/url]
plinko_kz_ufer
20 Aug 25 at 4:20 pm
The main one is the ease of installation, domfenshuy.net which is achieved through a special profile.
Henrysom
20 Aug 25 at 4:20 pm
https://www.montessorijobsuk.co.uk/author/igoagyagygah/
Howardhib
20 Aug 25 at 4:22 pm
Admiring the dedication you put into your blog
and in depth information you present. It’s awesome to come across a blog every once in a while that isn’t the same out
of date rehashed information. Wonderful read! I’ve saved
your site and I’m adding your RSS feeds to my Google account.
NOHU
20 Aug 25 at 4:22 pm
fantastic put up, very informative. I ponder why the other specialists of this sector do not understand this.
You should proceed your writing. I’m sure, you’ve a
huge readers’ base already!
NorthBridge AI
20 Aug 25 at 4:23 pm
плинко [url=https://plinko3002.ru]https://plinko3002.ru[/url]
plinko_kz_zhPa
20 Aug 25 at 4:23 pm
Its like you read my mind! You appear to
know a lot 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 magnificent blog. An excellent read.
I will certainly be back.
how to clean solar panel on garden lights
20 Aug 25 at 4:25 pm
Thermal insulation of pipelines also plays a key role besttoday.org in reducing operating costs. Thanks to effective thermal insulation, heat loss is significantly reduced, which directly affects heating costs.
Nathangresk
20 Aug 25 at 4:26 pm
What’s up, this weekend is nice for me, as this occasion i am reading this enormous educational article
here at my home.
دفترچه آزمون بانک مرکزی ۱۴۰۴
20 Aug 25 at 4:29 pm
melbet apps [url=http://melbet3006.com]melbet apps[/url]
melbet_nvpa
20 Aug 25 at 4:30 pm
Hola! I’ve been following your web site for some time now and finally got
the bravery to go ahead and give you a shout out from New Caney Tx!
Just wanted to say keep up the great work!
kèo nhà cái bóng đá hôm nay
20 Aug 25 at 4:30 pm
https://pixelfed.tokyo/muffincreepecraft2
Chriszek
20 Aug 25 at 4:36 pm
Выгодные условия доступны в Казино Ramenbet слот 10000 Wonders MultiMax.
KennethWet
20 Aug 25 at 4:37 pm
When someone writes an article he/she keeps the idea of a user in his/her mind
that how a user can know it. So that’s why this article
is perfect. Thanks!
تخمین رتبه کنکور ۱۴۰۴ با معدل آپدیت 1404
20 Aug 25 at 4:38 pm
оценка станков Москва оценочные компании
ocenochnaya-kompaniya-696
20 Aug 25 at 4:44 pm
SildenaPeak [url=https://sildenapeak.com/#]SildenaPeak[/url] SildenaPeak
RobertCat
20 Aug 25 at 4:50 pm
Excellent post. I was checking constantly this blog and I’m
impressed! Very helpful information specially the last part 🙂 I care for such info
a lot. I was seeking this certain information for
a very long time. Thank you and best of luck.
ameliyati
20 Aug 25 at 4:51 pm
Hi there, after reading this amazing article i am as well happy
to share my familiarity here with colleagues.
Massey roofing Contractor Near Me
20 Aug 25 at 4:53 pm
https://www.montessorijobsuk.co.uk/author/ufkyfagig/
Chriszek
20 Aug 25 at 4:57 pm
My coder is trying to convince me to move to .net from PHP.
I have always disliked the idea because of the expenses.
But he’s tryiong none the less. I’ve been using Movable-type
on various websites for about a year and am worried about switching to another platform.
I have heard very good things about blogengine.net. Is there a way I can transfer
all my wordpress content into it? Any kind of help would be really appreciated!
keo nha cai hom nay
20 Aug 25 at 4:57 pm
салон красоты санкт петербург beauty-salon-spb.ru/
beauty-salon-909
20 Aug 25 at 4:58 pm
https://a780721025a6124ba3fd2a1278.doorkeeper.jp/
Howardhib
20 Aug 25 at 5:01 pm
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Санкт-Петербурге приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-sankt-peterburge.ru/]вывод из запоя вызов на дом[/url]
DavidVok
20 Aug 25 at 5:04 pm
Согласен с предыдущим оратором, и в дополнение хочу сказать:
Для тех, кто ищет информацию по теме “clasifieds.ru”, нашел много полезного.
Вот, делюсь ссылкой:
[url=https://clasifieds.ru]https://clasifieds.ru[/url]
Спасибо за внимание.
rusPoito
20 Aug 25 at 5:07 pm
психологи калуга взрослые
Charliesoall
20 Aug 25 at 5:08 pm
melbet казино [url=https://melbet3006.com]melbet казино[/url]
melbet_bhpa
20 Aug 25 at 5:09 pm
Затяжной запой опасен для жизни. Врачи наркологической клиники в Челябинске проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Подробнее – [url=https://vyvod-iz-zapoya-chelyabinsk12.ru/]вывод из запоя капельница в челябинске[/url]
JesseBut
20 Aug 25 at 5:15 pm
This article gives clear idea for the new viewers of blogging, that really how to do blogging and site-building.
Massey Roofing & Contracting roofing company
20 Aug 25 at 5:16 pm
https://kemono.im/yadycafecy/mikonos-kupit-kokain-mefedron-marikhuanu
Chriszek
20 Aug 25 at 5:18 pm
При таких проявлениях самостоятельное вмешательство не рекомендуется, так как это может привести к ухудшению состояния. Своевременное обращение к врачу позволит предотвратить тяжелые осложнения и эффективно стабилизировать состояние больного.
Подробнее можно узнать тут – [url=https://narcolog-na-dom-novosibirsk0.ru/]нарколог на дом недорого[/url]
ThomasReT
20 Aug 25 at 5:20 pm
Hi there all, here every person is sharing these kinds of knowledge, so it’s good to read this
weblog, and I used to pay a visit this weblog every day.
how to charge solar lights without sun
20 Aug 25 at 5:21 pm
plinko game online [url=www.plinko-kz2.ru]www.plinko-kz2.ru[/url]
plinko_kz_mwer
20 Aug 25 at 5:22 pm