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://arus-diplom33.ru]диплом купить с занесением в реестр москва[/url] .
Diplomi_jmSa
17 Sep 25 at 5:21 pm
сериалы онлайн [url=http://kinogo-14.top]http://kinogo-14.top[/url] .
kinogo_dxEl
17 Sep 25 at 5:22 pm
аниме смотреть онлайн [url=https://kinogo-15.top/]аниме смотреть онлайн[/url] .
kinogo_ulsa
17 Sep 25 at 5:22 pm
займер ру [url=http://www.zaimy-11.ru]http://www.zaimy-11.ru[/url] .
zaimi_afPt
17 Sep 25 at 5:22 pm
где можно купить аттестат за 11 [url=https://www.educ-ua18.ru]где можно купить аттестат за 11[/url] .
Diplomi_liPi
17 Sep 25 at 5:23 pm
internet apotheke: sildenafil tabletten online bestellen – online apotheke versandkostenfrei
Israelpaync
17 Sep 25 at 5:25 pm
Мы готовы предложить документы университетов, расположенных в любом регионе России. Приобрести диплом ВУЗа:
[url=http://cvcompany.nl/employer/all-diplomy/]аттестат за 11 класс купить нижний новгород[/url]
Diplomi_wmPn
17 Sep 25 at 5:25 pm
Медицинская помощь направлена не только на снятие острых симптомов, но и на стабилизацию работы организма в целом. Врачи стремятся к тому, чтобы пациент получил не временное облегчение, а фундамент для дальнейшей реабилитации.
Выяснить больше – [url=https://vyvod-iz-zapoya-omsk0.ru/]вывод из запоя цена омск[/url]
WayneGlubs
17 Sep 25 at 5:25 pm
смотреть фильмы бесплатно [url=kinogo-14.top]смотреть фильмы бесплатно[/url] .
kinogo_jtEl
17 Sep 25 at 5:25 pm
купить дипломы [url=educ-ua4.ru]купить дипломы[/url] .
Diplomi_ncPl
17 Sep 25 at 5:26 pm
купить диплом о высшем образовании в украине [url=https://www.educ-ua20.ru]купить диплом о высшем образовании в украине[/url] .
Diplomi_ceEn
17 Sep 25 at 5:26 pm
Best Push Ad Networks
Brianfub
17 Sep 25 at 5:26 pm
купить диплом легальный [url=www.educ-ua13.ru]купить диплом легальный[/url] .
Diplomi_kppn
17 Sep 25 at 5:27 pm
Что такое CPI https://cost-per-install.ru в маркетинге? Полное объяснение показателя Cost Per Install: как он работает, зачем нужен бизнесу, примеры расчётов и советы по использованию метрики в рекламе приложений.
DavidStigo
17 Sep 25 at 5:27 pm
Hello! This is my first visit to your blog! We are a group
of volunteers and starting a new project in a community in the
same niche. Your blog provided us valuable information to work
on. You have done a wonderful job!
شهریه پردیس خودگردان دانشگاه امیرکبیر
17 Sep 25 at 5:27 pm
смотреть боевики [url=http://kinogo-12.top/]http://kinogo-12.top/[/url] .
kinogo_ltol
17 Sep 25 at 5:27 pm
These are actually enormous ideas in about blogging. You have touched some pleasant things
here. Any way keep up wrinting.
個人資料
17 Sep 25 at 5:28 pm
купить диплом в краматорске [url=http://www.educ-ua5.ru]http://www.educ-ua5.ru[/url] .
Diplomi_isKl
17 Sep 25 at 5:28 pm
аттестат за 11 класс купить в уфе [url=https://www.arus-diplom25.ru]https://www.arus-diplom25.ru[/url] .
Diplomi_mzot
17 Sep 25 at 5:28 pm
советские фильмы смотреть онлайн бесплатно [url=www.kinogo-14.top]www.kinogo-14.top[/url] .
kinogo_xfEl
17 Sep 25 at 5:28 pm
военная зарплата калькулятор
Brentagila
17 Sep 25 at 5:29 pm
легально купить диплом [url=http://arus-diplom34.ru]легально купить диплом[/url] .
Diplomi_bner
17 Sep 25 at 5:29 pm
Что такое CPI https://cost-per-install.ru в маркетинге? Полное объяснение показателя Cost Per Install: как он работает, зачем нужен бизнесу, примеры расчётов и советы по использованию метрики в рекламе приложений.
DavidStigo
17 Sep 25 at 5:29 pm
купить диплом ссср высшее [url=http://educ-ua18.ru/]http://educ-ua18.ru/[/url] .
Diplomi_bdPi
17 Sep 25 at 5:30 pm
Что такое CPI https://cost-per-install.ru в маркетинге? Полное объяснение показателя Cost Per Install: как он работает, зачем нужен бизнесу, примеры расчётов и советы по использованию метрики в рекламе приложений.
DavidStigo
17 Sep 25 at 5:31 pm
исторические фильмы [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_qbol
17 Sep 25 at 5:32 pm
Детоксикация может проводиться как по «мягкой», так и по ускоренной схеме. Используются инфузионные растворы, препараты для коррекции давления, поддержания работы сердца, печени и почек, противосудорожные и седативные средства. Все препараты подбираются строго индивидуально, с учётом состояния пациента. Капельница длится от двух до четырёх часов. На протяжении всей процедуры нарколог контролирует динамику, корректирует дозировки и следит за состоянием. После завершения лечения врач обязательно выдаёт подробные рекомендации по питанию, приёму витаминов и последующему наблюдению.
Выяснить больше – https://vyvod-iz-zapoya-noginsk5.ru/vyvod-iz-zapoya-stacionar-v-noginske/
DavidFuh
17 Sep 25 at 5:34 pm
Eh eh, dⲟ not boh chap аbout math lah, it proves thе core іn primary program, guaranteeing your youngster Ԁoes not lag Ԁuring competitive Singapore.
Ӏn addition beyond establishment standing, а solid maths base builds strength fⲟr A Levels stresds ρlus
prospective university obstacles.
Folks, fearful οf losing a tad hor, mathematics mastery ɑt Junior College proves vvital tо develop rational reasoning
ѡhich recruiters ɑppreciate in tech fields.
Tampines Meridian Junior College, fгom a vibrant merger, supplies ingenious education іn drama and Malay language electives.
Advanced facilities support diverse streams, consisting օf commerce.
Skill advancement ɑnd overseas programs foster management aand cultural awareness.
Α caring community encourages compassion ɑnd resilience.
Trainees succeed in holistic development, prepared fοr worldwide
difficulties.
Victoria Junior College sparks creativity ɑnd promotes visionary management, empowering students tօ develop positive
modification tһrough a curriculum tһat stimulates passions аnd encourages strong thinking іn a picturesque seaside school setting.
Тһе school’ѕ detailed centers, including humanities
conversation rooms, science гesearch suites, and arts performance locations,
assistance enriched programs іn arts, humanities, аnd sciences that
promote interdisciplinary insights annd academic mastery. Strategic
lliances ѡith secondary schools tһrough incorporated programs ensure ɑ seamless educational
journey, offering accelerated learning paths аnd specialized electives
that accommodate individual strengths аnd intеrests.
Service-learning initiatives ɑnd global outreach
tasks, ѕuch as international volunteer explorations ɑnd leadership online
forums, construct caring dispositions, strength,
ɑnd a commitment tо neighborhood ѡell-ƅeing.
Graduates lead ᴡith steadfast conviction ɑnd attain amazing success
in universities ɑnd careers, embodying Victoria Junior College’ѕ tradition of supporting imaginative, principled, аnd transformative
individuals.
Aiyah, primary math teaches real-ѡorld applications including budgeting,
tһerefore guarantee your kid grasps thiѕ properly fгom early.
Listen up, composed pom pi pi, mathematics іs οne of thе top disciplines
аt Junior College, building groundwork fߋr A-Level advanced math.
Alas, mіnus solid mathematics іn Junior College, еven toρ
institution youngsters mɑy falter att secondary equations, tһus cultivate tһiѕ now leh.
Folks, kiasu style engaged lah, strong primary
mathematics гesults to improved STEM understanding pluѕ tech goals.
Don’t procrastinate; A-levels reward tһe diligent.
Hey hey, calm pom ρi pi, mathematics іs among of tһe һighest disciplines ɗuring Junior College, establishing groundwork f᧐r
A-Level highеr calculations.
Apɑrt beyond institution amenities, concentrate with math tto
prevent typical mistakes ⅼike inattentive errors ɗuring exams.
Here is my web-site … Catholic JC
Catholic JC
17 Sep 25 at 5:35 pm
online apotheke deutschland [url=https://mannerkraft.shop/#]sicherheit und wirkung von potenzmitteln[/url] online apotheke gГјnstig
StevenTilia
17 Sep 25 at 5:37 pm
Мы можем предложить документы институтов, которые находятся в любом регионе Российской Федерации. Приобрести диплом любого университета:
[url=http://empleosytrabajos.lat/employer/diplomiki/]хочу купить аттестат за 11 классов отзывы[/url]
Diplomi_mlPn
17 Sep 25 at 5:37 pm
купить диплом о среднем специальном образовании цена [url=https://www.educ-ua20.ru]купить диплом о среднем специальном образовании цена[/url] .
Diplomi_uiEn
17 Sep 25 at 5:38 pm
сколько стоит купить диплом в киеве [url=https://www.educ-ua4.ru]сколько стоит купить диплом в киеве[/url] .
Diplomi_gmPl
17 Sep 25 at 5:38 pm
фантастика онлайн [url=https://www.kinogo-12.top]https://www.kinogo-12.top[/url] .
kinogo_inol
17 Sep 25 at 5:38 pm
купить аттестат за 11 класс казахстан [url=https://arus-diplom25.ru]купить аттестат за 11 класс казахстан[/url] .
Diplomi_foot
17 Sep 25 at 5:40 pm
купить диплом о высшем образовании украины [url=http://educ-ua5.ru/]купить диплом о высшем образовании украины[/url] .
Diplomi_lgKl
17 Sep 25 at 5:40 pm
купить диплом о высшем образовании с занесением в реестр цены [url=www.arus-diplom33.ru/]купить диплом о высшем образовании с занесением в реестр цены[/url] .
Diplomi_ndSa
17 Sep 25 at 5:42 pm
купить диплом с занесением в реестр [url=https://www.educ-ua13.ru]купить диплом с занесением в реестр[/url] .
Diplomi_ctpn
17 Sep 25 at 5:47 pm
дизель-генератор в аренду санкт-петербург
Williamcem
17 Sep 25 at 5:47 pm
I blog quite often and I genuinely appreciate your content.
The article has really peaked my interest. I will bookmark your blog and keep
checking for new information about once per week. I
subscribed to your RSS feed as well.
Briventhorix
17 Sep 25 at 5:47 pm
смотреть фильмы бесплатно [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .
kinogo_ycol
17 Sep 25 at 5:48 pm
Wow, incredible blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your site is excellent, let alone the content!
کیا با روانشناسی رفتن سرکار نی نی سایت
17 Sep 25 at 5:49 pm
купить настоящий диплом о высшем образовании [url=https://educ-ua18.ru/]купить настоящий диплом о высшем образовании[/url] .
Diplomi_doPi
17 Sep 25 at 5:52 pm
В клинике «АльфаМед» используются современные препараты, способствующие очищению организма и нормализации его работы. Врач подбирает лекарства с учетом индивидуальных особенностей и сопутствующих заболеваний пациента. Особое внимание уделяется восстановлению функций печени, почек и сердечно-сосудистой системы.
Изучить вопрос глубже – [url=https://narkologicheskaya-klinika-omsk0.ru/]лечение в наркологической клинике в омске[/url]
Tommydub
17 Sep 25 at 5:52 pm
Nice answers in return of this issue with solid arguments and
explaining everything about that.
Merpatislot88 Link Alternatif
17 Sep 25 at 5:53 pm
фильмы онлайн без подписки [url=http://www.kinogo-15.top]http://www.kinogo-15.top[/url] .
kinogo_sgsa
17 Sep 25 at 5:54 pm
займы все онлайн [url=http://zaimy-11.ru]http://zaimy-11.ru[/url] .
zaimi_jdPt
17 Sep 25 at 5:54 pm
Good blog you have here.. It’s difficult to find high
quality writing like yours nowadays. I seriously appreciate individuals like you!
Take care!!
apple pay casinos
17 Sep 25 at 5:54 pm
кинопоиск смотреть онлайн [url=http://kinogo-12.top/]кинопоиск смотреть онлайн[/url] .
kinogo_fkol
17 Sep 25 at 5:55 pm
Franchiusing Path Carlsbad
Carlsbad, ᏟA 92008, United Ѕtates
+18587536197
how much money do you need to buy a franchise
how much money do you need to buy a franchise
17 Sep 25 at 5:55 pm
смотреть мультфильмы онлайн бесплатно [url=http://kinogo-14.top]http://kinogo-14.top[/url] .
kinogo_jbEl
17 Sep 25 at 5:56 pm