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://natyazhnye-potolki-lipeck-1.ru]тканевый натяжной потолок[/url] .
natyajnie potolki_zmol
10 Sep 25 at 5:37 am
nexus shop url nexus darknet shop nexus onion mirror [url=https://darkmarketsdirectory.com/ ]darkmarket url [/url]
BrianWeX
10 Sep 25 at 5:39 am
да мэн правильно говоришь KEY фраернулся
https://2a6255350b87fa16553b58fbe0.doorkeeper.jp/
Кстати,что очень радует ,так это уровень общения продавца.Юмор лишним не бывает,ведь так:D?
Harrysem
10 Sep 25 at 5:41 am
установить кондиционер в квартире цена [url=www.kondicioner-obninsk-1.ru/]установить кондиционер в квартире цена[/url] .
kondicioneri s ystanovkoi_twmi
10 Sep 25 at 5:42 am
Je trouve absolument enivrant PokerStars Casino, on dirait un ciel etoile de sensations. Les options de jeu au casino sont riches et palpitantes, proposant des slots de casino a theme audacieux. Le personnel du casino offre un accompagnement digne d’un croupier d’elite, offrant des solutions claires et immediates. Les retraits au casino sont rapides comme une donne gagnante, quand meme j’aimerais plus de promotions de casino qui eblouissent. En somme, PokerStars Casino offre une experience de casino palpitante pour les joueurs qui aiment parier avec flair au casino ! En plus la plateforme du casino brille par son style audacieux, facilite une experience de casino strategique.
pokerstars open|
zestysquid7zef
10 Sep 25 at 5:42 am
If you would like to obtain much from this piece of writing then you have to apply such
techniques to your won blog.
TikTok Downloader
10 Sep 25 at 5:44 am
https://meditrustuk.shop/# MediTrust
Miltonbus
10 Sep 25 at 5:44 am
Наркологическая клиника «МедЛайн» предоставляет профессиональные услуги врача-нарколога с выездом на дом в Новосибирске и Новосибирской области. Мы оперативно помогаем пациентам справиться с тяжелыми состояниями при алкогольной и наркотической зависимости. Экстренный выезд наших специалистов доступен круглосуточно, а лечение проводится с применением проверенных методик и препаратов, что гарантирует безопасность и конфиденциальность каждому пациенту.
Детальнее – [url=https://narcolog-na-dom-novosibirsk00.ru/]запой нарколог на дом в новосибирске[/url]
Donaldsic
10 Sep 25 at 5:45 am
авиатор на деньги [url=https://aviator-igra-2.ru/]авиатор на деньги[/url] .
aviator igra_mqol
10 Sep 25 at 5:46 am
глянцевый натяжной потолок [url=http://natyazhnye-potolki-lipeck-1.ru]глянцевый натяжной потолок[/url] .
natyajnie potolki_kmol
10 Sep 25 at 5:48 am
Когда следует немедленно обращаться за помощью:
Получить дополнительную информацию – [url=https://narcolog-na-dom-novokuznetsk0.ru/]нарколог на дом вывод из запоя[/url]
MelvinZem
10 Sep 25 at 5:50 am
домашний кондиционер цена [url=http://kondicioner-obninsk-1.ru]домашний кондиционер цена[/url] .
kondicioneri s ystanovkoi_fvmi
10 Sep 25 at 5:50 am
купить диплом с реестром [url=www.educ-ua14.ru]купить диплом с реестром[/url] .
Diplomi_pckl
10 Sep 25 at 5:52 am
авиатор игра 1вин [url=https://aviator-igra-2.ru/]авиатор игра 1вин[/url] .
aviator igra_xfol
10 Sep 25 at 5:52 am
Howdy! This post could not be written much better!
Going through this post reminds me of my previous roommate!
He continually kept talking about this. I will send
this post to him. Pretty sure he will have a great read.
Thanks for sharing!
situs slot dana
10 Sep 25 at 5:53 am
Terrific work! That is the kind of info that are meant
to be shared across the net. Disgrace on the seek engines for now not positioning this publish upper!
Come on over and visit my web site . Thanks =)
buôn bán nội tạng
10 Sep 25 at 5:54 am
цена кв м натяжного потолка [url=http://natyazhnye-potolki-lipeck-1.ru]http://natyazhnye-potolki-lipeck-1.ru[/url] .
natyajnie potolki_vxol
10 Sep 25 at 5:55 am
plane crash money game [url=www.aviator-igra-3.ru/]www.aviator-igra-3.ru/[/url] .
aviator igra_xkmi
10 Sep 25 at 5:57 am
It’s great that you are getting thoughts from this post as well as from our argument made
at this time.
Look at my website ACL tear treatment Florida
ACL tear treatment Florida
10 Sep 25 at 6:00 am
Ищете источник ежедневной мотивации заботиться о себе? На «Здоровье и гармония» вы найдете простые советы по красоте, здоровью и психологии, чтобы жить легче и радостнее. Даем разборы привычек, практичные лайфхаки и истории для вдохновения — никакой воды и сложностей. Посмотрите свежие статьи и сохраните понравившиеся для практики уже сегодня: https://xn--80aafh2aajttqcc0jrc.xn--p1ai/ Начните с маленьких шагов — результаты удивят, а экспертные материалы помогут удержать курс.
NisipScusa
10 Sep 25 at 6:04 am
Урал и Chemical продукт знают как сделать грязно
https://www.divephotoguide.com/user/wydedkyyhd
Магази лутший на рц не первый раз работаем с ним!) удачи и процветания!)
Harrysem
10 Sep 25 at 6:05 am
установка кондиционера на фасад дома [url=www.kondicioner-obninsk-1.ru]установка кондиционера на фасад дома[/url] .
kondicioneri s ystanovkoi_mimi
10 Sep 25 at 6:05 am
установка натяжных потолков под ключ [url=natyazhnye-potolki-lipeck-1.ru]установка натяжных потолков под ключ[/url] .
natyajnie potolki_xfol
10 Sep 25 at 6:07 am
aviator игра на деньги [url=www.aviator-igra-3.ru/]aviator игра на деньги[/url] .
aviator igra_qami
10 Sep 25 at 6:08 am
tor drug market dark market link nexus url [url=https://darknetmarketgate.com/ ]darknet market lists [/url]
DwayneAricE
10 Sep 25 at 6:11 am
Very nice post. I just stumbled upon your weblog and wished to say that I
have really enjoyed surfing around your blog posts.
After all I’ll be subscribing to your feed and I hope you write
again very soon!
site
10 Sep 25 at 6:12 am
где купить натяжной потолок [url=https://www.natyazhnye-potolki-lipeck-1.ru]где купить натяжной потолок[/url] .
natyajnie potolki_lbol
10 Sep 25 at 6:16 am
IntimaCare UK [url=https://intimacareuk.com/#]buy ED pills online discreetly UK[/url] tadalafil generic alternative UK
Albertmoone
10 Sep 25 at 6:17 am
Вот почему TorgVsem помогает продавать быстрее: публикуйте объявления бесплатно, привлекайте покупателей из всех регионов и выходите на сделку без лишней бюрократии. На площадке удобная рубрикация и умный поиск, поэтому ваши товары не потеряются среди конкурентов, а покупатели быстро их находят. Переходите на https://torgvsem.ru/ и начните размещать объявления уже сегодня — от недвижимости и транспорта до работы, услуг и товаров для дома. Публикуйте сколько нужно и обновляйте позиции за секунды — так вы экономите время и получаете больше откликов.
Qeguqbrerm
10 Sep 25 at 6:19 am
After looking at a number of the blog articles on your web page,
I really like your way of blogging. I saved as a favorite it to my bookmark site
list and will be checking back in the near future. Please check out my website as
well and tell me your opinion.
home addition contractors service
10 Sep 25 at 6:20 am
You’re so interesting! I don’t suppose I’ve read anything like that before.
So great to discover another person with unique thoughts on this
subject matter. Really.. thank you for starting this up.
This site is something that’s needed on the web, someone
with a bit of originality!
online casino bonus
10 Sep 25 at 6:20 am
купить диплом в екатеринбург реестр [url=www.sumkin.ru/forum/member.php?u=53890]купить диплом в екатеринбург реестр[/url] .
Zakazat diplom lubogo instityta!_xjkt
10 Sep 25 at 6:21 am
MediTrustUK [url=https://meditrustuk.com/#]MediTrust UK[/url] MediTrustUK
Albertmoone
10 Sep 25 at 6:25 am
онлайн игра авиатор [url=www.aviator-igra-3.ru/]онлайн игра авиатор[/url] .
aviator igra_yjmi
10 Sep 25 at 6:26 am
купить диплом занесением реестр [url=http://educ-ua14.ru/]купить диплом занесением реестр[/url] .
Diplomi_fgkl
10 Sep 25 at 6:28 am
wonderful points altogether, you just won a logo new reader.
What might you suggest in regards to your publish
that you simply made some days ago? Any positive?
Alto Bitrow
10 Sep 25 at 6:29 am
Заявление про кидал не требует обоснования, ибо это не заявление. Перечитайте внимательно. Считаю, что такие речи тоже стоит оставлять при себе, не прочитав толком.
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%93%D0%BE%D0%B6%D1%83%D0%B2-%D0%92%D0%B5%D0%BB%D1%8C%D0%BA%D0%BE%D0%BF%D0%BE%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9/
Просьба не флудить. Руж тем более не развивать больные фантазии.
Harrysem
10 Sep 25 at 6:29 am
I really like your blog.. very nice colors & theme.
Did you make this website yourself or did you hire someone to do it for you?
Plz reply as I’m looking to construct my own blog and would like
to find out where u got this from. thanks a lot
nfs199.xyz
10 Sep 25 at 6:30 am
Группа препаратов
Разобраться лучше – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod00.ru/]врач на дом капельница от запоя нижний новгород[/url]
Ulyssesemuby
10 Sep 25 at 6:30 am
авиатор игра 1хбет [url=https://aviator-igra-3.ru]авиатор игра 1хбет[/url] .
aviator igra_znmi
10 Sep 25 at 6:32 am
Хотите узнать, где срочно сделать медицинскую книжку в течение суток без толкучки и проблем? На сайте [url=https://medraskhodka.ru/]https://medraskhodka.ru/[/url] медкнижку оформят или продлят оперативно: с анализами и заключением терапевта — даже онлайн. Услуга актуальна для специалистов пищевой промышленности, сферы обслуживания и учреждений, где требуются медосмотры и аттестация. Оформление займёт минимум времени, а стоимость честная и понятная (от 1 600 ?, обновление с 1 300 ?). Узнайте подробности — оформление за сутки, онлайн оформление, без проблем.
Spravkivbk
10 Sep 25 at 6:33 am
монтаж натяжных потолков в липецке [url=https://natyazhnye-potolki-lipeck-1.ru/]natyazhnye-potolki-lipeck-1.ru[/url] .
natyajnie potolki_qjol
10 Sep 25 at 6:36 am
Undeniably consider that which you stated. Your favorite justification seemed to be at the web the
easiest thing to be mindful of. I say to you, I definitely get annoyed at the same time
as other folks think about concerns that they plainly don’t
realize about. You managed to hit the nail upon the
top and also outlined out the whole thing with no need side effect ,
other people can take a signal. Will probably be again to get more.
Thank you
A Perfect Finish painting service near me
10 Sep 25 at 6:36 am
Срочный вызов врача на дом необходим при появлении следующих симптомов:
Детальнее – [url=https://narcolog-na-dom-nnovgorod8.ru/]нарколог на дом недорого[/url]
KevinPow
10 Sep 25 at 6:37 am
купить диплом о высшем образовании реестр [url=educ-ua14.ru]купить диплом о высшем образовании реестр[/url] .
Diplomi_ejkl
10 Sep 25 at 6:37 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Ознакомиться с деталями – https://kmzic.com/industry
Caseyfuh
10 Sep 25 at 6:39 am
What i don’t realize is in fact how you’re not really much more neatly-preferred than you might be right
now. You are so intelligent. You realize therefore
considerably when it comes to this subject, produced me personally consider it from numerous various angles.
Its like men and women don’t seem to be interested except it is one
thing to accomplish with Woman gaga! Your own stuffs outstanding.
At all times deal with it up!
Here is my web page; 청담쩜오
청담쩜오
10 Sep 25 at 6:40 am
It’s hard to find educated people about this subject, however,
you seem like you know what you’re talking about! Thanks
Review my blog … Niagara Falls Tours from Toronto
Niagara Falls Tours from Toronto
10 Sep 25 at 6:40 am
I like this site — clear and packed with great stuff.
Glory casino app download
Glory casino app download
10 Sep 25 at 6:42 am
darknet market list dark web marketplaces dark web market links [url=https://darknetmarketgate.com/ ]dark web marketplaces [/url]
DwayneAricE
10 Sep 25 at 6:43 am