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!
рейтинг seo компаний [url=www.reiting-seo-kompaniy.ru]рейтинг seo компаний[/url] .
reiting seo kompanii_pbon
2 Nov 25 at 4:55 am
safe place to order meds UK: UK online pharmacies list – legitimate pharmacy sites UK
HaroldSHems
2 Nov 25 at 4:55 am
мастбет [url=https://mostbet12034.ru/]https://mostbet12034.ru/[/url]
mostbet_kg_zbPr
2 Nov 25 at 4:56 am
trusted online pharmacy Ireland
Edmundexpon
2 Nov 25 at 4:57 am
купить диплом техникума ссср в спб [url=http://www.frei-diplom9.ru]купить диплом техникума ссср в спб[/url] .
Diplomi_haea
2 Nov 25 at 4:57 am
Excellent post. I was checking constantly this blog and I’m impressed!
Very useful information specially the last part 🙂 I care for such info
much. I was looking for this particular info for a very long time.
Thank you and best of luck.
www.exoticsouthafrica.com
2 Nov 25 at 4:58 am
mostbet казино [url=mostbet12034.ru]mostbet12034.ru[/url]
mostbet_kg_ukPr
2 Nov 25 at 4:59 am
В Ростове-на-Дону клиника «ЧСП№1» предоставляет услуги по выводу из запоя. Вы можете заказать выезд нарколога на дом или пройти лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-rostov17.ru/]наркологический вывод из запоя[/url]
Lamontdoubs
2 Nov 25 at 4:59 am
Мы предлагаем различные программы лечения в Ростове-на-Дону, включая стационарное и амбулаторное, чтобы выбрать оптимальный вариант для вас.
Подробнее тут – [url=https://vyvod-iz-zapoya-rostov238.ru/]скорая вывод из запоя в ростове-на-дону[/url]
AlbertNex
2 Nov 25 at 4:59 am
лучший seo продвижение [url=https://www.reiting-seo-agentstv.ru]https://www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_bcsa
2 Nov 25 at 4:59 am
Saya sudah mencoba banyak platform taruhan, tapi sejauh ini
KUBET adalah yang paling profesional.
Proses kubet login super cepat, membuat saya bisa langsung menikmati berbagai
permainan seru.
Situs Judi Bola Terlengkap ini benar-benar punya odds tinggi.
Selain itu, Situs Parlay Resmi dan Situs Parlay Gacor menjadi favorit saya
karena fiturnya lengkap.
Situs Mix Parlay juga tidak kalah menarik karena menawarkan kombinasi unik.
Permainan toto macau di sini juga transparan dan cocok untuk
penggemar angka.
Bagi saya, situs parlay seperti Kubet Parlay adalah tempat terbaik untuk menikmati Judi Bola
gacor dengan suasana yang seru dan profesional.
Situs Judi Bola ini benar-benar tempat terbaik untuk taruhan.
Jika kamu mencari situs terpercaya, maka KUBET adalah jawabannya!
KUBET
2 Nov 25 at 5:00 am
мелбет кыргызстан [url=https://mostbet12034.ru/]https://mostbet12034.ru/[/url]
mostbet_kg_mgPr
2 Nov 25 at 5:00 am
seo компании [url=reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo компании[/url] .
agentstvo poiskovogo prodvijeniya_ugKt
2 Nov 25 at 5:01 am
купить диплом в альметьевске [url=http://www.rudik-diplom6.ru]купить диплом в альметьевске[/url] .
Diplomi_deKr
2 Nov 25 at 5:04 am
сео компания [url=https://reiting-seo-agentstv.ru/]сео компания[/url] .
reiting seo agentstv_pjsa
2 Nov 25 at 5:04 am
online pharmacy: cheapest pharmacies in the USA – cheapest pharmacies in the USA
HaroldSHems
2 Nov 25 at 5:06 am
букмекерская. контора. мостбет. [url=https://mostbet12034.ru]https://mostbet12034.ru[/url]
mostbet_kg_qqPr
2 Nov 25 at 5:06 am
Отличная обработка от блох в доме , мастера приехали вовремя.
уничтожение рыжих тараканов
Wernermog
2 Nov 25 at 5:06 am
купить диплом техникум заочная форма обучения иркутск [url=www.frei-diplom9.ru/]купить диплом техникум заочная форма обучения иркутск[/url] .
Diplomi_yfea
2 Nov 25 at 5:08 am
топ seo компаний [url=https://reiting-seo-kompaniy.ru]топ seo компаний[/url] .
reiting seo kompanii_mdon
2 Nov 25 at 5:08 am
купить диплом с занесением в реестр казань [url=https://www.frei-diplom2.ru]https://www.frei-diplom2.ru[/url] .
Diplomi_duEa
2 Nov 25 at 5:09 am
букмекерская контора кыргызстан [url=http://mostbet12034.ru/]http://mostbet12034.ru/[/url]
mostbet_kg_gePr
2 Nov 25 at 5:09 am
топ сео сайтов [url=http://reiting-seo-agentstv.ru/]http://reiting-seo-agentstv.ru/[/url] .
reiting seo agentstv_pisa
2 Nov 25 at 5:10 am
В Ростове-на-Дону клиника «ЧСП№1» предлагает квалифицированный вывод из запоя в стационаре и на дому.
Углубиться в тему – https://vyvod-iz-zapoya-rostov18.ru/
Berryjew
2 Nov 25 at 5:10 am
https://harum888.net/kak-zaregistrirovatsya-v-melbet-oficialnyy-sayt/
JustinAcecy
2 Nov 25 at 5:10 am
мостбет официальный [url=http://mostbet12034.ru/]http://mostbet12034.ru/[/url]
mostbet_kg_yrPr
2 Nov 25 at 5:13 am
мостбет казино скачать [url=www.mostbet12034.ru]www.mostbet12034.ru[/url]
mostbet_kg_qzPr
2 Nov 25 at 5:14 am
Mikigaming |
Link Game Slot Online Paling Gacor Anti Rungkad !!!
Mikigaming
2 Nov 25 at 5:15 am
купить диплом о техническом образовании с занесением в реестр [url=http://frei-diplom2.ru/]http://frei-diplom2.ru/[/url] .
Diplomi_qsEa
2 Nov 25 at 5:16 am
Срочно нужна санобработка, тараканы достали!
дезинфекция помещений от вирусов
KennethceM
2 Nov 25 at 5:16 am
I am regular visitor, how are you everybody?
This post posted at this web page is in fact nice.
Also visit my web site :: http://www.heartoday.com
www.heartoday.com
2 Nov 25 at 5:17 am
купить диплом в уссурийске [url=www.rudik-diplom14.ru]www.rudik-diplom14.ru[/url] .
Diplomi_vsea
2 Nov 25 at 5:17 am
сео компании [url=http://www.reiting-seo-agentstv.ru]сео компании[/url] .
reiting seo agentstv_iqsa
2 Nov 25 at 5:17 am
агентство seo [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]агентство seo[/url] .
agentstvo poiskovogo prodvijeniya_jaKt
2 Nov 25 at 5:18 am
Usually I don’t learn article on blogs, however I would
like to say that this write-up very forced me to check out and do it!
Your writing taste has been amazed me. Thank
you, very nice post.
stem cell therapy for knee osteoarthritis thailand
2 Nov 25 at 5:22 am
купить диплом в рубцовске [url=www.rudik-diplom10.ru/]www.rudik-diplom10.ru/[/url] .
Diplomi_kcSa
2 Nov 25 at 5:23 am
турниры казино
WilliamShaWs
2 Nov 25 at 5:23 am
ranking seo [url=http://reiting-seo-agentstv.ru/]ranking seo[/url] .
reiting seo agentstv_rssa
2 Nov 25 at 5:24 am
рейтинг сео [url=https://reiting-seo-kompaniy.ru/]рейтинг сео[/url] .
reiting seo kompanii_qron
2 Nov 25 at 5:26 am
купить диплом техникума строительного [url=http://frei-diplom9.ru]купить диплом техникума строительного[/url] .
Diplomi_hyea
2 Nov 25 at 5:26 am
top-rated pharmacies in Ireland
Edmundexpon
2 Nov 25 at 5:31 am
compare pharmacy websites: verified online chemists in Australia – Aussie Meds Hub Australia
HaroldSHems
2 Nov 25 at 5:32 am
продвижение в топ [url=reiting-seo-agentstv.ru]продвижение в топ[/url] .
reiting seo agentstv_musa
2 Nov 25 at 5:32 am
1 x bet giri? [url=https://1xbet-giris-5.com]https://1xbet-giris-5.com[/url] .
1xbet giris_yhSa
2 Nov 25 at 5:33 am
где купить диплом техникума кого [url=http://www.frei-diplom9.ru]где купить диплом техникума кого[/url] .
Diplomi_bvea
2 Nov 25 at 5:33 am
www mostbet com [url=http://mostbet12034.ru]http://mostbet12034.ru[/url]
mostbet_kg_jjPr
2 Nov 25 at 5:34 am
мост бет букмекерская контора [url=http://mostbet12033.ru]http://mostbet12033.ru[/url]
mostbet_kg_gcpa
2 Nov 25 at 5:36 am
агентство продвижения сайтов [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]агентство продвижения сайтов[/url] .
agentstvo poiskovogo prodvijeniya_pxKt
2 Nov 25 at 5:37 am
seo рейтинг [url=www.reiting-seo-agentstv.ru/]www.reiting-seo-agentstv.ru/[/url] .
reiting seo agentstv_fysa
2 Nov 25 at 5:38 am
simply click the up coming internet page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
simply click the up coming internet page
2 Nov 25 at 5:39 am