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://novosti-sporta-2.ru/]http://novosti-sporta-2.ru/[/url] .
novosti sporta_rhsa
15 Aug 25 at 10:33 pm
Инфузии выполняются с помощью автоматизированных насосов, позволяющих скорректировать скорость введения в зависимости от показателей безопасности.
Получить дополнительные сведения – http://medicinskij-vyvod-iz-zapoya.ru
RobertExevy
15 Aug 25 at 10:34 pm
https://hub.docker.com/u/budhaburnea
ElijahGicky
15 Aug 25 at 10:34 pm
новости спорта футбол [url=www.novosti-sporta-2.ru/]www.novosti-sporta-2.ru/[/url] .
novosti sporta_hhsa
15 Aug 25 at 10:35 pm
купить диплом в киеве цены [url=http://educ-ua5.ru]купить диплом в киеве цены[/url] .
Diplomi_owKl
15 Aug 25 at 10:37 pm
Narcology Clinic в Москве оказывает экстренную наркологическую помощь дома — скорая выездная служба выполняет детоксикацию, капельницы и мониторинг до нормализации состояния. Анонимно и круглосуточно.
Подробнее можно узнать тут – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]скорая наркологическая помощь московская область[/url]
BernardCar
15 Aug 25 at 10:43 pm
купить диплом о высшем образовании с занесением в реестр в москве [url=https://www.arus-diplom32.ru]купить диплом о высшем образовании с занесением в реестр в москве[/url] .
Zakazat diplom VYZa!_pfEn
15 Aug 25 at 10:46 pm
спортивные новости [url=http://novosti-sporta-2.ru]http://novosti-sporta-2.ru[/url] .
novosti sporta_rjsa
15 Aug 25 at 10:51 pm
Quality posts is the key to interest the people to pay a quick visit the website,
that’s what this website is providing.
quicksmartweb.com
15 Aug 25 at 10:51 pm
[url=https://казанчугунный.рф ]God see[/url]
JosephNof
15 Aug 25 at 10:52 pm
https://pxlmo.com/ashnilaxay
ElijahGicky
15 Aug 25 at 10:54 pm
I like what you guys are up too. This type of clever work and exposure!
Keep up the awesome works guys I’ve incorporated you guys to my own blogroll.
рабочая ссылка на кракен в торе
15 Aug 25 at 10:57 pm
спортивные новости [url=http://www.novosti-sporta-2.ru]http://www.novosti-sporta-2.ru[/url] .
novosti sporta_npsa
15 Aug 25 at 11:00 pm
What’s Taking place i am new to this, I stumbled upon this I’ve found It positively useful
and it has aided me out loads. I am hoping to
give a contribution & aid other users like
its helped me. Good job.
agen toto togel
15 Aug 25 at 11:05 pm
Tadalify [url=https://tadalify.com/#]Tadalify[/url] Tadalify
RobertCat
15 Aug 25 at 11:12 pm
https://rant.li/cp7853cz2v
ElijahGicky
15 Aug 25 at 11:13 pm
Ꮤhat i Ԁοn’t realize is if tгuth be told how you агe no longer actually
a lot more well-likeɗ than you may be now. Yоu ɑre so intelligent.
You understand thus significantly in the caѕe of this suЬject, produced me for mʏ part cоnsidеr it from ѕo many numerous angles.
Its lіke women and men don’t seem to be fascinateⅾ except it is оne thing to
accomplish with Lady gagɑ! Yoᥙr іndividual stuffѕ excellent.
Always maintain it up!
Mʏ page; green Bags
green Bags
15 Aug 25 at 11:13 pm
https://allmynursejobs.com/author/rednightmare240/
Haroldbon
15 Aug 25 at 11:14 pm
I like the helpful info you provide in your articles. I’ll bookmark your blog and
check again here frequently. I’m quite certain I will learn lots of new stuff right here!
Best of luck for the next!
Look into my web site zakelijke wifi nederland
zakelijke wifi nederland
15 Aug 25 at 11:15 pm
Narcology Clinic в Москве оказывает экстренную наркологическую помощь дома — скорая выездная служба выполняет детоксикацию, капельницы и мониторинг до нормализации состояния. Анонимно и круглосуточно.
Подробнее тут – [url=https://skoraya-narkologicheskaya-pomoshch-moskva12.ru/]срочная наркологическая помощь москва[/url]
Jasonled
15 Aug 25 at 11:16 pm
Врачебный состав клиники “Путь к выздоровлению” состоит из высококвалифицированных специалистов в области наркологии. Наши врачи-наркологи имеют обширный опыт работы с зависимыми пациентами и постоянно совершенствуют свои навыки.
Подробнее – http://нарко-фильтр.рф
Billymub
15 Aug 25 at 11:16 pm
купить диплом с занесением в реестр цена [url=http://www.arus-diplom32.ru]купить диплом с занесением в реестр цена[/url] .
Kypit diplom ob obrazovanii!_wlEn
15 Aug 25 at 11:27 pm
прикольные горшки для цветов [url=http://www.dizaynerskie-kashpo-rnd.ru]прикольные горшки для цветов[/url] .
dizainerskie kashpo_wuEr
15 Aug 25 at 11:31 pm
I am extremely impressed with your writing skills and also with the layout on your
weblog. Is this a paid theme or did you modify
it yourself? Anyway keep up the nice quality writing, it’s rare to see a great blog like
this one these days.
bs2best
15 Aug 25 at 11:32 pm
https://www.metooo.io/u/689a641bc6fd1a348a405b95
ElijahGicky
15 Aug 25 at 11:33 pm
Для полноценного участия
в играх на реальные деньги на платформе PokerDom
требуется авторизация в личном кабинете.
покердом
15 Aug 25 at 11:34 pm
Купить диплом о высшем образовании!
Мы изготавливаем дипломы любых профессий по выгодным ценам— [url=http://kupitediplom0027.ru/]kupitediplom0027.ru[/url]
Lazrgvh
15 Aug 25 at 11:34 pm
Запчасти для плиты Hansa FCGW62020 Запчасти для стиральной машины Ariston AVL 14 (FR) (CO): Европейский стандарт надежности. Обеспечьте бесперебойную работу вашей стиральной машины, используя оригинальные или качественные аналоги запчастей.
Calebpes
15 Aug 25 at 11:41 pm
Скорая наркологическая служба Narcology Clinic в Москве работает круглосуточно. Выезд к пациенту, медикаментозная стабилизация, детоксикация и психологическая поддержка до выхода из кризисного состояния.
Подробнее – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]наркологическая помощь москве[/url]
Robertkix
15 Aug 25 at 11:46 pm
Tadalify: best price for cialis – Tadalify
PeterTEEFS
15 Aug 25 at 11:49 pm
https://odysee.com/@Russchstop
ElijahGicky
15 Aug 25 at 11:52 pm
https://git.project-hobbit.eu/iodegabacibg
Haroldbon
15 Aug 25 at 11:56 pm
Найти друга на форуме знакомств https://perekrestok.1bb.ru форум без регистрации где есть тема любовь и отношения, хорошие люди, есть модерация все культурно и красиво.
perekrestok-330
15 Aug 25 at 11:58 pm
Fastidious respond in return of this matter with genuine arguments and describing everything about that.
Köp Cialis säkert online till bästa pris
15 Aug 25 at 11:59 pm
купить диплом с занесением в реестр в украине [url=http://www.arus-diplom32.ru]http://www.arus-diplom32.ru[/url] .
Zakazat diplom VYZa!_ucEn
15 Aug 25 at 11:59 pm
Мы понимаем уникальность каждого пациента и проводим тщательную диагностику, анализируя его медицинскую историю, психологическое состояние и социальные факторы. На основе полученных данных создаем персональные планы лечения, включающие медикаментозные средства, психотерапию и социальные программы.
Узнать больше – https://медицинский-вывод-из-запоя.рф/vyvod-iz-zapoya-v-stacionare-v-rostove-na-donu.xn--p1ai/
Philipkam
16 Aug 25 at 12:03 am
форум общения Покупки в интернет-магазинах какие лучше выбрать? что посоветуете, обсуждение на форуме очень были полезны
perekrestok-907
16 Aug 25 at 12:05 am
https://sildenapeak.com/# SildenaPeak
Danielchumn
16 Aug 25 at 12:07 am
Найти друга на форуме знакомств https://perekrestok.1bb.ru форум без регистрации где есть тема любовь и отношения, хорошие люди, есть модерация все культурно и красиво.
perekrestok-311
16 Aug 25 at 12:09 am
http://kamameds.com/# Online sources for Kamagra in the United States
Danielchumn
16 Aug 25 at 12:11 am
Zasto se javlja bol u bubregu: od kamenaca i infekcija do prehlade. Kako prepoznati opasne simptome i brzo zapoceti lecenje. Korisne informacije.
bol-u-bubrezima-961
16 Aug 25 at 12:11 am
https://pxlmo.com/Jones_sandrak19119
ElijahGicky
16 Aug 25 at 12:11 am
как купить диплом с проведением [url=http://arus-diplom32.ru/]как купить диплом с проведением[/url] .
Zakazat diplom instityta!_qsEn
16 Aug 25 at 12:13 am
Wow, this piece of writing is good, my sister is analyzing these kinds of things,
therefore I am going to tell her.
kirkq370irx3.sunderwiki.com
16 Aug 25 at 12:15 am
With unrestricted accessibility tο exercise worksheets, OMT equips pupils tߋo master mathematics via repetition,
constructing love f᧐r tһe subject and test confidence.
Experience versatile knowing anytime, аnywhere through OMT’ѕ tһorough online e-learning platform, featuring unrestricted access tօ video
lessons ɑnd interactive tests.
As math forms tһе bedrock ᧐f rational
thinking and critical analytical іn Singapore’s education ѕystem, expert math tuition ⲟffers tһe personalized guidance neeԁed to tսrn difficulties іnto
accomplishments.
Tuition in primary school mathematics is essential fߋr PSLE preparation, ɑѕ it
introduces innovative methods fоr dealing with non-routine ρroblems tһаt stump ⅼots of candidates.
Secondary school math tuition іs essential foг O Levels aѕ it enhances mastery ᧐f algebraic adjustment, ɑ core element that օften sһows up in test inquiries.
Ιn an affordable Singaporean education аnd learning system,
junior college math tuition ɡives pupils tһe sidxe to achieve
high qualities required fⲟr university admissions.
Ꭲhe exclusive OMT curriculum stands ɑpart by
prolonging MOE curriculum with enrichment ߋn analytical modeling, ideal for data-driven exam concerns.
Limitless accessibility tο worksheets indicates үou exercise till shiok, improving yߋur math self-confidence and qualities quіckly.
Math tuition ρrovides enrichment beyond the basics, challenging
gifted Singapore trainees tօ aim foг difference іn exams.
Also visit my homepage – new york act math tutoring
new york act math tutoring
16 Aug 25 at 12:15 am
I was curious if you ever considered changing
the structure of your blog? Its very well written; I love what youve got
to say. But maybe you could a little more in the way
of content so people could connect with it better. Youve got an awful
lot of text for only having 1 or two images. Maybe you could space it
out better?
KL99
16 Aug 25 at 12:15 am
Kamagra reviews from US customers: Safe access to generic ED medication – Kamagra oral jelly USA availability
RichardTit
16 Aug 25 at 12:15 am
I’m really loving the theme/design of your site. Do you ever run into
any internet browser compatibility issues? A few of my blog visitors
have complained about my site not working correctly in Explorer
but looks great in Safari. Do you have any solutions to help fix this issue?
comprar billetes renfe con tarjeta dorada
16 Aug 25 at 12:18 am
Таким образом, наш подход направлен на создание комплексной системы поддержки, которая помогает каждому пациенту справиться с зависимостью и вернуться к полноценной жизни.
Получить дополнительную информацию – [url=https://srochnyj-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-cena-v-kazani.ru/]вывод из запоя вызов[/url]
Richardfowly
16 Aug 25 at 12:18 am
Zasto se javlja https://www.bol-u-bubrezima.com: od kamenaca i infekcija do prehlade. Kako prepoznati opasne simptome i brzo zapoceti lecenje. Korisne informacije.
bol-u-bubrezima-317
16 Aug 25 at 12:18 am