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://frei-diplom11.ru/]где можно купить диплом техникума[/url] .
Diplomi_irsa
16 Oct 25 at 8:11 am
купить диплом о высшем образовании с занесением в реестр отзывы [url=https://www.frei-diplom5.ru]купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Diplomi_uzPa
16 Oct 25 at 8:12 am
потол [url=https://stretch-ceilings-nizhniy-novgorod.ru/]https://stretch-ceilings-nizhniy-novgorod.ru/[/url] .
natyajnie potolki nijnii novgorod_mmPl
16 Oct 25 at 8:13 am
My brother recommended I may like this website.
He used to be entirely right. This submit truly made
my day. You can not consider just how a lot time I had spent for this information! Thanks!
טלגראס קישור
16 Oct 25 at 8:14 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Исследовать вопрос подробнее – https://fridaymusicale.com/favicon
Johnieknicy
16 Oct 25 at 8:14 am
J-center Studio — школа, где учат профессии парикмахера на практике с четвёртого дня: работа с клиентами, колористика, мужские и женские стрижки, укладки, стажировка в салонах. Прозрачные цены, маленькие группы, инструменты и материалы — за счёт школы. Записаться и узнать ближайший старт можно на https://j-center.ru/ — расписание, форматы (группы, индивидуально, экстерн) и контакты на странице. Диплом и реальный опыт дают выпускникам быстрый вход в индустрию красоты.
rihyftTop
16 Oct 25 at 8:16 am
1win pul çıxarma [url=http://1win5004.com/]http://1win5004.com/[/url]
1win_ysoi
16 Oct 25 at 8:16 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Перейти к полной версии – https://soloist.academy/full-width-post
WilliamWam
16 Oct 25 at 8:17 am
диплом о высшем образовании с занесением в реестр купить [url=http://frei-diplom5.ru]диплом о высшем образовании с занесением в реестр купить[/url] .
Diplomi_ahPa
16 Oct 25 at 8:18 am
Ꭲhe upcoming brand-new physical area at OMT assures
immersive math experiences, stimulating lifelong love fоr
the subject and motivation for exam accomplishments.
Established іn 2013 by Mг. Justin Tan, OMT
Math Tuition hаs actually helped countless trainees ace exams ⅼike PSLE, O-Levels, and A-Levels with tested ρroblem-solving techniques.
Ꮃith students in Singapore starting formal mathematics education fгom daу one and dealing wіth һigh-stakes assessments, math tuition ߋffers the extra edge needed to achieve leading
performance іn this essential topic.
Enrolling іn primary school school math tuition еarly fosters
confidence, minimizing anxiety fօr PSLE takers whо
face hiɡһ-stakes questions ߋn speed, range, ɑnd time.
Secondary math tuition ɡets over tһe limitations of big classroom dimensions, offering
concentrated іnterest that improves understanding for
O Level preparation.
Tuition оffers techniques foг time management tһroughout tһe extensive A
Level math tests, allowing trainees tօ allocate efforts
efficiently tһroughout ɑreas.
The originality оf OMT exists in itѕ tailored educational program tһat lines up flawlessly ԝith MOE criteria
ԝhile introducing ingenious analytical methods not typically stressed іn classrooms.
OMT’s e-learning decreases math anxiousness lor, mɑking
you more ϲertain аnd resulting іn hіgher examination marks.
Math tuition supports ɑ growth wаy of thinking, urging Singapore trainees tо watch challenges аs possibilities for examination excellence.
Ꮋere is myy ρage math tutor dvd electrical complete collection full download
math tutor dvd electrical complete collection full download
16 Oct 25 at 8:18 am
потолочник натяжные потолки [url=https://stretch-ceilings-nizhniy-novgorod.ru/]stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_jaPl
16 Oct 25 at 8:19 am
Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий!
Запросить дополнительные данные – https://www.bellewarmedia.com/%D8%A8%D8%AB-%D9%85%D8%A8%D8%A7%D8%B4%D8%B1
DavidNip
16 Oct 25 at 8:19 am
купить диплом в юрге [url=www.rudik-diplom5.ru]купить диплом в юрге[/url] .
Diplomi_nfma
16 Oct 25 at 8:19 am
купить диплом в рыбинске [url=https://rudik-diplom11.ru]https://rudik-diplom11.ru[/url] .
Diplomi_ztMi
16 Oct 25 at 8:21 am
This site was… how do I say it? Relevant!!
Finally I have found something which helped me. Cheers!
13win
16 Oct 25 at 8:22 am
Relax with a [url=https://www.vipmassagenuru.com/]soapy massage[/url] for slippery, smooth, and sensual enjoyment.
RonaldMaw
16 Oct 25 at 8:22 am
Всех благ данному магазину!!!
https://telegra.ph/Binokl-celestron-skymaster-25×70-kupit-10-13-3
Упаковано и расфасовано все в лучшем виде! За неделю взял 9 адресов подьем 100%. Ск оч.радует
MichaelViess
16 Oct 25 at 8:23 am
Эта статья предлагает захватывающий и полезный контент, который привлечет внимание широкого круга читателей. Мы постараемся представить тебе идеи, которые вдохновят вас на изменения в жизни и предоставят практические решения для повседневных вопросов. Читайте и вдохновляйтесь!
Неизвестные факты о… – https://pure-fm.de/qtvideo/red-lips
RobertDam
16 Oct 25 at 8:24 am
купить свидетельство о рождении ссср [url=http://www.rudik-diplom8.ru]купить свидетельство о рождении ссср[/url] .
Diplomi_nwMt
16 Oct 25 at 8:24 am
купить диплом по реестру [url=http://frei-diplom6.ru]купить диплом по реестру[/url] .
Diplomi_hjOl
16 Oct 25 at 8:24 am
тканевые натяжные потолки нижний новгород акции [url=stretch-ceilings-nizhniy-novgorod.ru]stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_jnPl
16 Oct 25 at 8:24 am
купить свидетельство о браке [url=https://rudik-diplom3.ru/]купить свидетельство о браке[/url] .
Diplomi_ugei
16 Oct 25 at 8:25 am
как купить диплом техникума в казахстане [url=http://frei-diplom7.ru]как купить диплом техникума в казахстане[/url] .
Diplomi_exei
16 Oct 25 at 8:25 am
потолочник отзывы натяжные потолки [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]http://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_vzma
16 Oct 25 at 8:27 am
Согласен, это забавная фраза
uzitecne vedet, ze pred vystupem 35nasobneho spinu musi zpet bonus, [url=https:/noresharski.com/cs/nejlepsi-ceske-online-casino/]cz online casino[/url] a pouze v online vyherni automaty Kajot Prime.
StellaNop
16 Oct 25 at 8:28 am
купить диплом в ростове-на-дону [url=rudik-diplom5.ru]купить диплом в ростове-на-дону[/url] .
Diplomi_djma
16 Oct 25 at 8:28 am
купить диплом в междуреченске [url=www.rudik-diplom1.ru/]www.rudik-diplom1.ru/[/url] .
Diplomi_qger
16 Oct 25 at 8:28 am
купить свидетельство о рождении [url=rudik-diplom4.ru]купить свидетельство о рождении[/url] .
Diplomi_icOr
16 Oct 25 at 8:28 am
https://t.me/Online_1_xbet/2953
CharlesCic
16 Oct 25 at 8:29 am
https://t.me/Online_1_xbet/2113
CharlesCic
16 Oct 25 at 8:30 am
купить диплом сантехника [url=www.rudik-diplom11.ru/]купить диплом сантехника[/url] .
Diplomi_ygMi
16 Oct 25 at 8:31 am
https://domebeli.ru/ofis/vannaya-v-russkom-stile
https://domebeli.ru/ofis/vannaya-v-russkom-stile
16 Oct 25 at 8:32 am
Hi, yes this article is really nice and I have learned
lot of things from it on the topic of blogging. thanks.
Visit here
16 Oct 25 at 8:32 am
Этот информационный материал привлекает внимание множеством интересных деталей и необычных ракурсов. Мы предлагаем уникальные взгляды на привычные вещи и рассматриваем вопросы, которые волнуют общество. Будьте в курсе актуальных тем и расширяйте свои знания!
Продолжить чтение – https://www.swastikenterprise.com/global
JosephArils
16 Oct 25 at 8:32 am
купить диплом в ишиме [url=http://rudik-diplom3.ru/]http://rudik-diplom3.ru/[/url] .
Diplomi_pdei
16 Oct 25 at 8:33 am
натяжные потолки нижний новгород [url=http://stretch-ceilings-nizhniy-novgorod.ru]http://stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_xjPl
16 Oct 25 at 8:33 am
Saved as a favorite, I love your website!
card game
16 Oct 25 at 8:33 am
купить диплом в воронеже [url=https://rudik-diplom15.ru/]купить диплом в воронеже[/url] .
Diplomi_kjPi
16 Oct 25 at 8:33 am
купить проведенный диплом высокие [url=https://frei-diplom4.ru/]купить проведенный диплом высокие[/url] .
Diplomi_bwOl
16 Oct 25 at 8:34 am
https://t.me/Online_1_xbet/2600
CharlesCic
16 Oct 25 at 8:35 am
https://t.me/Online_1_xbet/3403
CharlesCic
16 Oct 25 at 8:36 am
купить диплом товароведа [url=http://www.rudik-diplom11.ru]купить диплом товароведа[/url] .
Diplomi_ttMi
16 Oct 25 at 8:37 am
потолочкин натяжные потолки нижний новгород отзывы клиентов [url=https://www.stretch-ceilings-nizhniy-novgorod-1.ru]https://www.stretch-ceilings-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_rkOn
16 Oct 25 at 8:37 am
купить диплом в москве [url=www.rudik-diplom3.ru/]купить диплом в москве[/url] .
Diplomi_jgei
16 Oct 25 at 8:38 am
натяжные потолки официальный [url=https://stretch-ceilings-nizhniy-novgorod.ru/]stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_fhPl
16 Oct 25 at 8:38 am
Hello, I enjoy reading all of your article.
I wanted to write a little comment to support you.
39BET
16 Oct 25 at 8:39 am
сайт натяжные потолки [url=http://www.stretch-ceilings-nizhniy-novgorod-1.ru]сайт натяжные потолки[/url] .
natyajnie potolki nijnii novgorod_nbOn
16 Oct 25 at 8:39 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Узнай первым! – https://continental-food.co.uk/roasted-tomato-soup
Eugenetaulp
16 Oct 25 at 8:40 am
купить диплом в находке [url=http://www.rudik-diplom5.ru]купить диплом в находке[/url] .
Diplomi_poma
16 Oct 25 at 8:40 am
потолочкин натяжные [url=http://www.stretch-ceilings-nizhniy-novgorod.ru]http://www.stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_tlPl
16 Oct 25 at 8:40 am