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!
kraken СПб
kraken darknet
Henryamerb
27 Oct 25 at 12:49 pm
клиника наркологии москва [url=http://narkologicheskaya-klinika-24.ru/]http://narkologicheskaya-klinika-24.ru/[/url] .
narkologicheskaya klinika_rvSr
27 Oct 25 at 12:50 pm
купить диплом техникума ссср в нижнем новгороде [url=https://frei-diplom10.ru]купить диплом техникума ссср в нижнем новгороде[/url] .
Diplomi_yzEa
27 Oct 25 at 12:50 pm
Wow, in Singapore, a famous primary signifies access tօ former students connections, assisting ʏouг youngster oƄtain opportunities ɑnd employment latеr.
Avoid play play lah, elite schools conduct talks ƅy professionals, motivating үour kid towards bold job objectives.
Listen ᥙρ, Singapore moms and dads, math гemains ⲣrobably tһe highly essential
primary topic, fostering imagination tһrough issue-resolving fоr creative professions.
Alas, primary math instructs everyday implementations ⅼike budgeting, so guarantee
үour youngster gets thаt properly starting young.
Do not play play lah, pair а reputable primary school
alongside mathematics excellence fоr guarantee
superior PSLE гesults аs well as effortless transitions.
In aԁdition fr᧐m school facilities, focus оn mathematics іn order to prevent frequent mistakes including sloppy
errors ɑt assessments.
Oh dear, witһout solid mathematics in primary school, no matter t᧐p institution children mɑy struggle іn next-level equations, tһerefore develop tһiѕ
promptⅼʏ leh.
Advantage Lay Garden Primary School оffers a nurturing environment thɑt encourages іnterest and development.
Committed instructors аnd varied programs
assist trainees develop skills fօr lоng-lasting success.
Corporation Primary School ᥙses inclusive education ᴡith focus on specific requirements.
Τhe school promotes teamwork ɑnd academic progress.
Parents ѵalue іtѕ supportive ɑnd varied community.
Feel free tⲟ visit my homeρage – Nan Hua High School
Nan Hua High School
27 Oct 25 at 12:51 pm
OMT’s exclusive analytical strategies mаke taҝing on challenging
inquiries rеally feel likе a video game, helping trainees develop а real love for mathematics аnd ideas to sjine in tests.
Experience flexible knowing anytime, ɑnywhere throսgh OMT’s extensive online e-learning platform,
including endless access tο video lessons and interactive quizzes.
Ӏn Singapore’s rigorous education sүstem, where mathematics iѕ required and consumes аround
1600 hߋurs of curriculum tіme in primary and secondary schools,
math tuition becomeѕ vital to һelp trainees construct
a strong foundation for lifelong success.
Ꮃith PSLE math questions оften involving real-worldapplications, tuition supplies targeted practice tօ develop іmportant thinking abilities neϲessary foг high ratings.
With tһe O Level mathematics syllabus sometіmes advancing, tuition keeps pupils
updated οn modifications, ensuring tһey are ᴡell-prepared for current styles.
Junior college math tuition promotes joint discovering іn tiny
groups, boosting peer discussions оn complex A Level ideas.
OMT’ѕ proprietary educational program enhances MOE requirements
tһrough an alternative approach tһat nurtures bοth scholastic abilities and an enthusiasm f᧐r mathematics.
Alternative approach іn on-line tuition one, supporting
not simply abilities yet enthusiasm f᧐r mathematics and best quality success.
Math tuition рrovides enrichment Ьeyond the essentials, esting gifted Singapore
students tߋ aim for difference іn exams.
my ρage: sec 2 maths exam papers
sec 2 maths exam papers
27 Oct 25 at 12:53 pm
kraken qr code
кракен Россия
Henryamerb
27 Oct 25 at 12:54 pm
No matter if some one searches for his essential thing,
so he/she desires to be available that in detail, therefore that thing is
maintained over here.
https://www.instagram.com/soldier_surprise_stories/reel/DOjBzz3iPyd/?hl=en
27 Oct 25 at 12:56 pm
где купить диплом об окончании колледжа [url=https://www.frei-diplom7.ru]где купить диплом об окончании колледжа[/url] .
Diplomi_zcei
27 Oct 25 at 12:57 pm
купить диплом нового образца [url=www.rudik-diplom12.ru/]купить диплом нового образца[/url] .
Diplomi_fhPi
27 Oct 25 at 12:57 pm
hey there and thank you for your information – I’ve definitely picked up anything new from right here.
I did however expertise a few technical issues using this website, since I experienced to
reload the website many times previous to I could get it to load properly.
I had been wondering if your hosting is OK? Not that I am
complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage
your high quality score if advertising and marketing with
Adwords. Anyway I am adding this RSS to my e-mail and could
look out for a lot more of your respective intriguing content.
Make sure you update this again soon.
dewa scatter
27 Oct 25 at 12:59 pm
A useful selection here: https://primorskival.si
KellyNogue
27 Oct 25 at 12:59 pm
kraken client
кракен даркнет
Henryamerb
27 Oct 25 at 1:00 pm
Accurate and up-to-date: https://childstrive.org
Lutherlieva
27 Oct 25 at 1:00 pm
Only the most useful: https://amt-games.com
Horacefoots
27 Oct 25 at 1:02 pm
Great beat ! I would like to apprentice whilst you amend your
site, how can i subscribe for a blog website? The account aided me a applicable deal.
I were tiny bit acquainted of this your broadcast provided vibrant clear
concept
cat bubble carrier review
27 Oct 25 at 1:02 pm
наркологическая платная клиника [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_faSr
27 Oct 25 at 1:03 pm
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Детали по клику – https://exlinko.net/o/uvgco-rank-website-in-3-weeks
Charlieagric
27 Oct 25 at 1:04 pm
купить диплом в волгодонске [url=https://rudik-diplom12.ru/]купить диплом в волгодонске[/url] .
Diplomi_bbPi
27 Oct 25 at 1:04 pm
Всё получил свой АМ. Порошок кремового-оранжевого цвета, кстати полная растворимость на поровой бане. Так что не знаю кто там чо писал, помоему товар заебись! Как высохнет отпишу трип репорт от этой поставки… купить онлайн мефедрон, экстази, бошки 15 янв. в 6:00 Статус вашего заказа #100*****был изменен наОтправлен Заказ помещен в статус Отправлен,накладная №15 3800-****
RichardDring
27 Oct 25 at 1:06 pm
как купить диплом в колледже [url=http://frei-diplom10.ru]как купить диплом в колледже[/url] .
Diplomi_pdEa
27 Oct 25 at 1:06 pm
кракен клиент
кракен vk5
Henryamerb
27 Oct 25 at 1:09 pm
купить диплом техникума в красноярске [url=https://www.frei-diplom7.ru]купить диплом техникума в красноярске[/url] .
Diplomi_cdei
27 Oct 25 at 1:09 pm
кракен онлайн
kraken marketplace
Henryamerb
27 Oct 25 at 1:09 pm
This piece of writing is genuinely a good one it helps new net
viewers, who are wishing in favor of blogging.
Finxor GPT
27 Oct 25 at 1:11 pm
куплю диплом медсестры в москве [url=http://frei-diplom15.ru/]куплю диплом медсестры в москве[/url] .
Diplomi_imoi
27 Oct 25 at 1:13 pm
kraken onion
kraken 2025
Henryamerb
27 Oct 25 at 1:14 pm
клиники наркологические [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_smSr
27 Oct 25 at 1:15 pm
купить диплом техникума готовый пять плюс [url=http://www.frei-diplom7.ru]купить диплом техникума готовый пять плюс[/url] .
Diplomi_nhei
27 Oct 25 at 1:16 pm
купить диплом техникума общественного питания [url=http://frei-diplom10.ru]купить диплом техникума общественного питания[/url] .
Diplomi_rwEa
27 Oct 25 at 1:16 pm
https://t.me/s/jw_1xbet/495
Georgerah
27 Oct 25 at 1:17 pm
Remarkable things here. I’m very glad to peer your post.
Thank you so much and I am looking forward to touch you.
Will you please drop me a e-mail?
with local private key generation and offline capabilities to protect your data. Compatible with TRON’s ecosystem
27 Oct 25 at 1:17 pm
https://t.me/s/jw_1xbet/506
Georgerah
27 Oct 25 at 1:21 pm
kraken vk2
kraken marketplace
Henryamerb
27 Oct 25 at 1:21 pm
купить гриндер для травы
купить гриндер для травы
27 Oct 25 at 1:22 pm
Goodness, top schools possess secure environments, permitting focus οn learning for superior PSLE ɑnd furtheг.
Guardians, dread tһe gap hor, gooԁ establishments
provide board game сlubs,honing planning f᧐r commerce.
Аvoid taкe lightly lah, pair а excellent primary school рlus math excellence fߋr assure higһ PSLE results and smooth shifts.
Alas, primary mathematics educates practical applications
ѕuch as budgeting, theгefore mаke sure yⲟur kid gets tһɑt correctly starting young.
Parents, kiasu approach activated lah, solid primary math leads
f᧐r superior science unddrstanding ρlus engineering dreams.
Wah, mathematics acts ⅼike the groundwork block foг primary learning,
assisting children ѡith dimensional thinking for design routes.
Oi oi, Singapore parents, mathematics proves рrobably tһe extremely essential primary discipline, encouraging
imagination іn issue-resolving for creative careers.
Damai Primary School cultivates а motivating environment that motivates іnterest and
development.
Caring instructors аnd engaging programs һelp support weⅼl-rounded individuals.
Punggol Green Primary School οffers environmentally friendly programs ѡith strong academics.
Ꭲhe school nurtures ecological stewards.
Moms аnd dads valuе its green focus.
Ꮋere iѕ my pɑge :: Yuan Ching Secondary School (Jon)
Jon
27 Oct 25 at 1:23 pm
Заказать диплом любого ВУЗа мы поможем. Купить диплом в России, предлагает наша компания – [url=http://diplomybox.com//]diplomybox.com/[/url]
Cazriin
27 Oct 25 at 1:24 pm
Как купить Героин в Павловске?Нашел сайт https://SeptiKlux.ru
– вроде все ок по ценам, доставка гибкая. Может, кто уже покупал у них? Как с качеством продукта?
Stevenref
27 Oct 25 at 1:24 pm
Wow that was unusual. I just wrote an incredibly
long comment but after I clicked submit my comment
didn’t show up. Grrrr… well I’m not writing all that over
again. Anyhow, just wanted to say great blog!
https://www.instagram.com/soldier_surprise_stories/reel/DOn7HyYiLI7/?hl=en
27 Oct 25 at 1:25 pm
наркологическая клиника [url=https://narkologicheskaya-klinika-24.ru]наркологическая клиника[/url] .
narkologicheskaya klinika_itSr
27 Oct 25 at 1:26 pm
kraken зеркало
kraken vk6
Henryamerb
27 Oct 25 at 1:30 pm
kraken vk6
кракен маркетплейс
Henryamerb
27 Oct 25 at 1:30 pm
https://bestballs.ru/
DavidDrils
27 Oct 25 at 1:31 pm
купить диплом в севастополе [url=rudik-diplom12.ru]купить диплом в севастополе[/url] .
Diplomi_wbPi
27 Oct 25 at 1:32 pm
Right now it looks like Drupal is the preferred blogging platform available right now.
(from what I’ve read) Is that what you are using on your blog?
Charlie Kirk debates with a critical young woman
27 Oct 25 at 1:34 pm
Hello! I know this is kind of off topic but I was wondering which blog platform are you using for
this site? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at options for another platform.
I would be great if you could point me in the direction of a good platform.
https://www.instagram.com/soldier_surprise_stories/reel/DOeEBmGCDbI/?hl=en
27 Oct 25 at 1:35 pm
кракен зеркало
kraken 2025
Henryamerb
27 Oct 25 at 1:36 pm
https://t.me/jw_1xbet/313
Georgerah
27 Oct 25 at 1:37 pm
https://t.me/s/jw_1xbet/774
Georgerah
27 Oct 25 at 1:38 pm
помощь нарколога [url=www.narkologicheskaya-klinika-24.ru/]www.narkologicheskaya-klinika-24.ru/[/url] .
narkologicheskaya klinika_gxSr
27 Oct 25 at 1:41 pm
kraken android
kraken сайт
Henryamerb
27 Oct 25 at 1:43 pm