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-diplom12.ru]купить диплом в якутске[/url] .
Diplomi_bwPi
6 Oct 25 at 6:27 pm
купить диплом с реестром [url=https://frei-diplom4.ru/]купить диплом с реестром[/url] .
Diplomi_mvOl
6 Oct 25 at 6:28 pm
В обзорной статье вы найдете собрание важных фактов и аналитики по самым разнообразным темам. Мы рассматриваем как современные исследования, так и исторические контексты, чтобы вы могли получить полное представление о предмете. Погрузитесь в мир знаний и сделайте шаг к пониманию!
Подробнее – https://quick-vyvod-iz-zapoya-1.ru/
EmilioRom
6 Oct 25 at 6:30 pm
кухни под заказ спб [url=https://kuhni-spb-1.ru]https://kuhni-spb-1.ru[/url] .
kyhni spb_ermi
6 Oct 25 at 6:30 pm
В Екатеринбурге служба Stop-Alko круглосуточно помогает вывести из запоя на дому — быстро, анонимно и без постановки на учёт.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-ekaterinburg25.ru/]www.vyvod-iz-zapoya-ekaterinburg25.ru[/url]
Wendelltag
6 Oct 25 at 6:31 pm
кухни от производителя спб [url=www.kuhni-spb-1.ru]www.kuhni-spb-1.ru[/url] .
kyhni spb_szmi
6 Oct 25 at 6:37 pm
где купить диплом о среднем образование [url=https://rudik-diplom9.ru/]где купить диплом о среднем образование[/url] .
Diplomi_nkei
6 Oct 25 at 6:38 pm
купить диплом повара [url=https://rudik-diplom13.ru]купить диплом повара[/url] .
Diplomi_loon
6 Oct 25 at 6:39 pm
кухни на заказ спб каталог [url=www.kuhni-spb-1.ru]www.kuhni-spb-1.ru[/url] .
kyhni spb_dtmi
6 Oct 25 at 6:41 pm
Clomid price [url=http://clomicareusa.com/#]Generic Clomid[/url] where to get clomid now
Davidbax
6 Oct 25 at 6:47 pm
купить диплом в химках [url=https://www.rudik-diplom13.ru]купить диплом в химках[/url] .
Diplomi_npon
6 Oct 25 at 6:49 pm
купить диплом в подольске [url=www.rudik-diplom9.ru/]купить диплом в подольске[/url] .
Diplomi_rcei
6 Oct 25 at 6:49 pm
It’s very trouble-free to find out any matter on web as compared to books, as I
found this piece of writing at this site.
bokep guru vs murid
6 Oct 25 at 6:50 pm
This is really interesting, You’re a very skilled blogger.
I have joined your rss feed and look forward to seeking more of your excellent post.
Also, I have shared your website in my social networks!
Read more
6 Oct 25 at 6:50 pm
В Краснодаре клиника «Детокс» предлагает услугу выезда нарколога на дом. Быстро, безопасно, анонимно.
Разобраться лучше – [url=https://narkolog-na-dom-krasnodar27.ru/]нарколог на дом вывод краснодар[/url]
Charlesshofe
6 Oct 25 at 6:51 pm
Joint discussions іn OMT courses build excitement ɑrοund mathematics concepts,
motivating Singapore trainees tо develop love and aster
examinations.
Prepare fоr success in upcoming examinations ѡith OMT Math Tuition’s exclusive
curriculum, created tօ cultivate vital thinking and confidence іn every trainee.
As mathematics underpins Singapore’s credibility fоr excellence іn international benchmarks like PISA, math tuition іs essential to unlocking а child’ѕ prospective and securing academic advantages іn tһis core
topic.
Tuition programs fօr primary mathematics focus
оn error analysis from past PSLE documents, teaching trainees tߋ avoid recurring errors in estimations.
Holistic advancement tһrough math tuition not ϳust boosts O Level scores yet additionally cultivates logical reasoning abilities valuable
fοr lifelong understanding.
Individualized junior college tuition helps bridge
tһe gap from O Level to A Level mathematics,
ensuring pupils adapt tо the raised rigor and deepness required.
Ꭲhe individuality οf OMT lies in its customized educational program
tһat linkѕ MOE syllabus gaps ԝith supplmentary resources lіke proprietary worksheets and services.
Тhe platform’s sources are updated regularly оne, maintaining ʏou lined
up ԝith latest curriculum fօr grade increases.
Wіtһ mathematics ƅeing a core subject tһat affеcts general scholastic streaming, tuition aids Singapore students secure fаr better qualities
ɑnd brighter future possibilities.
Аlso visit my web site … singapore math tuition
singapore math tuition
6 Oct 25 at 6:52 pm
pin up android yuklab olish [url=http://pinup5006.ru]http://pinup5006.ru[/url]
pin_up_nfKt
6 Oct 25 at 6:53 pm
Everything is very open with a very clear description of the issues.
It was really informative. Your site is very helpful.
Thanks for sharing!
FEXOVION
6 Oct 25 at 6:53 pm
I could not refrain from commenting. Very well written!
Reddit YouTube marketing case study
6 Oct 25 at 6:54 pm
Heya i’m for the primary time here. I found this board and I find
It truly helpful & it helped me out much. I am hoping to offer something again and help others like you helped me.
online casino canada
6 Oct 25 at 6:55 pm
Tightrope Game – a balance challenge with obstacles. Quick, addictive, and perfect for testing focus: Tightrope game tips and tricks
LeroyTor
6 Oct 25 at 6:56 pm
купить диплом в магадане [url=https://www.rudik-diplom9.ru]купить диплом в магадане[/url] .
Diplomi_ivei
6 Oct 25 at 6:56 pm
купить диплом в воткинске [url=www.rudik-diplom14.ru]купить диплом в воткинске[/url] .
Diplomi_ytea
6 Oct 25 at 6:57 pm
No matter if some one searches for his required thing, therefore
he/she wants to be available that in detail, so that thing is maintained over here.
hastaoda.serhatatalayevis.com
6 Oct 25 at 7:00 pm
Quality articles or reviews is the main to attract
the users to pay a quick visit the site, that’s what this web
page is providing.
online casino sign up bonus
6 Oct 25 at 7:02 pm
Tremendous issues here. I’m very satisfied to look your post.
Thanks so much and I am taking a look ahead to touch you. Will you kindly drop me a e-mail?
mitolyn
6 Oct 25 at 7:04 pm
купить диплом для техникума цена [url=http://www.frei-diplom7.ru]купить диплом для техникума цена[/url] .
Diplomi_kkei
6 Oct 25 at 7:04 pm
купить диплом с занесением в реестр в москве [url=www.frei-diplom1.ru/]купить диплом с занесением в реестр в москве[/url] .
Diplomi_gqOi
6 Oct 25 at 7:06 pm
диплом высшего образования проведенный купить [url=http://www.frei-diplom3.ru]диплом высшего образования проведенный купить[/url] .
Diplomi_fuKt
6 Oct 25 at 7:06 pm
I do agree with all of the ideas you have offered to your post.
They are really convincing and can certainly work. Still, the posts are very quick for
starters. May just you please extend them a bit from next
time? Thank you for the post.
seo
6 Oct 25 at 7:10 pm
Мы обеспечиваем быстрое и безопасное восстановление после длительного употребления алкоголя.
Углубиться в тему – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя на дому круглосуточно нижний новгород[/url]
LarryZem
6 Oct 25 at 7:13 pm
zithromax z- pak buy online: zithromax over the counter canada – generic zithromax
Glennchilt
6 Oct 25 at 7:13 pm
Thank you for the auspicious writeup. It in fact was
a amusement account it. Look advanced to more added agreeable from you!
However, how could we communicate?
buôn bán nội tạng
6 Oct 25 at 7:14 pm
купить диплом в дербенте [url=https://www.rudik-diplom14.ru]купить диплом в дербенте[/url] .
Diplomi_rxea
6 Oct 25 at 7:19 pm
где купить диплом среднем [url=rudik-diplom13.ru]где купить диплом среднем[/url] .
Diplomi_gson
6 Oct 25 at 7:20 pm
купить диплом дизайнера [url=https://rudik-diplom8.ru]купить диплом дизайнера[/url] .
Diplomi_hwMt
6 Oct 25 at 7:21 pm
купить диплом менеджера по туризму [url=www.rudik-diplom12.ru]купить диплом менеджера по туризму[/url] .
Diplomi_hyPi
6 Oct 25 at 7:21 pm
xfj222 – The design is minimalist yet effective.
Sharleen Haper
6 Oct 25 at 7:22 pm
cheap prednisone prices
where to buy prednisone prices
6 Oct 25 at 7:25 pm
mhcw3kct – The content is well-researched and thought-provoking.
Carmen Pinsonneault
6 Oct 25 at 7:26 pm
5680686 – The design is minimalist yet effective.
Booker Swoope
6 Oct 25 at 7:27 pm
5xqvk – The layout is clean and easy to navigate.
Mae Venus
6 Oct 25 at 7:27 pm
кухни на заказ петербург [url=www.kuhni-spb-1.ru/]www.kuhni-spb-1.ru/[/url] .
kyhni spb_akmi
6 Oct 25 at 7:28 pm
Hi, I would like to subscribe for this weblog to obtain newest updates, thus where can i do it please assist.
Prospero Bitspire
6 Oct 25 at 7:29 pm
These are in fact fantastic ideas in on the topic of blogging.
You have touched some fastidious factors here.
Any way keep up wrinting.
Grevial Platform Scam
6 Oct 25 at 7:29 pm
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! However, how can we communicate?
اسکیما برای بهینهسازی محتوای ویدیویی
6 Oct 25 at 7:29 pm
Hi! I’ve been following your website for a long time now and finally got
the bravery to go ahead and give you a shout out from Austin Texas!
Just wanted to say keep up the fantastic work!
nya online casino
6 Oct 25 at 7:30 pm
Wow, this paragraph is fastidious, my sister is analyzing
such things, thus I am going to let know her.
https://kjc.bike
6 Oct 25 at 7:30 pm
купить диплом колледжа с занесением в реестр [url=www.frei-diplom10.ru]купить диплом колледжа с занесением в реестр[/url] .
Diplomi_fiEa
6 Oct 25 at 7:33 pm
Asking questions are truly nice thing if you are not understanding something totally, but this article provides fastidious understanding even.
www.reddit.com
6 Oct 25 at 7:34 pm