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=http://rudik-diplom4.ru/]купить диплом моряка[/url] .
Diplomi_rqOr
14 Oct 25 at 2:41 pm
потолки [url=http://stretch-ceilings-samara.ru]http://stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_wrkl
14 Oct 25 at 2:41 pm
Greetings! I know this is kind of off topic but I was wondering which blog platform are you using for this
site? I’m getting tired of WordPress because I’ve had
problems with hackers and I’m looking at options for another platform.
I would be great if you could point me in the direction of a good platform.
order painkillers online
14 Oct 25 at 2:42 pm
пластиковые жалюзи с электроприводом [url=http://zhalyuzi-s-elektroprivodom77.ru]http://zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_ggpa
14 Oct 25 at 2:42 pm
Je suis captive par Casinia Casino, c’est un casino en ligne qui s’eleve comme un chateau medieval. La selection du casino est une cour de plaisirs. proposant des slots de casino a theme medieval. est un virtuose de la noblesse. offrant des solutions claires et instantanees. Le processus du casino est transparent et sans trahison. neanmoins les offres du casino pourraient etre plus genereuses. Au final, Casinia Casino cadence comme une sonate de victoires pour les joueurs qui aiment parier avec panache au casino! Ajoutons la plateforme du casino brille par son style epique. enchante chaque partie avec une symphonie chevaleresque.
casinia promo code|
shadowwhirllynx2zef
14 Oct 25 at 2:42 pm
https://britmedsdirect.shop/# online pharmacy
HerbertScacy
14 Oct 25 at 2:44 pm
пластиковые жалюзи с электроприводом [url=http://zhalyuzi-s-elektroprivodom77.ru/]http://zhalyuzi-s-elektroprivodom77.ru/[/url] .
jaluzi na okna s elektroprivodom_hcpa
14 Oct 25 at 2:44 pm
Hi there, this weekend is good in favor of me, for the reason that this
point in time i am reading this fantastic informative article here at my residence.
הימורים אונליין מכונות מזל
14 Oct 25 at 2:45 pm
купить дипломы о высшем цены [url=https://rudik-diplom11.ru]купить дипломы о высшем цены[/url] .
Diplomi_feMi
14 Oct 25 at 2:46 pm
купить диплом в лениногорске [url=http://rudik-diplom8.ru]http://rudik-diplom8.ru[/url] .
Diplomi_qeMt
14 Oct 25 at 2:46 pm
потолочкин отзывы клиентов самара [url=https://natyazhnye-potolki-samara-2.ru]https://natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_vkPi
14 Oct 25 at 2:46 pm
Generally I do not learn posts on blogs, however I would like to say that this write-up very
forced me to take a look at and do it! Your writing style has surprised
me. Thank you, very nice post.|
I used to be suggested this website through my cousin. I am not certain whether
this post is written by means of him as nobody else recognises such specified information about my trouble.
You are amazing! Thank you!|
Hello there. I found your blog using msn. This is an extremely well-written article.
I’ll make sure to bookmark it and return to read more of
your useful info. Thanks for the post. I will definitely return.|
Hey there. I found your blog the use of msn. This is a really smartly written article.
I’ll make sure to bookmark it and return to learn more of your helpful info.
Thanks for the post. I’ll certainly return.|
Thanks for one’s marvelous posting! I definitely enjoyed reading it,
you may be a great author. I will be sure to bookmark
your blog and definitely will come back sometime soon. I
want to encourage you to continue your great work, have a nice afternoon!|
Hey there! I could have sworn I’ve been to this website before but after reading through some of the posts I realized it’s
new to me. Nonetheless, I’m definitely happy I found it and I’ll be
bookmarking and checking back frequently!|
Thanks in support of sharing such a pleasant thinking.
This piece of writing is nice, that’s why I have read it completely.|
Hello there and thank you for your information – I have certainly picked up something new from right here.
I did, however, experience a few technical points using
this website, since I experienced reloading the web site many
times before I could get it to load correctly. I was wondering if your web hosting is OK?
Not that I am complaining, but slow loading times often affect your
placement in Google and can damage your high-quality score if advertising and marketing with Adwords.
Anyway, I’m adding this RSS to my e-mail and could look out for a lot more of your intriguing content.
Ensure that you update this again soon.|
Wow! Finally I got a website from where I know how to actually obtain helpful data concerning
my study and knowledge.|
When someone writes an paragraph, he/she keeps the
idea of a user in mind, ensuring how a user can know it.
Thus, that’s why this post is perfect. Thanks!|
You’re so cool! I don’t believe I have read a single thing like this before.
So nice to find another person with some genuine thoughts on this subject.
Really.. thank you for starting this up. This website is
one thing that is required on the internet,
someone with a little originality!|
random video chat
14 Oct 25 at 2:47 pm
перепланировка нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/]перепланировка нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_oySr
14 Oct 25 at 2:47 pm
Топ 5273 выдающихся мыслителей zsg
recobxbpz
14 Oct 25 at 2:47 pm
экскаватор заказать цена [url=http://arenda-mini-ekskavatora-v-moskve-2.ru]экскаватор заказать цена[/url] .
arenda mini ekskavatora v moskve_bxKt
14 Oct 25 at 2:48 pm
My partner and I absolutely love your blog and find nearly all of your post’s to be exactly what I’m
looking for. Would you offer guest writers to write content available for you?
I wouldn’t mind writing a post or elaborating on a lot of
the subjects you write in relation to here. Again,
awesome weblog!
c health lebanon va
14 Oct 25 at 2:48 pm
тканевые натяжные потолки самара акции [url=http://natyazhnye-potolki-samara-1.ru/]http://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_hior
14 Oct 25 at 2:48 pm
https://www.imdb.com/list/ls4155613547/
vibukka
14 Oct 25 at 2:49 pm
диплом с реестром купить [url=frei-diplom5.ru]диплом с реестром купить[/url] .
Diplomi_ndPa
14 Oct 25 at 2:49 pm
перепланировка в нежилом здании [url=http://pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка в нежилом здании[/url] .
pereplanirovka nejilogo pomesheniya_mvKl
14 Oct 25 at 2:50 pm
натяжные потолки в самаре [url=http://natyazhnye-potolki-samara-1.ru/]http://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_xfor
14 Oct 25 at 2:51 pm
купить диплом в рубцовске [url=https://www.rudik-diplom3.ru]https://www.rudik-diplom3.ru[/url] .
Diplomi_gmei
14 Oct 25 at 2:51 pm
согласование перепланировок нежилых помещений [url=pereplanirovka-nezhilogo-pomeshcheniya10.ru]pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_pbSr
14 Oct 25 at 2:53 pm
карниз с электроприводом [url=www.karniz-shtor-elektroprivodom.ru/]карниз с электроприводом[/url] .
karniz dlya shtor s elektroprivodom_gaer
14 Oct 25 at 2:53 pm
бамбуковые электрожалюзи [url=https://zhalyuzi-s-elektroprivodom77.ru/]zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_vcpa
14 Oct 25 at 2:53 pm
мини экскаватор услуги [url=arenda-mini-ekskavatora-v-moskve-2.ru]arenda-mini-ekskavatora-v-moskve-2.ru[/url] .
arenda mini ekskavatora v moskve_aeKt
14 Oct 25 at 2:53 pm
Hi all, here every person is sharing these knowledge,
so it’s good to read this web site, and I used to pay a quick visit this
website everyday.
Hobicode
14 Oct 25 at 2:53 pm
согласование перепланировки нежилого помещения в нежилом здании [url=www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_caSr
14 Oct 25 at 2:54 pm
J’ai un engouement sincere pour Locowin Casino, ca transporte dans un univers envoutant. La diversite des titres est epoustouflante, proposant des jeux de table immersifs. Pour un lancement puissant. Le service est operationnel 24/7, proposant des reponses limpides. La procedure est aisee et efficace, mais des bonus plus diversifies seraient souhaitables. En synthese, Locowin Casino est une plateforme qui excelle pour les adeptes de sensations intenses ! A mentionner la navigation est simple et engageante, stimule le desir de revenir. Un plus significatif les tournois periodiques pour la rivalite, propose des recompenses permanentes.
Commencer Г explorer|
EchoVortexE3zef
14 Oct 25 at 2:55 pm
купить диплом в уссурийске [url=http://rudik-diplom4.ru/]http://rudik-diplom4.ru/[/url] .
Diplomi_niOr
14 Oct 25 at 2:55 pm
взять в аренду мини экскаватор [url=http://arenda-mini-ekskavatora-v-moskve-2.ru]взять в аренду мини экскаватор[/url] .
arenda mini ekskavatora v moskve_jwKt
14 Oct 25 at 2:55 pm
потолочкин потолки натяжные [url=stretch-ceilings-samara.ru]stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_wfkl
14 Oct 25 at 2:56 pm
I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.
официальный сайт Dragon Money
StephenGlona
14 Oct 25 at 2:57 pm
электрокарнизы для штор купить в москве [url=https://elektrokarnizy797.ru/]elektrokarnizy797.ru[/url] .
elektrokarnizi_myMl
14 Oct 25 at 2:57 pm
сайт фитнес клуба https://fitnes-klub-msk.ru
fitnes-klub-645
14 Oct 25 at 2:58 pm
купить диплом в салавате [url=http://www.rudik-diplom13.ru]купить диплом в салавате[/url] .
Diplomi_jdon
14 Oct 25 at 2:58 pm
Hi, јust wanted to sɑy, I loved this blog post.
It was funny. Keeep on posting!
Guest house in Karachi
14 Oct 25 at 2:58 pm
переустройство нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_hzKl
14 Oct 25 at 3:00 pm
https://www.imdb.com/list/ls4155601491/
aewgttx
14 Oct 25 at 3:00 pm
купить диплом в канске [url=http://rudik-diplom4.ru]купить диплом в канске[/url] .
Diplomi_jrOr
14 Oct 25 at 3:02 pm
купить диплом средне техническое [url=www.rudik-diplom3.ru/]купить диплом средне техническое[/url] .
Diplomi_lpei
14 Oct 25 at 3:02 pm
купить диплом бакалавра [url=rudik-diplom8.ru]купить диплом бакалавра[/url] .
Diplomi_rcMt
14 Oct 25 at 3:03 pm
порядок согласования перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/[/url] .
pereplanirovka nejilogo pomesheniya_obSr
14 Oct 25 at 3:04 pm
натяжные потолки потолочкин отзывы самара [url=http://www.natyazhnye-potolki-samara-1.ru]http://www.natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_tkor
14 Oct 25 at 3:05 pm
После стабилизации состояния пациенту предлагается пройти этап реабилитации. В клинике он может занять от 30 до 180 дней, в зависимости от тяжести зависимости, стажа употребления и социальной ситуации. Реабилитационный блок построен по принципам когнитивной реструктуризации: меняются привычные модели мышления, формируются новые способы реагирования на стресс, прорабатываются неразрешённые психологические конфликты. Используются методы психодрамы, арт-терапии, телесно-ориентированной терапии и даже нейропсихологической гимнастики.
Получить дополнительные сведения – [url=https://lechenie-narkomanii-samara0.ru/]лечение наркомании на дому[/url]
Richardcoern
14 Oct 25 at 3:05 pm
аренда мини экскаватора [url=http://arenda-mini-ekskavatora-v-moskve-2.ru]аренда мини экскаватора[/url] .
arenda mini ekskavatora v moskve_sdKt
14 Oct 25 at 3:05 pm
купить диплом техникума легко пять плюс [url=https://frei-diplom12.ru/]купить диплом техникума легко пять плюс[/url] .
Diplomi_wtPt
14 Oct 25 at 3:05 pm
карниз с приводом [url=https://karniz-shtor-elektroprivodom.ru/]karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_sxer
14 Oct 25 at 3:07 pm
Все обращения в клинику «РеабКузбасс» обрабатываются в рамках строгой анонимности. Пациент может проходить лечение без паспорта, под вымышленным именем, если это важно для психологического комфорта. Ни одна медицинская процедура или консультация не фиксируется в государственных базах без согласия. Персонал подписывает документы о неразглашении. Также предлагается анонимная оплата и оформление без упоминания диагноза в документах. При необходимости пациент может получить справку с нейтральной формулировкой для работы или страховой компании.
Получить больше информации – [url=https://lechenie-narkomanii-novokuzneczk0.ru/]лечение алкоголизма и наркомании центр в новокузнецке[/url]
Johnnyjab
14 Oct 25 at 3:07 pm
потолочкин натяжные потолки отзывы [url=https://www.stretch-ceilings-samara-1.ru]потолочкин натяжные потолки отзывы[/url] .
natyajnie potolki samara_eesl
14 Oct 25 at 3:09 pm