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!
Adoro o role insano de Flabet Casino, e um cassino online que e pura dinamite. O catalogo de jogos do cassino e uma loucura, com slots de cassino unicos e eletrizantes. O suporte do cassino ta sempre na area 24/7, acessivel por chat ou e-mail. Os saques no cassino sao velozes como um raio, de vez em quando queria mais promocoes de cassino que arrebentam. No geral, Flabet Casino vale demais explorar esse cassino para quem curte apostar com estilo no cassino! Vale falar tambem a interface do cassino e fluida e cheia de vibe, faz voce querer voltar pro cassino toda hora.
flabet apk|
whimsyjelly6zef
5 Oct 25 at 11:32 am
купить диплом [url=https://rudik-diplom7.ru]купить диплом[/url] .
Diplomi_fzPl
5 Oct 25 at 11:32 am
диплом автотранспортного техникума купить [url=https://www.frei-diplom9.ru]диплом автотранспортного техникума купить[/url] .
Diplomi_pvea
5 Oct 25 at 11:32 am
https://t.me/s/Official_Pokerdomm
Thomastaume
5 Oct 25 at 11:32 am
купить диплом в новороссийске [url=http://rudik-diplom11.ru/]купить диплом в новороссийске[/url] .
Diplomi_vyMi
5 Oct 25 at 11:32 am
52cjg.xyz – The color palette feels muted and easy on the eyes.
August Przybyl
5 Oct 25 at 11:33 am
Greetings! I know this is kind of off topic but I was wondering if you knew
where I could get a captcha plugin for my comment form?
I’m using the same blog platform as yours and
I’m having trouble finding one? Thanks a lot!
Frame Inomax Nx
5 Oct 25 at 11:36 am
Когда уместен
Узнать больше – [url=https://narkologicheskaya-klinika-odincovo0.ru/]наркологическая клиника нарколог[/url]
FidelDob
5 Oct 25 at 11:37 am
прогноз на футбол [url=www.prognozy-na-futbol-10.ru/]прогноз на футбол[/url] .
prognozi na fytbol_lxOi
5 Oct 25 at 11:38 am
J’adore le delire de FatPirate, il offre une aventure totalement barge. La selection est carrement dingue, incluant des jeux de table pleins de panache. Le service client est au top niveau, joignable par chat ou email. Les gains arrivent en mode eclair, mais bon des bonus plus reguliers ce serait cool. Bref, FatPirate garantit un fun total pour les aventuriers du jeu ! Et puis le site est une pepite visuelle, ajoute un max de swag.
fatpirate pЕ™ihlГЎЕЎenГ|
wildpickle3zef
5 Oct 25 at 11:38 am
купить диплом в тамбове [url=https://rudik-diplom7.ru/]купить диплом в тамбове[/url] .
Diplomi_lxPl
5 Oct 25 at 11:40 am
прогноз футбол на сегодня [url=http://www.prognozy-na-futbol-10.ru]прогноз футбол на сегодня[/url] .
prognozi na fytbol_idOi
5 Oct 25 at 11:42 am
купить диплом о высшем образовании легально [url=https://frei-diplom2.ru/]купить диплом о высшем образовании легально[/url] .
Diplomi_tpEa
5 Oct 25 at 11:43 am
Вместо универсальных «капельниц на все случаи» мы собираем персональный план: состав инфузий, необходимость диагностик, частоту наблюдения и следующий шаг маршрута. Такой подход экономит время, снижает тревогу и даёт предсказуемый горизонт: что будет сделано сегодня, чего ждать завтра и какие критерии покажут, что идём по плану.
Узнать больше – https://narkologicheskaya-klinika-himki0.ru/kruglosutochnaya-narkologicheskaya-klinika-v-himkah
StephenHizat
5 Oct 25 at 11:43 am
Для меня Складчик стал настоящим открытием. Я давно занимаюсь бизнесом и постоянно обучаюсь, но стоимость качественных курсов часто слишком высока. Благодаря складчине я получил доступ к курсам по маркетингу, продажам и личностному росту за символические суммы. В обычной продаже они стоили десятки тысяч рублей, а здесь — копейки. Процесс покупки простой и быстрый, доступ открыли моментально. Порадовало, что есть обратная связь и живое сообщество. Теперь проверяю Складчик перед тем, как купить что-то дорого напрямую, ведь экономия реально колоссальная https://v27.skladchik.org/
BryanTop
5 Oct 25 at 11:44 am
купить дипломы о высшем [url=https://www.rudik-diplom3.ru]купить дипломы о высшем[/url] .
Diplomi_qbei
5 Oct 25 at 11:44 am
Закладки тут – купить гашиш, мефедрон, альфа-РїРІРї
RodneyDof
5 Oct 25 at 11:45 am
АНО «Бюро судебной экспертизы и оценки “АРГУМЕНТ”» — команда кандидатов и докторов наук, выполняющая более 15 видов экспертиз: от автотехнической и строительно-технической до финансово-экономической, лингвистической и в сфере банкротств. Индивидуальная методика, оперативные сроки от 5 рабочих дней и защита заключений в судах по всей РФ делают результаты предсказуемыми и убедительными. Ознакомьтесь с кейсами и запишитесь на консультацию на https://anoargument.ru/ — точные выводы в срок, когда на кону исход спора.
xypodamBuics
5 Oct 25 at 11:45 am
прогнозы на сегодня футбол [url=http://prognozy-na-futbol-10.ru]прогнозы на сегодня футбол[/url] .
prognozi na fytbol_wfOi
5 Oct 25 at 11:45 am
купить диплом учителя физической культуры [url=http://rudik-diplom7.ru]купить диплом учителя физической культуры[/url] .
Diplomi_eePl
5 Oct 25 at 11:47 am
It’s going to be end of mine day, however before ending I am reading
this wonderful article to increase my know-how.
comment-29235
5 Oct 25 at 11:49 am
viralvideo
funnyvideo
funny
funnyvideo
funnyshorts
funnyvideos
nasa
নাসাভাইবিনোদোন
funnyvideo
5 Oct 25 at 11:49 am
купить диплом в златоусте [url=www.rudik-diplom10.ru]купить диплом в златоусте[/url] .
Diplomi_ghSa
5 Oct 25 at 11:49 am
изготовление кухни на заказ в спб [url=http://kuhni-spb-4.ru]изготовление кухни на заказ в спб[/url] .
kyhni spb_fher
5 Oct 25 at 11:49 am
https://ozon.ru/t/csgBrx8
DavidCes
5 Oct 25 at 11:51 am
Hi to every , since I am really eager of reading this web site’s post to be updated regularly.
It consists of pleasant stuff.
azino777
5 Oct 25 at 11:51 am
Way cool! Some extremely valid points! I appreciate
you penning this post and the rest of the site is very good.
au88
5 Oct 25 at 11:52 am
http://regrowrxonline.com/# buy finasteride
AnthonyGique
5 Oct 25 at 11:52 am
можно ли купить диплом в реестре [url=https://www.frei-diplom2.ru]можно ли купить диплом в реестре[/url] .
Diplomi_qeEa
5 Oct 25 at 11:52 am
Wow, marvelous blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your
web site is wonderful, let alone the content!
tt88 casino
5 Oct 25 at 11:54 am
viralvideo
funnyvideo
funny
funnyvideo
funnyshorts
funnyvideos
nasa
নাসাভাইবিনোদোন
nasa
5 Oct 25 at 11:54 am
кухни на заказ спб каталог [url=www.kuhni-spb-4.ru/]кухни на заказ спб каталог[/url] .
kyhni spb_zuer
5 Oct 25 at 11:55 am
ставки на футбол сегодня [url=www.prognozy-na-futbol-10.ru/]ставки на футбол сегодня[/url] .
prognozi na fytbol_urOi
5 Oct 25 at 11:56 am
поставка медоборудования [url=medtehnika-msk.ru]medtehnika-msk.ru[/url] .
oborydovanie medicinskoe_eupa
5 Oct 25 at 11:56 am
Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results.
If you know of any please share. Thanks!
rectostop online
5 Oct 25 at 11:57 am
Hondrolife natürliches Spray gegen Gelenkschmerzen ist mein Begleiter beim Sport.
Es schützt meine Gelenke gut.
Hondrolife natürliches Spray gegen Gelenkschmerzen
5 Oct 25 at 11:57 am
купить диплом товароведа [url=http://rudik-diplom11.ru/]купить диплом товароведа[/url] .
Diplomi_fsMi
5 Oct 25 at 11:58 am
купить диплом строительного техникума в спб [url=frei-diplom9.ru]купить диплом строительного техникума в спб[/url] .
Diplomi_zmea
5 Oct 25 at 11:58 am
1win букмекерская контора зеркало [url=https://www.1win5517.ru]1win букмекерская контора зеркало[/url]
1win_nqOl
5 Oct 25 at 11:58 am
купить диплом о высшем образовании с реестром [url=http://frei-diplom2.ru]купить диплом о высшем образовании с реестром[/url] .
Diplomi_ljEa
5 Oct 25 at 11:58 am
кухни на заказ производство спб [url=http://kuhni-spb-4.ru]http://kuhni-spb-4.ru[/url] .
kyhni spb_nser
5 Oct 25 at 11:59 am
ylu555.xyz – Load speed is okay, though more complex pages lag a bit on weak connection.
Arvilla Shuecraft
5 Oct 25 at 11:59 am
Adoro o role insano de Flabet Casino, parece um furacao de diversao. A gama do cassino e simplesmente um arraso, com jogos de cassino perfeitos pra criptomoedas. O atendimento ao cliente do cassino e uma explosao, dando solucoes na hora e com precisao. Os ganhos do cassino chegam voando baixo, de vez em quando mais recompensas no cassino seriam um baita plus. No geral, Flabet Casino e um cassino online que e um vulcao para os amantes de cassinos online! E mais a navegacao do cassino e facil como brincadeira, torna o cassino uma curticao total.
bonus flabet|
whimsyjelly6zef
5 Oct 25 at 12:03 pm
купить диплом зарегистрированный в реестре [url=frei-diplom5.ru]frei-diplom5.ru[/url] .
Diplomi_ivPa
5 Oct 25 at 12:04 pm
Sou louco pela vibe de AFun Casino, tem uma vibe de jogo tao vibrante quanto um desfile de cores. As opcoes de jogo no cassino sao ricas e cheias de swing, com caca-niqueis de cassino modernos e contagiantes. O servico do cassino e confiavel e cheio de energia, garantindo suporte de cassino direto e sem pausa. Os ganhos do cassino chegam voando como serpentinas, mas queria mais promocoes de cassino que botam pra quebrar. Na real, AFun Casino e um cassino online que e uma explosao de alegria para os viciados em emocoes de cassino! De lambuja o design do cassino e um espetaculo visual de purpurina, faz voce querer voltar ao cassino como num desfile sem fim.
entra na afun|
zappyglitterkoala8zef
5 Oct 25 at 12:04 pm
экспресс на футбол сегодня [url=https://prognozy-na-futbol-10.ru]https://prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_yjOi
5 Oct 25 at 12:05 pm
куплю диплом медсестры в москве [url=https://frei-diplom14.ru]куплю диплом медсестры в москве[/url] .
Diplomi_sgoi
5 Oct 25 at 12:05 pm
Hi there I am so glad I found your website,
I really found you by accident, while I was researching on Google for something else,
Anyways I am here now and would just like to
say cheers for a incredible post and a all round entertaining blog (I also love the theme/design),
I don’t have time to read it all at the minute but I have book-marked it and also added your RSS feeds,
so when I have time I will be back to read much more, Please do keep up the excellent work.
live казино без проверки документов
5 Oct 25 at 12:08 pm
купить диплом в саратове [url=www.rudik-diplom11.ru]купить диплом в саратове[/url] .
Diplomi_naMi
5 Oct 25 at 12:09 pm
купить диплом техникума в донецке [url=http://www.frei-diplom9.ru]купить диплом техникума в донецке[/url] .
Diplomi_agea
5 Oct 25 at 12:09 pm