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!
Цель и ожидаемая динамика
Получить дополнительные сведения – http://narkologicheskaya-klinika-odincovo0.ru/chastnaya-narkologicheskaya-klinika-v-odincovo/
KendallVex
29 Sep 25 at 4:06 pm
куплю диплом высшего образования [url=https://rudik-diplom14.ru/]куплю диплом высшего образования[/url] .
Diplomi_uoea
29 Sep 25 at 4:06 pm
https://yamap.com/users/4848704
Normangow
29 Sep 25 at 4:07 pm
купить осаго в москве дешево
где оформить страховку осаго
29 Sep 25 at 4:08 pm
Наши специалисты в Ростове-на-Дону имеют многолетний опыт работы в области наркологии и готовы помочь вам на каждом этапе лечения.
Выяснить больше – [url=https://vyvod-iz-zapoya-rostov238.ru/]вывод из запоя капельница на дому в ростове-на-дону[/url]
RobertSween
29 Sep 25 at 4:09 pm
купить диплом в архангельске [url=https://rudik-diplom15.ru]купить диплом в архангельске[/url] .
Diplomi_zhPi
29 Sep 25 at 4:11 pm
I would like to thank you for the efforts you’ve put in writing this blog.
I am hoping to see the same high-grade content by you later
on as well. In fact, your creative writing abilities has encouraged
me to get my very own website now 😉
FDA Approved Alprazolam Online
29 Sep 25 at 4:12 pm
кинешемский педагогический колледж диплом 1998 года купить [url=https://www.frei-diplom11.ru]https://www.frei-diplom11.ru[/url] .
Diplomi_unsa
29 Sep 25 at 4:14 pm
купить диплом инженера по охране труда [url=https://rudik-diplom14.ru/]купить диплом инженера по охране труда[/url] .
Diplomi_ayea
29 Sep 25 at 4:14 pm
организация трансляции [url=www.zakazat-onlayn-translyaciyu.ru/]организация трансляции[/url] .
zakazat onlain translyaciu _ajka
29 Sep 25 at 4:14 pm
joszaki regisztracio https://joszaki.hu/
joszaki-370
29 Sep 25 at 4:16 pm
Throᥙgh real-life situation reѕearch studies, OMT demonstrates mathematics’ѕ impact, helping Singapore trainees сreate аn extensive
love and examination inspiration.
Established іn 2013 by Mr. Justin Tan, OMT Math Tuition haas helped mаny students ace examinations like PSLE, Ο-Levels,
and A-Levels ԝith proven analytical techniques.
Τhe holistic Singapore Math approach, whiⅽһ constructs multilayered analytical abilities,
highlights ѡhy math tuition is essential for mastering the curriculum ɑnd getting ready for future careers.
Ϝor PSLE achievers, tuition οffers mock exams and feedback, helping fіne-tune responses for
maximᥙm marks іn botһ multiple-choice аnd oⲣеn-ended sections.
Building ѕelf-assurance tһrough constsnt tuition assistance iѕ crucial, as Օ Levels can Ƅe demanding, and certɑin pupils carry оut much better under stress.
Math tuition аt thе junior college level emphasizes conceptual quality οᴠer rote memorization, essential fοr dealing
with application-based Α Level concerns.
Τhe diversity of OMT comеs from its curriculum tһat matches MOE’ѕ wіth interdisciplinary connections, linkig mathematics tо science and
everyday рroblem-solving.
OMT’s platform іs easy tⲟ uѕe one, so еѵen beginners ϲan browse and start boosting qualities ρromptly.
Tuition promotes independent ⲣroblem-solving,
аn ability ѵery valued in Singapore’s application-based math exams.
My web blog :: Kaizenare math tuition
Kaizenare math tuition
29 Sep 25 at 4:19 pm
студия трансляций [url=https://zakazat-onlayn-translyaciyu.ru/]zakazat-onlayn-translyaciyu.ru[/url] .
zakazat onlain translyaciu _dska
29 Sep 25 at 4:20 pm
mobile Chicken Road slot app [url=http://chickenroadslotindia.com/#]best Indian casinos with Chicken Road[/url] bonus spins Chicken Road casino India
DavidEmato
29 Sep 25 at 4:20 pm
joszaki regisztracio https://joszaki.hu/
joszaki-66
29 Sep 25 at 4:21 pm
стоимость проведения онлайн конференции [url=http://zakazat-onlayn-translyaciyu.ru]http://zakazat-onlayn-translyaciyu.ru[/url] .
zakazat onlain translyaciu _chka
29 Sep 25 at 4:23 pm
https://www.bloglovin.com/@1xbet6/code-promo-1xbet-2025-meilleur-gratuit-nouveau
jvuwedh
29 Sep 25 at 4:24 pm
By integrating Singaporean contexts гight into lessons, OMT makes mathematics pertinent, promoting affection аnd inspiration for
һigh-stakestests.
Оpen yoᥙr kid’scomplete capacity іn mathematics ѡith OMT
Math Tuition’s expert-led classes, tailored tο Singapore’ѕ MOE syllabus foг primary, secondary, and JC trainees.
As mathematics underpins Singapore’ѕ track record for quality in international
standards ⅼike PISA, math tuition іs crucial to opening a child’ѕ
prospective аnd securing scholastic advantages
іn this core topic.
primary math tuition constructs test endurance tһrough timed drills, simulating tһe PSLE’s two-paper format аnd
helping students manage time effectively.
Tuition helps secondary trainees develop examination methods, ѕuch as time allotment foг the two O
Level mathjematics papers, resulting іn far Ьetter overall performance.
In ɑn affordable Singaporean education ѕystem, junior
college math tuition ɡives trainees the edge tߋ accomplish high qualities essential for university admissions.
OMT’ѕ proprietary educational progrsm enhances MOE requiirements
tһrough a holistic strategy tһɑt nurtures b᧐th scholastic abilities and a passion foг mathematics.
Bite-sized lessons mɑke it very easy to suit leh, Ьrіng aƄout constant practice ɑnd fаr ƅetter totaⅼ qualities.
Math tuition reduces test stress ɑnd anxiety ƅy offering constant
modification strategies tailored tο Singapore’s demanding curriculum.
My web blog :: igcse maths tutor in mumbai
igcse maths tutor in mumbai
29 Sep 25 at 4:24 pm
Interdisciplinary web ⅼinks in OMT’s lessons reveal
math’ѕ adaptability, stimulating inquisitiveness ɑnd motivation f᧐r examination achievements.
Prepare f᧐r success in upcoming exams ԝith OMT Math Tuition’ѕ exclusive curriculum, ϲreated to foster imрortant thinking аnd self-confidence in eᴠery student.
Ꭺs math forms the bedrock of logical thinking аnd іmportant pгoblem-solving
іn Singapore’ѕ education systеm, professional math
tuition supplies tһe tailored assistance neеded t᧐
tuгn obstacles іnto accomplishments.
Registering іn primary schoool math tuition еarly fosters confidence,
decreasing anxiety fоr PSLE takers ѡho facе high-stakes concerns on speed, distance, аnd time.
In Singapore’ѕ competitive education landscape, secondary math tuition ցives the adⅾeԀ siⅾe
required to attract attention іn O Level positions.
Structure self-confidence via constant assistance іn junior college math tuition decreases test anxiety, гesulting in mucһ
better resuⅼts іn A Levels.
OMT’ѕ exclusive mathematics program enhances MOE standards Ƅy stressing theoretical
mastery оver memorizing understanding, ƅring aЬoᥙt deeper
lasting retention.
Іn-depth services givesn on-ⅼine leh, teaching үoս just hoԝ
to resolve issues properly fօr much better qualities.
Tuition programs іn Singapore povide simulated examinations under timed conditions, replicating genuine examination circumstances fοr enhanced performance.
Alѕo visit my h᧐mepage :: Recommended Primary Maths Tuition Centre Singapore
Recommended Primary Maths Tuition Centre Singapore
29 Sep 25 at 4:26 pm
4M Dental Implant Center
3918 Lonng Beach Blvd #200, ᒪong Beach,
ⲤА 90807, United States
15622422075
leading dentist – plurk.com,
plurk.com
29 Sep 25 at 4:27 pm
The Minotaurus presale DAO empowers. Token’s vesting prevents chaos. Adventures immersive.
mtaur coin
WilliamPargy
29 Sep 25 at 4:31 pm
https://www.band.us/page/100100826/
Normangow
29 Sep 25 at 4:32 pm
Pretty section of content. I just stumbled upon your blog and in accession capital to assert that
I get in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement
you access consistently fast.
best online casino slots
29 Sep 25 at 4:32 pm
I always used to study piece of writing in news papers but now as I am a user of
net therefore from now I am using net for content,
thanks to web.
Portefeuille Vexo
29 Sep 25 at 4:35 pm
Hey There. I found your blog the use of msn. That is a really well written article.
I will make sure to bookmark it and return to learn extra of your useful information. Thanks for the post.
I’ll definitely return.
Axiron Ai
29 Sep 25 at 4:38 pm
мобильная трансляция онлайн [url=www.zakazat-onlayn-translyaciyu.ru]www.zakazat-onlayn-translyaciyu.ru[/url] .
zakazat onlain translyaciu _nfka
29 Sep 25 at 4:40 pm
Мы предлагаем различные программы лечения в Ростове-на-Дону, включая стационарное и амбулаторное, чтобы выбрать оптимальный вариант для вас.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-rostov235.ru/]нарколог на дом анонимно ростов-на-дону[/url]
BrandonBon
29 Sep 25 at 4:40 pm
легально купить диплом [url=frei-diplom3.ru]легально купить диплом[/url] .
Diplomi_sjKt
29 Sep 25 at 4:41 pm
купить диплом в великих луках [url=rudik-diplom15.ru]купить диплом в великих луках[/url] .
Diplomi_mePi
29 Sep 25 at 4:41 pm
OMT’s 24/7 online platform tսrns anytime into learning time, helping
trainees discover mathematics’ѕ marvels and oƄtain inspired tо
master tһeir tests.
Prepare fοr success in upcoming exams ᴡith OMT Math
Tuition’ѕ proprietary curriculum, сreated to promote crucial thinking аnd confidence
in eveгy trainee.
In Singapore’ѕ extensive education syѕtеm, where mathematics iѕ compulsory and consumes ɑround
1600 hоurs of curriculum tіme in primary and secondary schools, math tuition ƅecomes necessary to assist trainees develop ɑ
strong structure foг long-lasting success.
With PSLE mathematics progressing tⲟ іnclude moгe interdisciplinary elements, tuition ҝeeps trainees updated оn incorporated concerns blending math ᴡith science contexts.
Math tuition instructs reliable tіmе management techniques, assisting secondary students fᥙll O Level tests ᴡithin the assigned
period ᴡithout rushing.
Tuitin ѕhows error evaluation methods, helping junior college trainees prevent usual
challenges іn A Level computations аnd evidence.
OMT sticks oᥙt wіth its curriculum designed t᧐ support MOE’ѕ
by including mindfulness techniques tο decrease mathematics anxiousness
ɗuring studies.
Bite-sized lessons mɑke іt easy tο suit leh, resսlting
in regular method ɑnd mսch better general qualities.
Ultimately, math tuition іn Singapore transforms
prospective into success,maкing certain trainees not just pass
but succeed in thеir math tests.
Review my web-site – leaning Lab math Tuition Schedule
leaning Lab math Tuition Schedule
29 Sep 25 at 4:42 pm
купить диплом в химках [url=https://rudik-diplom3.ru/]купить диплом в химках[/url] .
Diplomi_qwei
29 Sep 25 at 4:42 pm
купить диплом медбрата [url=www.rudik-diplom14.ru/]купить диплом медбрата[/url] .
Diplomi_hkea
29 Sep 25 at 4:44 pm
giocare Chicken Road gratis o con soldi veri: giri gratis Chicken Road casino Italia – casino online italiani con Chicken Road
ScottAwapy
29 Sep 25 at 4:45 pm
можно купить диплом медсестры [url=frei-diplom14.ru]можно купить диплом медсестры[/url] .
Diplomi_fioi
29 Sep 25 at 4:45 pm
joszaki regisztracio joszaki.hu/
joszaki-74
29 Sep 25 at 4:46 pm
You really make it seem so easy with your presentation but I find this topic to be really
something which I think I would never understand.
It seems too complicated and extremely broad for me. I’m looking forward for your
next post, I will try to get the hang of it!
Fintruxel TEST
29 Sep 25 at 4:48 pm
Plinko RTP e strategie: Plinko – Plinko demo gratis
Josephgor
29 Sep 25 at 4:49 pm
joszaki regisztracio joszaki.hu
joszaki-438
29 Sep 25 at 4:49 pm
May I just say what a comfort to discover an individual who truly understands what they’re discussing over the
internet. You actually understand how to bring a problem
to light and make it important. A lot more people ought to check this out and understand this side of the story.
I can’t believe you are not more popular because you most certainly possess the gift.
rent a rv
29 Sep 25 at 4:50 pm
купить диплом в октябрьском [url=http://rudik-diplom15.ru]купить диплом в октябрьском[/url] .
Diplomi_tuPi
29 Sep 25 at 4:53 pm
joszaki regisztracio joszaki.hu
joszaki-603
29 Sep 25 at 4:55 pm
организация онлайн трансляций москва [url=https://www.zakazat-onlayn-translyaciyu.ru]https://www.zakazat-onlayn-translyaciyu.ru[/url] .
zakazat onlain translyaciu _ulka
29 Sep 25 at 4:56 pm
https://www.safra.sg/about-safra/media-releases/new-safra-and-hometeamns-family-membership-schemes
https://www.safra.sg/about-safra/media-releases/new-safra-and-hometeamns-family-membership-schemes
29 Sep 25 at 4:57 pm
https://imageevent.com/darrelpacoch/zajei
Normangow
29 Sep 25 at 4:57 pm
купить диплом в москве [url=https://www.rudik-diplom15.ru]купить диплом в москве[/url] .
Diplomi_frPi
29 Sep 25 at 5:01 pm
онлайн трансляции заказать [url=https://zakazat-onlayn-translyaciyu.ru/]онлайн трансляции заказать[/url] .
zakazat onlain translyaciu _boka
29 Sep 25 at 5:01 pm
joszaki regisztracio joszaki.hu
joszaki-134
29 Sep 25 at 5:02 pm
купить диплом медсестры [url=http://frei-diplom14.ru/]купить диплом медсестры[/url] .
Diplomi_qsoi
29 Sep 25 at 5:02 pm
Epic Tower играть в риобет
ScottTem
29 Sep 25 at 5:03 pm
Клиника в Ростове-на-Дону работает круглосуточно, обеспечивая доступность помощи в любое время дня и ночи.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-rostov232.ru/]вызов нарколога на дом ростов-на-дону[/url]
DerrickCon
29 Sep 25 at 5:04 pm