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://natyazhnye-potolki-samara-2.ru/]http://natyazhnye-potolki-samara-2.ru/[/url] .
natyajnie potolki samara_usPi
14 Oct 25 at 8:25 pm
регистрация перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_aeKl
14 Oct 25 at 8:27 pm
گیربکس sew – قیمت گیربکس صنعتی –
خرید گیربکس صنعتی
قاسم ولی زاده
14 Oct 25 at 8:27 pm
натяжные потолки потолочкин [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_qbkl
14 Oct 25 at 8:28 pm
куплю диплом высшего образования [url=https://rudik-diplom9.ru/]куплю диплом высшего образования[/url] .
Diplomi_ehei
14 Oct 25 at 8:29 pm
Thank you for some other excellent post. The place else may anyone get that type of
information in such a perfect manner of writing? I’ve a presentation next week,
and I am at the search for such information.
seo
14 Oct 25 at 8:30 pm
электрокранизы [url=www.elektrokarnizy797.ru/]www.elektrokarnizy797.ru/[/url] .
elektrokarnizi_qzMl
14 Oct 25 at 8:30 pm
купить диплом в междуреченске [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .
Diplomi_tnpi
14 Oct 25 at 8:31 pm
натяжные потолки сайт [url=https://stretch-ceilings-samara-1.ru]натяжные потолки сайт[/url] .
natyajnie potolki samara_qesl
14 Oct 25 at 8:32 pm
самара натяжные потолки [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_omor
14 Oct 25 at 8:32 pm
My family members always say that I am killing my time here at net, but I know I am getting experience daily by reading thes nice articles.
78win
14 Oct 25 at 8:34 pm
диплом техникум колледж купить [url=frei-diplom11.ru]диплом техникум колледж купить[/url] .
Diplomi_rzsa
14 Oct 25 at 8:35 pm
потолки [url=https://stretch-ceilings-samara-1.ru]потолки[/url] .
natyajnie potolki samara_vhsl
14 Oct 25 at 8:36 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Dr c121,
Charlotte, NC 28273, United Տtates
+19803517882
Studies ideas and renovation case
Studies ideas and renovation case
14 Oct 25 at 8:39 pm
потолочек су [url=www.stretch-ceilings-samara.ru/]www.stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_cekl
14 Oct 25 at 8:39 pm
регистрация перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_esKl
14 Oct 25 at 8:39 pm
натяжной потолок в самаре [url=http://natyazhnye-potolki-samara-2.ru]натяжной потолок в самаре[/url] .
natyajnie potolki samara_guPi
14 Oct 25 at 8:40 pm
Диагностический блок включает сбор анамнеза, оценку витальных показателей, скрининговые шкалы по тревоге, депрессии и патологическому влечению, лабораторные тесты по показаниям. На основании полученных данных выбирается формат помощи и составляется медикаментозная схема с учётом взаимодействий препаратов и вероятных рисков.
Получить больше информации – [url=https://narkologicheskaya-klinika-v-luganske0.ru/]наркологическая клиника в луганске[/url]
MichaeldraFe
14 Oct 25 at 8:41 pm
Выбор методов определяется клинической картиной, коморбидными состояниями и переносимостью препаратов. Ниже представлена сводная структура основных вмешательств и терапевтических целей.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-lugansk0.ru/]врач вывод из запоя луганск[/url]
Raymondabuck
14 Oct 25 at 8:41 pm
Да, ссылка на страницу с ее условиями размещена в футере официального сайта.
кет казино
14 Oct 25 at 8:42 pm
Для достижения максимального эффекта вывод из запоя в клинике включает несколько этапов. Ниже представлены основные направления, которые применяются в процессе терапии:
Углубиться в тему – [url=https://vyvod-iz-zapoya-ulan-ude00.ru/]вывод из запоя на дому[/url]
DonaldVes
14 Oct 25 at 8:42 pm
купить диплом москва с занесением в реестр [url=http://frei-diplom1.ru/]купить диплом москва с занесением в реестр[/url] .
Diplomi_zrOi
14 Oct 25 at 8:43 pm
потолочкин потолки натяжные отзывы [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_alor
14 Oct 25 at 8:44 pm
На данном этапе врач уточняет длительность запоя, тип употребляемого алкоголя и наличие сопутствующих заболеваний. Тщательный анализ этих данных позволяет оперативно сформировать индивидуальный план лечения и выбрать оптимальные методы детоксикации.
Подробнее – http://kapelnica-ot-zapoya-arkhangelsk00.ru
Stevenunurf
14 Oct 25 at 8:44 pm
купить диплом в междуреченске [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .
Diplomi_vuKr
14 Oct 25 at 8:44 pm
диплом техникума купить дешево [url=www.frei-diplom10.ru]диплом техникума купить дешево[/url] .
Diplomi_blEa
14 Oct 25 at 8:44 pm
купить диплом в комсомольске-на-амуре [url=http://rudik-diplom15.ru/]купить диплом в комсомольске-на-амуре[/url] .
Diplomi_ozPi
14 Oct 25 at 8:44 pm
натяжные потолки дешево самара [url=www.stretch-ceilings-samara-1.ru]натяжные потолки дешево самара[/url] .
natyajnie potolki samara_kysl
14 Oct 25 at 8:46 pm
best UK online chemist for Prednisolone [url=https://medreliefuk.shop/#]buy corticosteroids without prescription UK[/url] UK chemist Prednisolone delivery
Jameshoasy
14 Oct 25 at 8:47 pm
купить диплом в мытищах [url=www.rudik-diplom14.ru/]купить диплом в мытищах[/url] .
Diplomi_dgea
14 Oct 25 at 8:47 pm
перепланировка здания [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]перепланировка здания[/url] .
pereplanirovka nejilogo pomesheniya_kgKl
14 Oct 25 at 8:47 pm
ПитерКомфорт — это единый центр решений для водоочистки и инженерных систем, где важна эффективность и ресурс. Здесь собран полный спектр решений: фильтры для квартиры и HoReCa, установки обратного осмоса, УФ-обеззараживание, насосные станции ESPA, химия и оборудование для бассейнов, сервисные реагенты для отопления. В центре каталога — проверенные бренды BWT, SFA и другие. Ищете установка для промывки теплообменников? Подробности, акции и консультации — на pitercomfort.ru Поможем выбрать оптимальную систему и оперативно доставим заказ по России — удобно, прозрачно, в нужные сроки.
tulajiPlowl
14 Oct 25 at 8:47 pm
https://ru.pinterest.com/pin/1091419290961253185/
Nathanhip
14 Oct 25 at 8:47 pm
потолочкин [url=http://stretch-ceilings-samara.ru]http://stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_npkl
14 Oct 25 at 8:49 pm
электрокарнизы для штор купить [url=http://elektrokarnizy797.ru/]электрокарнизы для штор купить[/url] .
elektrokarnizi_yoMl
14 Oct 25 at 8:49 pm
натяжной потолок цена самара [url=www.natyazhnye-potolki-samara-2.ru]натяжной потолок цена самара[/url] .
natyajnie potolki samara_lpPi
14 Oct 25 at 8:49 pm
купить диплом в находке [url=www.rudik-diplom10.ru]купить диплом в находке[/url] .
Diplomi_ozSa
14 Oct 25 at 8:50 pm
Just extended my $MTAUR vesting for that 10% bonus—smart play. The audited contracts and cliff mechanisms build trust. Can’t wait to battle crypto monsters in full release.
mtaur coin
WilliamPargy
14 Oct 25 at 8:51 pm
http://inquisnower.phorum.pl/viewtopic.php?p=666506#666506
qveknxc
14 Oct 25 at 8:51 pm
Acho simplesmente brabissimo MegaPosta Casino, da uma energia de cassino que e um vulcao. As opcoes de jogo no cassino sao ricas e vibrantes, com caca-niqueis de cassino modernos e eletrizantes. O suporte do cassino ta sempre na ativa 24/7, acessivel por chat ou e-mail. O processo do cassino e limpo e sem turbulencia, porem as ofertas do cassino podiam ser mais generosas. No fim das contas, MegaPosta Casino oferece uma experiencia de cassino que e puro fogo para os viciados em emocoes de cassino! Alem disso o design do cassino e uma explosao visual braba, o que deixa cada sessao de cassino ainda mais alucinante.
megaposta bonus codes|
whackypenguin6zef
14 Oct 25 at 8:51 pm
My brother recommended I might like this website.
He was entirely right. This post truly made my day.
You can not imagine simply how much time I had
spent for this information! Thanks!
best crypto casinos
14 Oct 25 at 8:52 pm
купить диплом в кирово-чепецке [url=http://rudik-diplom9.ru/]http://rudik-diplom9.ru/[/url] .
Diplomi_piei
14 Oct 25 at 8:53 pm
order ED pills online UK: viagra – order ED pills online UK
JamesDes
14 Oct 25 at 8:54 pm
Acho simplesmente insano OshCasino, oferece uma aventura de cassino que incendeia tudo. Tem uma enxurrada de jogos de cassino irados, com slots de cassino unicos e explosivos. O suporte do cassino ta sempre na ativa 24/7, garantindo suporte de cassino direto e sem cinzas. Os ganhos do cassino chegam voando como um meteoro, porem as ofertas do cassino podiam ser mais generosas. No geral, OshCasino e um cassino online que e uma erupcao de diversao para os amantes de cassinos online! De lambuja a navegacao do cassino e facil como uma trilha vulcanica, torna o cassino uma curticao total.
osh application mobile|
zestylizard7zef
14 Oct 25 at 8:54 pm
потолочкин натяжные потолки самара отзывы [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_rior
14 Oct 25 at 8:54 pm
Minotaurus token’s ecosystem ties game, DAO, and rewards seamlessly. ICO phase is buzzing with partnerships forming. As a gamer, I’m all in on this maze adventure.
minotaurus ico
WilliamPargy
14 Oct 25 at 8:54 pm
купить диплом техникума и поступить в вуз [url=http://www.frei-diplom11.ru]купить диплом техникума и поступить в вуз[/url] .
Diplomi_sysa
14 Oct 25 at 8:58 pm
Ich bin beeindruckt von SpinBetter Casino, es liefert ein Abenteuer voller Energie. Das Angebot an Spielen ist phanomenal, mit dynamischen Tischspielen. Der Kundenservice ist ausgezeichnet, mit praziser Unterstutzung. Der Ablauf ist unkompliziert, ab und an mehr abwechslungsreiche Boni waren super. In Kurze, SpinBetter Casino ist eine Plattform, die uberzeugt fur Krypto-Enthusiasten ! Hinzu kommt die Plattform ist visuell ein Hit, erleichtert die gesamte Erfahrung. Hervorzuheben ist die schnellen Einzahlungen, die den Einstieg erleichtern.
spinbettercasino.de|
SpinMasterZ7zef
14 Oct 25 at 8:59 pm
натяжные потолки потолочкин [url=http://stretch-ceilings-samara-1.ru]натяжные потолки потолочкин[/url] .
natyajnie potolki samara_yssl
14 Oct 25 at 8:59 pm
По прибытии проводится экспресс-диагностика: измеряются артериальное давление, пульс, сатурация, температура, оценивается уровень обезвоживания и неврологический статус; при показаниях выполняется ЭКГ. Врач простым языком объясняет, какие препараты и в каком порядке будут вводиться, отвечает на вопросы и получает информированное согласие.
Детальнее – https://narkolog-na-dom-serpuhov6.ru/vrach-narkolog-na-dom-v-serpuhove
SamuelClosy
14 Oct 25 at 9:01 pm