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-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_awPt
15 Oct 25 at 12:59 pm
1win bonus kodu [url=http://1win5005.com]http://1win5005.com[/url]
1win_irml
15 Oct 25 at 12:59 pm
купить диплом в владикавказе [url=rudik-diplom13.ru]rudik-diplom13.ru[/url] .
Diplomi_qhon
15 Oct 25 at 12:59 pm
mexico prescription online [url=https://medicosur.com/#]pharmacy in mexico online[/url] mexico pharmacy
CareyMag
15 Oct 25 at 1:00 pm
Сертификация одежды – это многоступенчатый процесс, подтверждающий соответствие продукции установленным стандартам качества, безопасности и экологичности.
В современном мире, где потребители становятся все более осознанными, наличие сертификата является важным конкурентным преимуществом для производителей. Как происходит [url=https://forum.sportmashina.com/index.php?threads/professionalnaja-sertifikacija-odezhdy.24399/]сертификация одежды[/url]
Willieken
15 Oct 25 at 1:02 pm
где купить диплом техникума [url=https://frei-diplom8.ru]где купить диплом техникума[/url] .
Diplomi_ohsr
15 Oct 25 at 1:02 pm
потолочкин натяжные потолки нижний новгород официальный сайт [url=http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_wyma
15 Oct 25 at 1:04 pm
https://fpgeeks.com/forum/showthread.php/47695-%D0%9E%D0%BF%D1%8B%D1%82-%D0%B1%D1%80%D0%BE%D0%BD%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D1%87%D0%B5%D1%80%D0%B5%D0%B7-Otello?p=449042#post449042
Nathanhip
15 Oct 25 at 1:05 pm
wonderful issues altogether, you simply won a new reader.
What could you suggest in regards to your post that you simply made
some days ago? Any positive?
roofing contractors springboro
15 Oct 25 at 1:06 pm
More methods
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
More methods
15 Oct 25 at 1:06 pm
1win oyun izləmək [url=https://www.1win5005.com]https://www.1win5005.com[/url]
1win_ptml
15 Oct 25 at 1:08 pm
купить диплом гознак [url=https://rudik-diplom9.ru/]купить диплом гознак[/url] .
Diplomi_wpei
15 Oct 25 at 1:08 pm
With timed drills tһat feel liкe adventures, OMT develops test stamina ԝhile
strengthening affection fⲟr tһе topic.
Dive into self-paced mathematics mastery ᴡith OMT’s 12-month e-learning courses, complete with practice
worksheers ɑnd tape-recorded sessions fօr thorough modification.
Singapore’ѕ focus оn vital thinking tһrough mathematics highlights tһe value
of math tuition, ԝhich helps trainees develop tһe analytical
abilities required ƅy the country’ѕ forward-thinking syllabus.
Improving primary education ѡith mqth tuition prepares trainees fߋr PSLE by
cultivating ɑ growth stɑte of mind towаrds tough
topics ⅼike proportion аnd transformations.
Secondary math tuition lays ɑ strong foundation fоr
post-О Level researches, ѕuch ɑѕ A Levels oг polytechnic programs,
by excelling іn fundamental subjects.
Junior college math tuition іs vital fоr A Degrees aѕ it deepen understanding ⲟf advanced calculus subjects like combination strategies аnd differential formulas, ᴡhich ɑre central to the test syllabus.
The exclusive OMT curriculum distinctively boosts tһe MOE
curriculum ԝith concentrated method ᧐n heuristic approaϲhеs,
preparing students mսch better for exam difficulties.
Tape-recorded sessions іn OMT’s syѕtem let yοu rewind and replay
lah, ensuring you comprehend еverү idea fοr excellent examination outcomes.
Math tuition supports а development mindset, encouraging Singapore trainees tο watch obstacles aѕ opportunities for exam quality.
Ꮋere іѕ mү blog:online classes math tuition singapore
online classes math tuition singapore
15 Oct 25 at 1:10 pm
Salutations, passionnes de jeux en ligne !
Je viens de trouver un article avec des details tout frais sur le jeu Plinko dans les sites francais.
Si tu es fan de ce jeu, cette lecture est fortement conseillee.
Lis tout cela via le lien qui suit :
plinko
Haroldutell
15 Oct 25 at 1:10 pm
куплю диплом цена [url=https://www.rudik-diplom1.ru]куплю диплом цена[/url] .
Diplomi_cher
15 Oct 25 at 1:11 pm
https://telegra.ph/Kakoj-kupit-radar-detektor-signaturnyj-10-11
DennisNeene
15 Oct 25 at 1:12 pm
Огромное спасибо за платформу kazino olimp —
очень выручает!
бонустар
бонустар
15 Oct 25 at 1:13 pm
Asking questions are actually fastidious thing if you are not understanding something entirely, but
this article gives nice understanding yet.
best online casinos
15 Oct 25 at 1:14 pm
https://bs2tsite1.at
Hermannalia
15 Oct 25 at 1:14 pm
где купить диплом колледжа омск [url=https://frei-diplom8.ru/]https://frei-diplom8.ru/[/url] .
Diplomi_vvsr
15 Oct 25 at 1:14 pm
Эта познавательная публикация погружает вас в море интересного контента, который быстро захватит ваше внимание. Мы рассмотрим важные аспекты темы и предоставим вам уникальные Insights и полезные сведения для дальнейшего изучения.
Не упусти шанс – https://webtest.nagaland.gov.in/statistics/2024/01/24/registration-of-births-deaths-2014
Ricardowhisy
15 Oct 25 at 1:16 pm
купить диплом москва с занесением в реестр [url=http://frei-diplom1.ru]купить диплом москва с занесением в реестр[/url] .
Diplomi_ojOi
15 Oct 25 at 1:19 pm
сайт натяжных потолков [url=http://stretch-ceilings-nizhniy-novgorod-1.ru/]сайт натяжных потолков[/url] .
natyajnie potolki nijnii novgorod_moOn
15 Oct 25 at 1:20 pm
потолочкин натяжные потолки нижний новгород отзывы [url=https://natyazhnye-potolki-nizhniy-novgorod.ru/]https://natyazhnye-potolki-nizhniy-novgorod.ru/[/url] .
natyajnie potolki nijnii novgorod_vnOt
15 Oct 25 at 1:20 pm
wettstrategien livewetten
Also visit my blog beste bonusbedingungen sportwetten (oldtimer.wp-dev-Staging.de)
oldtimer.wp-dev-Staging.de
15 Oct 25 at 1:21 pm
диплом мед колледжа купить в [url=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_xlPt
15 Oct 25 at 1:21 pm
Hey there! I know this is kinda off topic but I’d figured I’d ask.
Would you be interested in trading links or maybe guest writing a
blog post or vice-versa? My website discusses a lot of the same topics as yours and I think we could greatly benefit from each other.
If you are interested feel free to shoot me an e-mail.
I look forward to hearing from you! Superb blog by the way!
au88.com
15 Oct 25 at 1:23 pm
Join ATASPANKING, the premier spanking club and community.
Explore exciting content, connect with enthusiasts, and enjoy a
safe, welcoming environment.
Punishments
15 Oct 25 at 1:24 pm
Link gue naik gara-gara ini.
maxwin spam
15 Oct 25 at 1:25 pm
купить диплом в междуреченске [url=www.rudik-diplom9.ru/]www.rudik-diplom9.ru/[/url] .
Diplomi_awei
15 Oct 25 at 1:26 pm
Right here is the perfect blog for anyone who hopes to
find out about this topic. You realize so much its almost tough to argue with you (not
that I really will need to…HaHa). You definitely put a
new spin on a topic that has been discussed for many years.
Excellent stuff, just wonderful!
local pet acupuncture
15 Oct 25 at 1:27 pm
купить диплом в ухте [url=https://rudik-diplom7.ru]купить диплом в ухте[/url] .
Diplomi_agPl
15 Oct 25 at 1:28 pm
В стационаре предусмотрены одноместные и двухместные палаты с удобствами, телевизором и беспроводным интернетом. Медсестры дежурят круглосуточно, врачи проводят обходы и при необходимости меняют схему инфузий или назначают дополнительные процедуры. Пациентам обеспечивают сбалансированное питание, соответствующее диетическим требованиям при детоксикации.
Подробнее можно узнать тут – [url=https://narcologicheskaya-klinika-ekaterinburg0.ru/]платная наркологическая клиника[/url]
RickyRaw
15 Oct 25 at 1:29 pm
После прибытия на место врач проводит тщательное обследование пациента. Измеряются основные физиологические параметры — артериальное давление, частота пульса, сатурация кислорода, температура тела. Проводится экспресс-анализ крови на сахар и кислотно-щелочной баланс. Также врач проводит оценку неврологического и психического статуса пациента, проверяет уровень сознания по шкале Глазго, выявляет признаки возможных осложнений: отёка мозга, энцефалопатии, алкогольного делирия. При необходимости принимается решение о дополнительной поддержке (например, вызов реанимационной бригады или немедленный перевод в стационар).
Ознакомиться с деталями – [url=https://narkologicheskaya-pomoshh-novosibirsk0.ru/]вызвать наркологическую помощь[/url]
Randybubre
15 Oct 25 at 1:31 pm
Howdy fantastic website! Does running a blog similar to this require a great
deal of work? I’ve no expertise in programming however I had been hoping
to start my own blog soon. Anyhow, if you have any
ideas or tips for new blog owners please share.
I know this is off subject nevertheless I just wanted to ask.
Many thanks!
homepage
15 Oct 25 at 1:32 pm
OMT’ѕ multimedia resources, lіke involving video clips, mаke mathematics cⲟme active, assisting Singapore pupils fаll passionately in love ѡith it for test success.
Founded іn 2013 by Mг. Justin Tan, OMT Math Tuition һаѕ actually helped countless trainees ace exams
ⅼike PSLE, O-Levels, and А-Levels with tested analytical strategies.
Ӏn a system whеre math education haas ɑctually progressed tߋ foster innovation and worldwide competitiveness, enrolling іn math tuition ensures students stay ahead bү deepening tһeir understanding and application օf
essential principles.
Math tuition addresses specific learning speeds, enabling primary school trainees
t᧐ deepen understanding ⲟf PSLE subjects ⅼike location, border,
ɑnd volume.
Tuition fosters innovative analytic skills, іmportant
for fixing tһe complex, multi-step questions tһat define O Level math challenges.
Ϝоr thߋsе pursuing Ꮋ3 Mathematics, junior college tuition uѕeѕ sophisticated assistance ߋn research-level topics
to excel іn this difficult extension.
Tһe proprietary OMT curriculum differs ƅy extending MOE curriculum
with enrichment on analytical modeling, ideal fⲟr data-driven examiination questions.
All natural strategy іn on the internet tuition one,
nurturing not simply skills howеνer enthusiasm foг mathematics аnd best quality success.
Ӏn Singapore, whеre math effectiveness оpens doors to STEM jobs, tuition іs
essential for strong examination structures.
mү website; singapore math tutor los angeles
singapore math tutor los angeles
15 Oct 25 at 1:32 pm
Cập nhật link xem trực tiếp đá gà CPC2 mỗi ngày tại 88daga.
Theo dõi những trận đấu nảy lửa từ các
trường gà uy tín với chất lượng video sắc
nét và bình luận hấp dẫn. Tham gia ngay!
CPC2 Archives - Daga88: trực tiếp đá gà Thomo
15 Oct 25 at 1:33 pm
Hello mates, how is all, and what you desire to say on the topic of this article,
in my view its in fact amazing in favor of me.
spinfest casino no deposit bonus
15 Oct 25 at 1:33 pm
купить диплом в ленинск-кузнецком [url=https://rudik-diplom4.ru]https://rudik-diplom4.ru[/url] .
Diplomi_lwOr
15 Oct 25 at 1:33 pm
Hi there, all is going well here and ofcourse every one is sharing information, that’s in fact fine, keep
up writing.
casino utan svensk licens snabba uttag
15 Oct 25 at 1:34 pm
диплом нефтяного техникума купить [url=http://frei-diplom8.ru/]диплом нефтяного техникума купить[/url] .
Diplomi_rzsr
15 Oct 25 at 1:35 pm
купить диплом дизайнера [url=www.rudik-diplom13.ru]купить диплом дизайнера[/url] .
Diplomi_zhon
15 Oct 25 at 1:36 pm
купить диплом с занесением в реестр казань [url=https://frei-diplom1.ru]https://frei-diplom1.ru[/url] .
Diplomi_hbOi
15 Oct 25 at 1:38 pm
купить диплом журналиста [url=www.rudik-diplom3.ru]купить диплом журналиста[/url] .
Diplomi_liei
15 Oct 25 at 1:39 pm
купить диплом химика [url=http://www.rudik-diplom2.ru]купить диплом химика[/url] .
Diplomi_ehpi
15 Oct 25 at 1:39 pm
куплю диплом младшей медсестры [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_kikt
15 Oct 25 at 1:40 pm
купить диплом магистра [url=http://rudik-diplom6.ru/]купить диплом магистра[/url] .
Diplomi_qyKr
15 Oct 25 at 1:42 pm
купить диплом с занесением в реестр в москве [url=https://frei-diplom6.ru]купить диплом с занесением в реестр в москве[/url] .
Diplomi_mnOl
15 Oct 25 at 1:42 pm
https://telegra.ph/Kupit-v-kemerovskoj-oblasti-teplovizionnyj-pricel-10-12-4
DennisNeene
15 Oct 25 at 1:42 pm
купить диплом колледжа спб [url=http://www.frei-diplom9.ru]http://www.frei-diplom9.ru[/url] .
Diplomi_ujea
15 Oct 25 at 1:44 pm