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://www.narkologicheskaya-klinika-11.ru]http://www.narkologicheskaya-klinika-11.ru[/url] .
narkologicheskaya klinika_adPn
7 Sep 25 at 11:17 am
маркетинговые стратегии статьи [url=blog-o-marketinge1.ru]маркетинговые стратегии статьи[/url] .
blog o marketinge_nssa
7 Sep 25 at 11:18 am
наркология лечение [url=https://www.narkologicheskaya-klinika-11.ru]https://www.narkologicheskaya-klinika-11.ru[/url] .
narkologicheskaya klinika_dkPn
7 Sep 25 at 11:20 am
купить диплом о техническом образовании с занесением в реестр [url=www.ransis.org/index.php?name=Account&op=info&uname=iliaanisimov]www.ransis.org/index.php?name=Account&op=info&uname=iliaanisimov[/url] .
Zakazat diplom o visshem obrazovanii!_cmkt
7 Sep 25 at 11:20 am
Heya i’m for the primary time here. I came across this board and I
to find It really helpful & it helped me out
a lot. I hope to provide something again and aid others like you helped
me.
kliknij tutaj
7 Sep 25 at 11:23 am
больница наркологическая [url=www.narkologicheskaya-klinika-11.ru/]www.narkologicheskaya-klinika-11.ru/[/url] .
narkologicheskaya klinika_yuPn
7 Sep 25 at 11:23 am
скачать мостбет кг [url=http://mostbet4160.ru]http://mostbet4160.ru[/url]
mostbet_alot
7 Sep 25 at 11:24 am
Нужна медицинскую книжку сегодня по городу недорого? В медицинском центре [url=https://hearth-health.ru]https://hearth-health.ru[/url] можно быстро оформить новую медкнижку от 1 200 ?, продлить существующую по цене от 1 800 ? или получить медицинский документ по цене 1 000 ?, включая сдачу анализов по цене 500 ?. Всё — легально, по всем правилам и без лишних забот. Удобный режим работы, можно подать заявку онлайн и забрать справки быстро. Подробнее на сайте — медкнижка срочно, онлайн заказ, справка по низкой цене.
Spravkielq
7 Sep 25 at 11:24 am
Hello, just wanted to say, I liked this article. It was practical.
Keep on posting!
P.C.
7 Sep 25 at 11:25 am
наркологическая больница [url=http://narkologicheskaya-klinika-12.ru]http://narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_hmMn
7 Sep 25 at 11:25 am
ск домстрой [url=http://stroitelstvo-domov-irkutsk-2.ru/]http://stroitelstvo-domov-irkutsk-2.ru/[/url] .
stroitelstvo domov irkytsk_kjOi
7 Sep 25 at 11:25 am
Заказать диплом ВУЗа!
Наши специалисты предлагаютвыгодно и быстро приобрести диплом, который выполняется на оригинальном бланке и заверен печатями, водяными знаками, подписями. Наш диплом пройдет лубую проверку, даже с применением специальных приборов. Решайте свои задачи максимально быстро с нашими дипломами- [url=http://lada-xray.net/member.php?u=2434/]lada-xray.net/member.php?u=2434[/url]
Jariorzcr
7 Sep 25 at 11:26 am
Получить диплом ВУЗа поспособствуем. Куплю диплом: цены на документы – [url=http://diplomybox.com/tseny-na-dokumenty/]diplomybox.com/tseny-na-dokumenty[/url]
Cazriiw
7 Sep 25 at 11:28 am
https://sorvachev.com/code/pages/koncepciya_preventivnoy_voyny_vo_vneshney_politike.html
https://sorvachev.com/code/pages/koncepciya_preventivnoy_voyny_vo_vneshney_politike.html
7 Sep 25 at 11:28 am
анонимная наркологическая клиника [url=http://narkologicheskaya-klinika-12.ru]http://narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_qiMn
7 Sep 25 at 11:28 am
купить диплом в черкассах [url=www.educ-ua4.ru/]www.educ-ua4.ru/[/url] .
Diplomi_puPl
7 Sep 25 at 11:29 am
best darknet markets darkmarket url darknet sites [url=https://darknetmarketstore.com/ ]dark web market [/url]
Jamespem
7 Sep 25 at 11:29 am
darknet markets darknet markets onion dark web market list [url=https://darknetmarketsgate.com/ ]dark market 2025 [/url]
Donaldfup
7 Sep 25 at 11:30 am
клиники наркологические [url=https://www.narkologicheskaya-klinika-12.ru]https://www.narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_phMn
7 Sep 25 at 11:31 am
мосвет казино [url=mostbet4158.ru]mostbet4158.ru[/url]
mostbet_xoEn
7 Sep 25 at 11:31 am
номер наркологии [url=www.narkologicheskaya-klinika-11.ru/]www.narkologicheskaya-klinika-11.ru/[/url] .
narkologicheskaya klinika_vaPn
7 Sep 25 at 11:31 am
САЙТ ПРОДАЖИ 24/7 – Купить мефедрон, гашиш, альфа-пвп
Georgehot
7 Sep 25 at 11:33 am
Thank you for sharing your thoughts. I really appreciate your efforts and
I am waiting for your next write ups thanks once again.
дейзи дак
7 Sep 25 at 11:33 am
дом под ключ иркутск цена [url=stroitelstvo-domov-irkutsk-2.ru]stroitelstvo-domov-irkutsk-2.ru[/url] .
stroitelstvo domov irkytsk_epOi
7 Sep 25 at 11:33 am
цифровой маркетинг статьи [url=http://blog-o-marketinge1.ru]цифровой маркетинг статьи[/url] .
blog o marketinge_nrsa
7 Sep 25 at 11:34 am
строительство дома [url=stroitelstvo-domov-irkutsk-2.ru]stroitelstvo-domov-irkutsk-2.ru[/url] .
stroitelstvo domov irkytsk_hxOi
7 Sep 25 at 11:37 am
наркология анонимно [url=http://narkologicheskaya-klinika-11.ru/]http://narkologicheskaya-klinika-11.ru/[/url] .
narkologicheskaya klinika_ikPn
7 Sep 25 at 11:39 am
Hey! Someone in my Facebook group shared this
site with us so I came to look it over. I’m definitely enjoying
the information. I’m bookmarking and will be tweeting this to my followers!
Exceptional blog and amazing style and design.
my web blog: aviamasters
aviamasters
7 Sep 25 at 11:39 am
статьи про продвижение сайтов [url=https://www.blog-o-marketinge1.ru]статьи про продвижение сайтов[/url] .
blog o marketinge_dtsa
7 Sep 25 at 11:40 am
клиника вывод из запоя [url=www.narkologicheskaya-klinika-12.ru]www.narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_ilMn
7 Sep 25 at 11:40 am
дом строительство [url=www.stroitelstvo-domov-irkutsk-2.ru/]www.stroitelstvo-domov-irkutsk-2.ru/[/url] .
stroitelstvo domov irkytsk_peOi
7 Sep 25 at 11:42 am
купить легальный диплом техникума [url=www.forum.l2c4.com/member.php?u=18296/]www.forum.l2c4.com/member.php?u=18296/[/url] .
Vigodno zakazat diplom yniversiteta!_xokt
7 Sep 25 at 11:43 am
наркологические клиники в москве [url=https://www.narkologicheskaya-klinika-11.ru]https://www.narkologicheskaya-klinika-11.ru[/url] .
narkologicheskaya klinika_kqPn
7 Sep 25 at 11:43 am
контекстная реклама статьи [url=http://blog-o-marketinge1.ru]контекстная реклама статьи[/url] .
blog o marketinge_kasa
7 Sep 25 at 11:44 am
анонимная наркологическая помощь в москве [url=http://narkologicheskaya-klinika-11.ru/]http://narkologicheskaya-klinika-11.ru/[/url] .
narkologicheskaya klinika_ufPn
7 Sep 25 at 11:48 am
Kangaroo Baby is a charming India-based mobile game where players care for adorable kangaroo joeys. With simple gameplay, nurturing tasks, and cute graphics, it’s perfect for kids and casual gamers: Kangaroo drawing tutorials
BrianCiz
7 Sep 25 at 11:48 am
как купить диплом занесенный в реестр [url=forum.ozz.tv/memberlist.php?mode=viewprofile&u=12883]как купить диплом занесенный в реестр[/url] .
Priobresti diplom ob obrazovanii!_znkt
7 Sep 25 at 11:49 am
seo статьи [url=http://www.statyi-o-marketinge1.ru]seo статьи[/url] .
stati o marketinge_miot
7 Sep 25 at 11:51 am
ск домстрой [url=www.stroitelstvo-domov-irkutsk-2.ru]www.stroitelstvo-domov-irkutsk-2.ru[/url] .
stroitelstvo domov irkytsk_okOi
7 Sep 25 at 11:51 am
анонимный наркологический центр [url=https://narkologicheskaya-klinika-12.ru/]narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_bqMn
7 Sep 25 at 11:51 am
Частный вебмастер https://разработка.site/ – разработка и доработка сайтов. Выполню работы по: разработке сайта, доработке, продвижении и рекламе. Разрабатываю лендинги, интернет магазины, сайты каталоги, сайты для бизнеса, сайты с системой бронирования.
Kikupamgor
7 Sep 25 at 11:52 am
купить диплом в запорожье [url=http://educ-ua4.ru/]купить диплом в запорожье[/url] .
Diplomi_rkPl
7 Sep 25 at 11:52 am
наркологический диспансер москва [url=https://narkologicheskaya-klinika-12.ru/]narkologicheskaya-klinika-12.ru[/url] .
narkologicheskaya klinika_zwMn
7 Sep 25 at 11:55 am
мостбет вход через соцсети [url=http://mostbet4156.ru/]http://mostbet4156.ru/[/url]
mostbet_noma
7 Sep 25 at 11:55 am
приобрести mef mefedron GASH1K alfa
Georgehot
7 Sep 25 at 11:56 am
Hi there friends, its wonderful article regarding tutoringand fully defined, keep it up all the time.
building architect
7 Sep 25 at 11:56 am
наркологическая помощь [url=www.narkologicheskaya-klinika-11.ru]www.narkologicheskaya-klinika-11.ru[/url] .
narkologicheskaya klinika_cmPn
7 Sep 25 at 11:56 am
построить дом на заказ [url=www.stroitelstvo-domov-irkutsk-2.ru/]www.stroitelstvo-domov-irkutsk-2.ru/[/url] .
stroitelstvo domov irkytsk_feOi
7 Sep 25 at 11:57 am
http://smolensk-potolok.ru/files/pgs/kak_sdelaty_irokez.html
Brucechait
7 Sep 25 at 11:58 am
http://netkurenia.ru/wp-content/pages/kordelion_v_rampc.html
Brucechait
7 Sep 25 at 12:00 pm