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.arus-diplom34.ru]купить диплом с реестром отзывы[/url] .
Diplomi_fier
17 Aug 25 at 2:22 am
купить аттестат за 11 класс ярославль [url=https://arus-diplom23.ru]купить аттестат за 11 класс ярославль[/url] .
Diplomi_yaSr
17 Aug 25 at 2:23 am
спортивные новости [url=http://www.novosti-sporta-2.ru]http://www.novosti-sporta-2.ru[/url] .
novosti sporta_nzsa
17 Aug 25 at 2:24 am
кривой рог купить диплом о высшем образовании [url=https://www.educ-ua1.ru]кривой рог купить диплом о высшем образовании[/url] .
Diplomi_aeei
17 Aug 25 at 2:30 am
В Москве к вашим услугам скорая наркологическая помощь от Narcology Clinic — выезд врача 24/7, качественная помощь при алкогольной интоксикации, стабилизация состояния и организация дальнейших этапов детоксикации.
Подробнее тут – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]круглосуточная наркологическая помощь[/url]
TerryPROOT
17 Aug 25 at 2:32 am
Kamagra oral jelly USA availability: Compare Kamagra with branded alternatives – ED treatment without doctor visits
RichardTit
17 Aug 25 at 2:38 am
купить диплом легальный о высшем образовании [url=https://www.arus-diplom33.ru]https://www.arus-diplom33.ru[/url] .
Diplomi_ycSa
17 Aug 25 at 2:38 am
Наркологическая клиника “Чистый Путь” — это специализированное медицинское учреждение, предоставляющее помощь людям, страдающим от алкогольной и наркотической зависимости. Наша цель — помочь пациентам справиться с зависимостью, вернуться к здоровой и полноценной жизни, используя эффективные методы лечения и всестороннюю поддержку.
Разобраться лучше – https://срочно-вывод-из-запоя.рф/vyvod-iz-zapoya-v-kruglosutochno-v-chelyabinske.xn--p1ai
Elmerlar
17 Aug 25 at 2:40 am
Если требуется экстренная помощь при алкогольном кризисе — Narcology Clinic Москва предоставляет срочную помощь на дому: выезд нарколога, купирование симптомов, мониторинг состояния, без очередей и задержек.
Разобраться лучше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]круглосуточная наркологическая помощь московская область[/url]
Robertkix
17 Aug 25 at 2:46 am
prix du viagra 50mg [url=https://sildenapeak.shop/#]SildenaPeak[/url] pharmacy rx viagra
RobertCat
17 Aug 25 at 2:46 am
купить диплом о высшем образовании с занесением в реестр цена [url=www.arus-diplom34.ru]купить диплом о высшем образовании с занесением в реестр цена[/url] .
Diplomi_kner
17 Aug 25 at 2:47 am
My partner and I stumbled over here by a different web address and thought
I might as well check things out. I like what I see so now i am following you.
Look forward to going over your web page repeatedly.
artis indonesia bokep
17 Aug 25 at 2:50 am
This paragraph gives clear idea designed for the new users of
blogging, that in fact how to do running a blog.
trang chủ 69VN
17 Aug 25 at 2:52 am
купить аттестат за 11 класс в нижнем тагиле на [url=http://www.arus-diplom23.ru]купить аттестат за 11 класс в нижнем тагиле на[/url] .
Diplomi_lwSr
17 Aug 25 at 2:53 am
купить аттестат за 11 класс в школе [url=https://arus-diplom23.ru]купить аттестат за 11 класс в школе[/url] .
Diplomi_niol
17 Aug 25 at 2:56 am
купить диплом с занесением в реестр в мурманске [url=www.arus-diplom33.ru]купить диплом с занесением в реестр в мурманске[/url] .
Diplomi_xzSa
17 Aug 25 at 2:59 am
dove posso acquistare stromectol generico
come posso acquistare stromectol generico in pillole
17 Aug 25 at 3:05 am
купить диплом техникума с занесением в реестр [url=https://arus-diplom33.ru/]купить диплом техникума с занесением в реестр[/url] .
Diplomi_koSa
17 Aug 25 at 3:05 am
прогнозы на хоккей с высокой проходимостью [url=https://luchshie-prognozy-na-khokkej13.ru/]luchshie-prognozy-na-khokkej13.ru[/url] .
lychshie prognozi na hokkei_yhEa
17 Aug 25 at 3:06 am
Online sources for Kamagra in the United States: Online sources for Kamagra in the United States – Safe access to generic ED medication
PeterTEEFS
17 Aug 25 at 3:08 am
купить диплом с занесением в реестр чита [url=http://www.arus-diplom34.ru]http://www.arus-diplom34.ru[/url] .
Diplomi_geer
17 Aug 25 at 3:08 am
купить легальный аттестат за 11 классов [url=https://arus-diplom21.ru/]купить легальный аттестат за 11 классов[/url] .
Diplomi_bhPr
17 Aug 25 at 3:10 am
Кроме того, клиника «Новый шанс» уделяет особое внимание профилактике рецидивов. Мы обучаем пациентов навыкам управления стрессом, эмоциональной регуляции и прививаем навыки здорового образа жизни. Наша цель — обеспечить долгосрочное восстановление и снизить риск возврата к зависимости.
Подробнее можно узнать тут – [url=https://tajno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-kruglosutochno-v-rostove-na-donu.ru/]вывод из запоя на дому круглосуточно в ростове-на-дону[/url]
ParisCappy
17 Aug 25 at 3:10 am
Nice post. I was checking constantly this weblog and I’m inspired!
Very helpful information specially the remaining phase 🙂 I maintain such information much.
I used to be looking for this certain information for a
long time. Thanks and best of luck.
red dog casino
17 Aug 25 at 3:12 am
купить диплом высшем образовании занесением реестр [url=https://www.arus-diplom35.ru]купить диплом высшем образовании занесением реестр[/url] .
Kypit diplom o visshem obrazovanii!_seot
17 Aug 25 at 3:14 am
купить аттестат за 11 класс новосибирск [url=http://arus-diplom23.ru]http://arus-diplom23.ru[/url] .
Diplomi_gdSr
17 Aug 25 at 3:14 am
купить диплом с занесением в реестр в кемерово [url=www.arus-diplom34.ru]www.arus-diplom34.ru[/url] .
Diplomi_wver
17 Aug 25 at 3:15 am
купить аттестаты за 11 класс курган [url=https://arus-diplom22.ru]купить аттестаты за 11 класс курган[/url] .
Diplomi_mvKt
17 Aug 25 at 3:15 am
купить свидетельство о расторжении брака [url=http://educ-ua1.ru]http://educ-ua1.ru[/url] .
Diplomi_izei
17 Aug 25 at 3:16 am
новости спорта сегодня [url=http://novosti-sporta-3.ru]http://novosti-sporta-3.ru[/url] .
novosti sporta_bamn
17 Aug 25 at 3:28 am
Оптимально для пациентов в стабильном состоянии. Процедура начинается с приезда врача, осмотра и постановки капельницы с индивидуально подобранными растворами.
Исследовать вопрос подробнее – https://narko-zakodirovan2.ru
MarvinGon
17 Aug 25 at 3:28 am
купить аттестат за 11 класс в иркутске [url=www.arus-diplom9.ru]www.arus-diplom9.ru[/url] .
Diplomi_plEi
17 Aug 25 at 3:30 am
What i don’t realize is actually how you are now not really much more smartly-preferred than you may be right now.
You’re so intelligent. You know thus considerably relating to this
matter, made me in my view believe it from a
lot of varied angles. Its like women and men don’t seem to be interested except it is one thing to accomplish with Woman gaga!
Your personal stuffs outstanding. Always take care of it up!
Dog Collar
17 Aug 25 at 3:31 am
купить диплом украина [url=http://www.educ-ua1.ru]купить диплом украина[/url] .
Diplomi_zkei
17 Aug 25 at 3:33 am
OMT’s standalone e-learning options empower independent exploration, supporting аn individual love for mathematics аnd
exam aspiration.
Օpen yoᥙr child’ѕ full capacity іn mathematics with OMT Math Tuition’ѕ expert-led
classes, tailored tօ Singapore’s MOE syllabus foг primary, secondary, ɑnd JC students.
The holistic Singapore Math method, ѡhich develops multilayered рroblem-solving capabilities,
highlights ԝhy math tuition iѕ vital for mastering the curriculum аnd preparing foг future professions.
Ϝօr PSLE success, tuition prⲟvides tailored guidance
tο weak locations, like ratio and portion problems, avoiding common risks during the exam.
Secondary math tuition conquers tһе restrictions оf largе class dimensions, ցiving concentrated interеѕt that boosts
understanding fߋr Օ Level preparation.
In a competitive Singaporean education ѕystem, junior college math
tuition οffers pupils the ѕide to attain hіgh qualities necеssary for university admissions.
Ꮃhat sets арart OMT іѕ its proprietary program tһat matches MOE’ѕ viа emphasis
on moral analytical іn mathematical contexts.
Specialist pointers іn videos offer faster ᴡays lah, assisting you fіx
questions faster and rack up mսch more in tests.
Witһ global competition increasing, math tuition settings Singapore
trainees ɑѕ tօp entertainers in worldwide math analyses.
Нere iѕ my webpage :: junior college maths tuition
junior college maths tuition
17 Aug 25 at 3:34 am
купить диплом об образовании с занесением в реестр [url=arus-diplom33.ru]купить диплом об образовании с занесением в реестр[/url] .
Diplomi_rvSa
17 Aug 25 at 3:36 am
Современная наркология предлагает два основных формата вывода из запоя:
Углубиться в тему – https://nadezhnyj-vyvod-iz-zapoya.ru/
MichaelMes
17 Aug 25 at 3:37 am
Наркологическая клиника “Маяк надежды” — специализированное медицинское учреждение, предназначенное для оказания помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и вернуть их к здоровой и полноценной жизни.
Узнать больше – https://алко-лечение24.рф/vivod-iz-zapoya-v-stacionare-v-Sankt-Peterburge
JasonLoorm
17 Aug 25 at 3:42 am
Magnificent items from you, man. I’ve take note your stuff prior to
and you are simply extremely wonderful. I actually like what you have bought right here, really like what you are stating and the best way in which you say it.
You are making it enjoyable and you still take care
of to keep it wise. I can not wait to read far more from you.
This is actually a great site.
https://789club.lt/
17 Aug 25 at 3:42 am
Love these insights. I always go with Get Seeds Right Here Get Clones
Right Here for live plants.
Grow a clone and smoke your own
17 Aug 25 at 3:44 am
20
Выяснить больше – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]наркологическая помощь москва[/url]
BernardCar
17 Aug 25 at 3:49 am
Someone essentially assist to make seriously posts
I’d state. This is the first time I frequented your web page and so far?
I surprised with the research you made to create this actual put up
extraordinary. Wonderful task!
LINK WW88
17 Aug 25 at 3:49 am
я купил диплом с проводкой [url=http://arus-diplom31.ru/]я купил диплом с проводкой[/url] .
Priobresti diplom lubogo yniversiteta!_erOl
17 Aug 25 at 3:49 am
новости спорта сегодня [url=www.novosti-sporta-3.ru/]www.novosti-sporta-3.ru/[/url] .
novosti sporta_aqmn
17 Aug 25 at 3:54 am
Incredible! This blog looks just like my old one!
It’s on a completely different topic but it has pretty much the same layout and design. Wonderful choice of colors!
HM88 COM
17 Aug 25 at 3:54 am
Во-вторых, индивидуальный подход к каждому пациенту. Учитываются личные особенности, такие как возраст, пол, социальный статус. Это позволяет создать эффективный план лечения.
Выяснить больше – http://
Stevengal
17 Aug 25 at 3:56 am
как купить диплом техникума с занесением в реестр цена в [url=https://www.arus-diplom33.ru]как купить диплом техникума с занесением в реестр цена в[/url] .
Diplomi_ygSa
17 Aug 25 at 3:57 am
Way cool! Some extremely valid points! I appreciate you penning
this post plus the rest of the website is very good.
slot777
17 Aug 25 at 4:04 am
Мы понимаем уникальность каждого пациента и проводим тщательную диагностику, анализируя его медицинскую историю, психологическое состояние и социальные факторы. На основе полученных данных создаем персональные планы лечения, включающие медикаментозные средства, психотерапию и социальные программы.
Узнать больше – http://медицинский-вывод-из-запоя.рф/
Philipkam
17 Aug 25 at 4:04 am
инъектирование [url=http://www.remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi ]http://www.remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi [/url] .
inektirovanie_ktOr
17 Aug 25 at 4:10 am