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!
купить аттестаты 11 класс 2022 года [url=http://arus-diplom21.ru/]купить аттестаты 11 класс 2022 года[/url] .
Diplomi_bzPr
29 Aug 25 at 10:35 pm
slot gacor hari ini preman69: preman69 situs judi online 24 jam – preman69 login
Miltondep
29 Aug 25 at 10:36 pm
Приобрести диплом о высшем образовании!
Наша компания предлагаетвыгодно и быстро заказать диплом, который выполнен на оригинальном бланке и заверен мокрыми печатями, водяными знаками, подписями должностных лиц. Данный документ способен пройти лубую проверку, даже при помощи специального оборудования. Достигайте своих целей максимально быстро с нашим сервисом- [url=http://girlscools.ru/kak-proverit-kuplennyiy-diplom/]girlscools.ru/kak-proverit-kuplennyiy-diplom[/url]
Jariorjrg
29 Aug 25 at 10:37 pm
Amazing! Its truly awesome piece of writing, I have got much clear idea concerning from
this article.
Drug Rehab Marketing
29 Aug 25 at 10:38 pm
Hello, I would like to subscribe for this webpage to obtain most up-to-date
updates, therefore where can i do it please help out.
dewascatter link alternatif
29 Aug 25 at 10:39 pm
На данном этапе врач уточняет продолжительность запоя, характер употребляемого алкоголя и наличие сопутствующих заболеваний. Тщательный анализ позволяет оперативно определить оптимальную схему детоксикации и минимизировать риск осложнений.
Исследовать вопрос подробнее – [url=https://reabcentr-narko.ru/]вывод из запоя в стационаре в твери[/url]
MichaelSmurn
29 Aug 25 at 10:43 pm
mostbet az basketbol mərcləri [url=mostbet4138.ru]mostbet az basketbol mərcləri[/url]
mostbet_iqot
29 Aug 25 at 10:43 pm
Купить кокаин, мефедрон, гашиш, бошки, альфа-пвп
Darrylzer
29 Aug 25 at 10:44 pm
In longer discussions I usually skip, but what i especially appreciate how this post focuses on down-to-earth and affordable residence care. it’s motivating to see tips that anyone can follow without professional skills. i recently used some [url=https://pakstore.ru/]supportive repair ideas[/url] that worked well with these suggestions, making fixes less intimidating. it feels encouraging to know that even without special training, one can gradually build the skills needed to keep a home in better shape. it’s details like these that often get overlooked, yet they bring real improvement when applied consistently. This time I stayed and thought it adds value to the overall topic.
GeorgeCleaw
29 Aug 25 at 10:44 pm
постройка дома под ключ [url=stroitelstvo-domov-irkutsk-1.ru]stroitelstvo-domov-irkutsk-1.ru[/url] .
stroitelstvo domov irkytsk_avOr
29 Aug 25 at 10:45 pm
купить приложение к аттестату за 11 класс [url=http://arus-diplom24.ru/]купить приложение к аттестату за 11 класс[/url] .
Diplomi_nrKn
29 Aug 25 at 10:47 pm
I’m amazed, I must say. Rarely do I encounter a blog that’s equally educative and amusing, and without a
doubt, you have hit the nail on the head. The issue is something too few men and women are speaking intelligently about.
Now i’m very happy I stumbled across this during my hunt
for something regarding this.
Veltrex Core GPT
29 Aug 25 at 10:51 pm
купить аттестат за 11 класс в ярославле [url=www.arus-diplom24.ru/]купить аттестат за 11 класс в ярославле[/url] .
Diplomi_lgKn
29 Aug 25 at 10:52 pm
mostbet pul çıxarma [url=https://mostbet4136.ru]mostbet pul çıxarma[/url]
mostbet_onOn
29 Aug 25 at 10:56 pm
Hello, i think that i saw you visited my weblog thus i came to go back the desire?.I’m trying
to to find things to improve my web site!I assume its good
enough to use some of your concepts!!
check my blog
29 Aug 25 at 10:58 pm
iGenics looks like a promising supplement for eye health.
I really like that it’s made with natural ingredients aimed at supporting vision,
protecting against oxidative stress, and keeping eyes sharp as we age.
If you’re looking for something to naturally support your eyesight, iGenics
definitely seems worth checking out.
iGenics
29 Aug 25 at 10:59 pm
It’s not my first time to visit this web site, i am visiting this
website dailly and obtain fastidious data from here everyday.
no limit casinos
29 Aug 25 at 10:59 pm
купить аттестат 11 класс фото [url=https://www.arus-diplom25.ru]купить аттестат 11 класс фото[/url] .
Diplomi_qrot
29 Aug 25 at 11:00 pm
I know this web site gives quality depending content and other stuff,
is there any other web site which offers
such things in quality?
https://git.protokolla.fi/nildaagee15544/6906324/wiki/RespiClear-Sublingual-Lung-Detox-Drops:-Breathe-Easier-Naturally
29 Aug 25 at 11:01 pm
fantastic submit, very informative. I’m wondering why the
other experts of this sector don’t understand this. You must continue your writing.
I am sure, you’ve a great readers’ base already!
singapore money
29 Aug 25 at 11:05 pm
72 Fortunes demo
Wilsonlof
29 Aug 25 at 11:06 pm
ТОП ПРОДАЖИ 24/7 – ПРИОБРЕСТИ MEFEDRON (MEF) GASHISH BOSHK1
DanielVeiff
29 Aug 25 at 11:06 pm
I’m gone to say to my little brother, that he should also visit this weblog on regular basis to obtain updated
from hottest news.
HVAC repair Los Angeles CA
29 Aug 25 at 11:11 pm
вывод из запоя круглосуточно
vivod-iz-zapoya-smolensk015.ru
вывод из запоя круглосуточно
alkogolizmsmolenskNeT
29 Aug 25 at 11:13 pm
строительство дома под ключ [url=http://stroitelstvo-domov-irkutsk-1.ru/]http://stroitelstvo-domov-irkutsk-1.ru/[/url] .
stroitelstvo domov irkytsk_cbOr
29 Aug 25 at 11:15 pm
Please let me know if you’re looking for a author for
your blog. You have some really great articles and I feel I would be a good asset.
If you ever want to take some of the load off, I’d absolutely love to
write some content for your blog in exchange for a link back to mine.
Please blast me an e-mail if interested.
Kudos!
nh3limpiezas.com
29 Aug 25 at 11:15 pm
Usually I do not read article on blogs, but I would like to say that this write-up very compelled me to take a look at and do so!
Your writing taste has been surprised me. Thanks, quite nice article.
https://git.intafw.com/
29 Aug 25 at 11:16 pm
купить аттестат за 10 11 классы [url=https://arus-diplom25.ru]купить аттестат за 10 11 классы[/url] .
Diplomi_qiot
29 Aug 25 at 11:17 pm
QQ88 chính thống năm 2025, nhiều trò chơi hấp dẫn, bảo mật
an toàn, dịch vụ chuyên nghiệp.
qq 88
29 Aug 25 at 11:18 pm
book of ra deluxe: Book of Ra Deluxe slot online Italia – recensioni Book of Ra Deluxe slot
Ramonatowl
29 Aug 25 at 11:18 pm
I every time emailed this website post page to all my friends, because if like to read it
then my contacts will too.
비닉스 효과
29 Aug 25 at 11:19 pm
And kick your ailments. Guaranteed online proven methods with ibuprofen contraindications at the lowest prices anywhere on the net offered on this site ibuprofen pronunciation
Rvbdgeora
29 Aug 25 at 11:23 pm
Thank you for any other fantastic article. The place else may just anybody get that type of information in such an ideal means of writing?
I have a presentation subsequent week, and I’m on the
look for such information.
toto togel 4d
29 Aug 25 at 11:24 pm
купить аттестаты за 11 в челябинске [url=arus-diplom24.ru]купить аттестаты за 11 в челябинске[/url] .
Diplomi_tdKn
29 Aug 25 at 11:24 pm
youtube 9744
youtubenpy
29 Aug 25 at 11:27 pm
Howdy would you mind letting me know which hosting company you’re
utilizing? I’ve loaded your blog in 3 completely different internet
browsers and I must say this blog loads a lot quicker then most.
Can you suggest a good hosting provider at a reasonable price?
Thanks, I appreciate it!
Renew & Restore Roof Washing services Melbourne
29 Aug 25 at 11:28 pm
Boostaro seems like a solid option for men who want more natural support for
energy, stamina, and performance. I like that it’s made with plant-based ingredients instead of
harsh chemicals, and the fact that it also supports circulation is a
big plus. Looks like a promising supplement for overall vitality
Boostaro
29 Aug 25 at 11:29 pm
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
29 Aug 25 at 11:29 pm
Excellent beat ! I wish to apprentice whilst you amend your website, how
could i subscribe for a blog website? The account helped me a acceptable deal.
I have been a little bit familiar of this your broadcast offered vivid clear concept
my web site: nipples
nipples
29 Aug 25 at 11:29 pm
Thanks for some other informative blog. Where else may just
I get that kind of information written in such a
perfect manner? I’ve a mission that I am just now working on, and I’ve been on the glance out for such info.
кракен даркнет
29 Aug 25 at 11:30 pm
VW 108 merupakan website permainan daring resmi paling unggul
di Tanah Air dengan beragam opsi hiburan menarik serta hadiah fantastis yang akan membuatmu betah,
registrasi dan login hari ini!
vw 108
29 Aug 25 at 11:34 pm
Excellent site you have here but I was curious if you knew of any discussion boards that cover the same
topics discussed in this article? I’d really like to be a part of group where I
can get feedback from other experienced people that share the same interest.
If you have any suggestions, please let me know. Kudos!
AlphaTrize
29 Aug 25 at 11:34 pm
http://1wbook.com/# book of ra deluxe
Alfredrew
29 Aug 25 at 11:35 pm
I visit daily a few websites and sites to read articles, but this weblog presents quality based writing.
кракен онион
29 Aug 25 at 11:37 pm
Hey There. I found your blog using msn. This is a really well written article.
I will be sure to bookmark it and come back to read more of your useful info.
Thanks for the post. I will certainly comeback.
harga toto
29 Aug 25 at 11:39 pm
Мы изготавливаем дипломы любой профессии по доступным ценам. Приобретение документа, который подтверждает окончание ВУЗа, – это грамотное решение. Заказать диплом ВУЗа: [url=http://socialsmerch.com/read-blog/31073_diplom-oficialno-kupit.html/]socialsmerch.com/read-blog/31073_diplom-oficialno-kupit.html[/url]
Mazrzlp
29 Aug 25 at 11:39 pm
We’re a group of volunteers and starting a new
scheme in our community. Your website provided us with
valuable information to work on. You’ve done a formidable job and our entire community will be
thankful to you.
gitlab.ngser.com
29 Aug 25 at 11:42 pm
купить копию аттестата за 11 класс [url=http://arus-diplom24.ru]http://arus-diplom24.ru[/url] .
Diplomi_baKn
29 Aug 25 at 11:42 pm
Thank you for the good writeup. It actually was a leisure account it.
Glance complicated to far added agreeable from you! By the way, how can we keep up a correspondence?
car battery shop near
29 Aug 25 at 11:44 pm
каталог домов под ключ иркутск [url=http://stroitelstvo-domov-irkutsk-1.ru]http://stroitelstvo-domov-irkutsk-1.ru[/url] .
stroitelstvo domov irkytsk_moOr
29 Aug 25 at 11:47 pm