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://aviator-igra-1.ru/]http://aviator-igra-1.ru/[/url] .
aviator igra_cyOn
11 Sep 25 at 1:50 pm
перепланировка помещения [url=https://www.soglasovanie-pereplanirovki-kvartiry17.ru]перепланировка помещения[/url] .
soglasovanie pereplanirovki kvartiri _jkol
11 Sep 25 at 1:51 pm
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Что ещё нужно знать? – https://falconsindia.com/tyre-changer-installation-at-bsf-gandhinagar
DonaldVab
11 Sep 25 at 1:51 pm
When someone writes an paragraph he/she keeps the thought of a user in his/her mind that how a user can be aware
of it. Therefore that’s why this post is outstdanding.
Thanks!
시알리스세일구매
11 Sep 25 at 1:52 pm
Драгон Мани – платформа для азартных игр с турнирами, слотами и быстрыми призами. Идеально для тех, кто ценит простоту и драйв!
dragon money
драгон мани официальный сайт
11 Sep 25 at 1:53 pm
Explore Kaizenaire.ϲom for Singapore’s ƅеѕt-curated promotions аnd
unsurpassable shopping deals.
Constantly on sharp fⲟr deals, Singaporeans embody Singapore’ѕ spirit as a shopping hаᴠen.
Singaporeans liкe bubble tea ҝeeps up friends ɑfter ѡork, and remember tо
гemain upgraded on Singapore’s most current promotions аnd shopping deals.
The Closet Lover ρrovides budget friendly stylish apparel, preferred
Ƅy budget-conscious fashionistas iin Singapore for
theiг regular updates.
Shopee, a leading ecommerce ѕystem ѕia, sells whatever frоm gadgets
tо groceries lah, cherished ƅy Singaporeans fߋr іts flash sales andd սser-friendly application lor.
Оld Chang Kee pleases cravings ᴡith curry puffs аnd snacks, favored Ьү Singaporeans for theіr crunchy, flavorful attacks excellent for on-the-gochomping.
Auntie love leh, Kaizenaire.ϲom’s shopping discount rates ᧐ne.
My blog … electricity provider promotions
electricity provider promotions
11 Sep 25 at 1:54 pm
авиатор игра 1хбет [url=https://aviator-igra-1.ru/]авиатор игра 1хбет[/url] .
aviator igra_sqOn
11 Sep 25 at 1:55 pm
IntimaCare UK [url=http://intimacareuk.com/#]IntimaCareUK[/url] weekend pill UK online pharmacy
Albertmoone
11 Sep 25 at 1:56 pm
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Подробнее – https://thewebcrawlers.com/dr-vinti-ayurvedika-clinic-logo-design-sample
MiguelDwero
11 Sep 25 at 1:56 pm
darknet market list dark websites darkmarket [url=https://darkmarketslegion.com/ ]dark web market list [/url]
DwayneAricE
11 Sep 25 at 2:00 pm
Just wish to say your article is as surprising. The clarity to your submit is just nice and i could suppose you’re knowledgeable on this subject.
Fine together with your permission let me to grab your RSS feed to
keep updated with impending post. Thank you a million and please keep up the enjoyable
work.
fish it script
11 Sep 25 at 2:01 pm
Казино X слот Bonanza Billion
EdwardTix
11 Sep 25 at 2:01 pm
aeroplane game money [url=http://www.aviator-igra-1.ru]http://www.aviator-igra-1.ru[/url] .
aviator igra_bsOn
11 Sep 25 at 2:01 pm
Appreciate it. Building on this, my take: ;
https://bbrbetbr.Top/,.
https://bbrbetbr.Top/
11 Sep 25 at 2:02 pm
Come in – don’t miss the latest: https://www.radio-rfe.com
Agustinbeike
11 Sep 25 at 2:03 pm
Only we have the newest materials: https://jnp.chitkara.edu.in
Jamesbar
11 Sep 25 at 2:04 pm
клиенты знают нас и нашу работу [url=https://soglasovanie-pereplanirovki-kvartiry17.ru/]https://soglasovanie-pereplanirovki-kvartiry17.ru/[/url] .
soglasovanie pereplanirovki kvartiri _jool
11 Sep 25 at 2:04 pm
Always relevant information: https://agriness.com
MarioHex
11 Sep 25 at 2:06 pm
Information that is always relevant: https://billi-walker.jp
CharlesSusip
11 Sep 25 at 2:09 pm
Link exchange is nothing else but it is simply placing the
other person’s blog link on your page at proper place and other person will
also do similar in support of you.
best crypto casinos germany
11 Sep 25 at 2:09 pm
перепланировка офиса согласование [url=https://soglasovanie-pereplanirovki-kvartiry17.ru/]https://soglasovanie-pereplanirovki-kvartiry17.ru/[/url] .
soglasovanie pereplanirovki kvartiri _ovol
11 Sep 25 at 2:10 pm
Купить диплом колледжа в Луганск [url=www.educ-ua6.ru/]Купить диплом колледжа в Луганск[/url] .
Diplomi_ecMl
11 Sep 25 at 2:11 pm
магазу процветания желаю и клиентов хороших и честных!
https://kemono.im/eodreegti/kak-naiti-sait-chtoby-kupit-narkotiki
классный магазин, была впечатлянна скоростью доставки и качествомтовара)) всем пис
EmileScaks
11 Sep 25 at 2:14 pm
компании занимащиеся офицально перепланировками квартир [url=https://soglasovanie-pereplanirovki-kvartiry17.ru]https://soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _iiol
11 Sep 25 at 2:16 pm
купить диплом легальный [url=https://educ-ua12.ru]купить диплом легальный[/url] .
Diplomi_rtMt
11 Sep 25 at 2:18 pm
Very descriptive post, I enjoyed that a lot. Will there be a part 2?
My site – Colorful x Splash x Splatter x Paint x Brush Strokes x Artistic x Art x Colors Multifunctional Diaper Backpack
Colorful x Splash x Splatter x Paint x Brush Strokes x Artistic x Art x Colors Multifunctional Diaper Backpack
11 Sep 25 at 2:18 pm
Нужна, где заказать санитарную книжку в городе Пермь официально и без бюрократии? На [url=https://klinika-zdorovya-no1.ru]https://klinika-zdorovya-no1.ru[/url] можно оформить санитарную книжку всего за 1700 ? или продлить действующую — по цене от 1000 ?. Книжки подлинные и легальные, привезём документ курьером к вам домой. Всё удобно: передать нужные данные онлайн, внести оплату и ждать доставку — без посещения поликлиники и ожидания. Все подробности — санитарная книжка Пермь, оформление без очередей, выгодное продление.
Spravkinxa
11 Sep 25 at 2:19 pm
Драгон Мани – платформа для азартных игр с турнирами, слотами и быстрыми призами. Идеально для тех, кто ценит простоту и драйв!
драгон мани официальный сайт
драгон мани официальный сайт
11 Sep 25 at 2:19 pm
Greetings! I know this is kinda off topic nevertheless I’d
figured I’d ask. Would you be interested in trading links or
maybe guest writing a blog post or vice-versa? My website addresses a lot of the same subjects as yours and
I believe we could greatly benefit from each other.
If you happen to be interested feel free to send me an email.
I look forward to hearing from you! Fantastic blog by the way!
ฮานอย
11 Sep 25 at 2:24 pm
самолетик казино [url=www.aviator-igra-1.ru]www.aviator-igra-1.ru[/url] .
aviator igra_ebOn
11 Sep 25 at 2:25 pm
I was very pleased to discover this page. I need to to
thank you for your time due to this fantastic read!! I
definitely savored every part of it and I have you saved as a favorite to
see new stuff in your blog.
Here is my site; 70BET
70BET
11 Sep 25 at 2:26 pm
Казино Mostbet слот Book of Sun Choice
Rupertnurne
11 Sep 25 at 2:27 pm
Драгон Мани – платформа для азартных игр с турнирами, слотами и быстрыми призами. Идеально для тех, кто ценит простоту и драйв!
dragon money
https://poletlipetsk.ru/
11 Sep 25 at 2:27 pm
aviator игра на деньги [url=http://www.aviator-igra-1.ru]aviator игра на деньги[/url] .
aviator igra_mwOn
11 Sep 25 at 2:32 pm
Купить диплом колледжа в Ивано-Франковск [url=http://educ-ua6.ru/]Купить диплом колледжа в Ивано-Франковск[/url] .
Diplomi_yfMl
11 Sep 25 at 2:34 pm
nexus market darknet darknet market list nexus market link [url=https://darknetmarketseasy.com/ ]nexus onion [/url]
BrianWeX
11 Sep 25 at 2:34 pm
aviator игра официальный сайт [url=http://aviator-igra-1.ru/]aviator игра официальный сайт[/url] .
aviator igra_weOn
11 Sep 25 at 2:35 pm
jugar aviator [url=https://www.aviator-igra-4.ru]https://www.aviator-igra-4.ru[/url] .
aviator igra_xypr
11 Sep 25 at 2:36 pm
I’m not sure why but this blog is loading extremely slow for me.
Is anyone else having this problem or is it a issue on my end?
I’ll check back later on and see if the problem still exists.
Klik disini
11 Sep 25 at 2:38 pm
лучший магаз берите все!!!!, все порешали вина не магазина. просто красавец!!!
https://rant.li/efahyiduigec/kupit-boshki-chita
а теперь представь что тебе таким макаром в сутки пишут десятки человек. большая часть с вопросами аля “как это бодяжить” и “чо это за хрень и как прёт”. + ко всему заказы.
MerleDiolf
11 Sep 25 at 2:38 pm
1win ставки скачать [url=http://1win12003.ru]1win ставки скачать[/url]
1win_pqoi
11 Sep 25 at 2:39 pm
скачать 1win официальный сайт [url=https://www.1win12003.ru]https://www.1win12003.ru[/url]
1win_uvoi
11 Sep 25 at 2:40 pm
Pokud hledáte online casino cz, cz casino online nebo kasina, jste na správném místě. Jsem žurnalista a pomohu vám srovnat rizika i možnosti českého online hazardu – stylově, seriózně a uživatelsky přívětivě: online casino cz
LarryHeady
11 Sep 25 at 2:41 pm
контора 1 вин [url=https://www.1win12003.ru]контора 1 вин[/url]
1win_mtoi
11 Sep 25 at 2:41 pm
букмекерская контора mostbet [url=mostbet12004.ru]mostbet12004.ru[/url]
mostbet_huOt
11 Sep 25 at 2:44 pm
подготовка проекта перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry8.ru/]https://proekt-pereplanirovki-kvartiry8.ru/[/url] .
proekt pereplanirovki kvartiri_qmMl
11 Sep 25 at 2:47 pm
Magnificent web site. Lots of useful information here. I am sending it to some friends ans also sharing
in delicious. And of course, thanks in your sweat!
23win
11 Sep 25 at 2:48 pm
Казино Leonbets слот Book of Plenty
Robertcok
11 Sep 25 at 2:48 pm
Normally I do not learn article on blogs, but I wish to say that this write-up
very compelled me to try and do it! Your writing taste has
been amazed me. Thank you, very nice article.
AI Funny Video Generator;Funny Video Generator
11 Sep 25 at 2:51 pm
купить диплом высшего образования с занесением в реестр [url=https://www.educ-ua12.ru]купить диплом высшего образования с занесением в реестр[/url] .
Diplomi_btMt
11 Sep 25 at 2:52 pm