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!
Магазин тут! Отзывы, Качество. kokain gash mefedron alfa-pvp
DanielVeiff
30 Aug 25 at 12:59 am
There is certainly a lot to find out about this issue. I like all the points you made.
Respiclear routine 7 seconds a day
30 Aug 25 at 1:04 am
mostbet qeydiyyat promo kod [url=http://mostbet4138.ru/]mostbet qeydiyyat promo kod[/url]
mostbet_ppot
30 Aug 25 at 1:06 am
купить диплом о среднем [url=https://educ-ua4.ru]купить диплом о среднем[/url] .
Diplomi_cwPl
30 Aug 25 at 1:07 am
Spot on with this write-up, I actually think this web site needs much more attention.
I’ll probably be back again to read more, thanks for the information!
FF
30 Aug 25 at 1:08 am
Start by marking out the mosesolmos.com room to determine how the laminate will be laid. Typically, you should start laying from the window – this will minimize visual defects.
Robertboone
30 Aug 25 at 1:08 am
Works affecting the common news24time.net property of the building include actions that change the condition of the common parts of the apartment building.
DavidJeort
30 Aug 25 at 1:09 am
Book of Ra Deluxe soldi veri: recensioni Book of Ra Deluxe slot – Book of Ra Deluxe soldi veri
Ramonatowl
30 Aug 25 at 1:09 am
My partner and I absolutely love your blog and find most
of your post’s to be precisely what I’m looking for. Do you
offer guest writers to write content for you? I wouldn’t mind writing a post or
elaborating on a few of the subjects you write concerning here.
Again, awesome website!
cloaking SEO
30 Aug 25 at 1:14 am
Cabinet IQ Austin
8305 Ⴝtate Hwy 71 #110, Austin,
TX 78735, United Ѕtates
+12542755536
Project
Project
30 Aug 25 at 1:15 am
Hi! I know this is kind of off-topic however I needed to ask.
Does operating a well-established website such as yours take a large amount of work?
I am completely new to running a blog however I do write in my journal everyday.
I’d like to start a blog so I can easily share my own experience and feelings online.
Please let me know if you have any suggestions or tips for brand
new aspiring bloggers. Thankyou!
situs toto
30 Aug 25 at 1:19 am
Hello to every body, it’s my first visit of this blog; this weblog contains awesome and in fact good
stuff in support of readers.
toto togel 4d
30 Aug 25 at 1:20 am
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
30 Aug 25 at 1:22 am
напольный горшок для цветов [url=http://kashpo-napolnoe-moskva.ru/]напольный горшок для цветов[/url] .
kashpo napolnoe _fjOi
30 Aug 25 at 1:23 am
Exploratory modules ɑt OMT motivate creative analytic, assisting pupils
discover math’ѕ virtuosity and really feel motivated fоr test achievements.
Expand yοur horizons with OMT’s upcoming new physical ɑrea opening in September 2025,
using a lot morе chances fⲟr hands-on math exploration.
Singapore’ѕ world-renowned mathematics curriculum
stresses conceptual understanding оver simple
computation, mаking math tuition vital for trainees to understand deep concepts
ɑnd stand օut іn national tests lіke PSLE and O-Levels.
Ϝοr PSLE achievers, tuition supplies mock exams ɑnd
feedback, helping fine-tune answers fοr maximum marks іn both
multiple-choice and open-ended ɑreas.
Ԝith О Levels stressing geometry evidence ɑnd theses, math tuition supplies
specialized drills tо makе certaіn students ϲɑn tаke on tһese with precision and sеⅼf-confidence.
Ᏼy providing considerable technique with past Ꭺ Level examination papers,
math tuition familiarizes trainees ᴡith inquiry styles and noting
schemes fоr optimal performance.
OMT’ѕ exclusive curriculum boosts MOE standards tһrough аn all
natural method tһat nurtures ƅoth scholastic skills and an enthusiasm f᧐r mathematics.
12-mߋnth accessibility indіcates you cɑn revisit subjects anytime lah, constructing strong foundations fⲟr regular hіgh mathematics marks.
Ӏn Singapore, wheгe math effectiveness opens doors tο STEM occupations, tuition іs vital for solid exam foundations.
Check ߋut my blog post :: maths practice papers
maths practice papers
30 Aug 25 at 1:27 am
Greetings! Very helpful advice in this particular post!
It is the little changes that will make the biggest changes.
Thanks for sharing!
Janie
30 Aug 25 at 1:27 am
I got this web site from my friend who informed me concerning this web site
and now this time I am visiting this site and reading very
informative content at this place.
Trade 500
30 Aug 25 at 1:28 am
купить реальный диплом о высшем образовании [url=http://educ-ua4.ru]купить реальный диплом о высшем образовании[/url] .
Diplomi_gwPl
30 Aug 25 at 1:29 am
This blog was… how do I say it? Relevant!! Finally I have found something that helped me.
Thanks a lot!
ashlingcottage.com
30 Aug 25 at 1:35 am
I know this if off topic but I’m looking into starting my own weblog and was curious what all is required
to get setup? I’m assuming having a blog like yours would cost a pretty
penny? I’m not very internet smart so I’m not 100%
positive. Any recommendations or advice would be greatly appreciated.
Thanks
Leon
30 Aug 25 at 1:36 am
отели в анапе с бассейном с подогревом
ScottDow
30 Aug 25 at 1:39 am
garuda888 game slot RTP tinggi [url=https://1win888indonesia.com/#]garuda888 slot online terpercaya[/url] permainan slot gacor hari ini
Aaronreima
30 Aug 25 at 1:39 am
где купить аттестат за 11 класс в саратове [url=http://www.arus-diplom24.ru]где купить аттестат за 11 класс в саратове[/url] .
Diplomi_tpsa
30 Aug 25 at 1:40 am
Hey there excellent website! Does running a blog similar to this require a lot of work?
I’ve virtually no understanding of coding but I was hoping
to start my own blog in the near future. Anyways, if you have any recommendations or tips for new blog owners please share.
I understand this is off subject however I just needed to ask.
Cheers!
Intel Erymax Pro
30 Aug 25 at 1:43 am
купить диплом техникума с реестром [url=https://arus-diplom31.ru/]купить диплом техникума с реестром[/url] .
Diplomi_dcpl
30 Aug 25 at 1:44 am
Купить кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
30 Aug 25 at 1:44 am
mostbet mobil qeydiyyat [url=mostbet4138.ru]mostbet4138.ru[/url]
mostbet_tgot
30 Aug 25 at 1:45 am
Мы предлагаем дипломы любых профессий по доступным тарифам. Заказ диплома, который подтверждает окончание института, – это грамотное решение. Заказать диплом о высшем образовании: [url=http://cubicbricks.com/author/shantaerincon7/]cubicbricks.com/author/shantaerincon7[/url]
Mazrfgp
30 Aug 25 at 1:50 am
где можно купить аттестат [url=http://educ-ua5.ru]где можно купить аттестат[/url] .
Diplomi_coKl
30 Aug 25 at 1:53 am
best online casinos for 80sPop
Jamesasync
30 Aug 25 at 1:55 am
https://arcadiasochi.ru/
MichaelViono
30 Aug 25 at 1:55 am
отели в анапе с бассейном с подогревом
ScottDow
30 Aug 25 at 1:58 am
I read this article fully regarding the resemblance of most up-to-date and previous technologies, it’s awesome article.
Web Rehberim - Sosyal İçerik Platformu
30 Aug 25 at 1:58 am
Оказание помощи нарколога на дому организовано по отлаженной схеме, включающей несколько ключевых этапов, которые позволяют оперативно стабилизировать состояние пациента и начать детоксикацию:
Подробнее можно узнать тут – http://наркология-дома1.рф/vyzov-narkologa-na-dom-ryazan/https://наркология-дома1.рф
SteveFEP
30 Aug 25 at 1:58 am
Мы изготавливаем дипломы любой профессии по выгодным ценам. Заказ документа, подтверждающего обучение в университете, – это грамотное решение. Купить диплом о высшем образовании: [url=http://thcsnghiaan.pgdnamtruc.edu.vn/textstat/smotret-doramy-onlajn-v-horoshem-kachestve-220.html/]thcsnghiaan.pgdnamtruc.edu.vn/textstat/smotret-doramy-onlajn-v-horoshem-kachestve-220.html[/url]
Mazrgvz
30 Aug 25 at 2:04 am
Наркологическая помощь на платной основе, это ключевой момент в борьбе с зависимостями. В специальной наркологической клинике, такой как narkolog-tula016.ru, пациентам предоставляется профессиональная помощь, включая лечение наркомании и реабилитацию алкоголиков. Процесс реабилитации включает очистку организма и психотерапию. Обсуждение с наркологом позволяет определить оптимальный курс лечения к индивидуальной проблеме. Клиники предлагают анонимную помощь и кризисную интервенцию. Поддержка родственников также имеет огромное значение. Групповые занятия помогают поддерживать друг друга, а медицинская поддержка обеспечивает безопасность лечения. Коммерческие услуги позволяют достигать лучших результатов и индивидуальный подход врачей, что способствует эффективному выздоровлению.
zapojtulaNeT
30 Aug 25 at 2:04 am
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
30 Aug 25 at 2:07 am
отели анапы ультра все включено
ScottDow
30 Aug 25 at 2:12 am
I just couldn’t leave your website before suggesting
that I really enjoyed the standard info an individual supply to your guests?
Is gonna be again ceaselessly in order to inspect new posts
Parlions Platform
30 Aug 25 at 2:12 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-662
30 Aug 25 at 2:13 am
купить диплом [url=https://www.educ-ua4.ru]купить диплом[/url] .
Diplomi_cjPl
30 Aug 25 at 2:15 am
Good day! I know this is somewhat off topic but I was
wondering if you knew where I could locate a captcha
plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one?
Thanks a lot!
dewascatter link alternatif
30 Aug 25 at 2:17 am
купить диплом о высшем образовании в днепропетровске [url=http://www.educ-ua5.ru]купить диплом о высшем образовании в днепропетровске[/url] .
Diplomi_byKl
30 Aug 25 at 2:20 am
Heya are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and set up my own.
Do you require any html coding knowledge to
make your own blog? Any help would be greatly appreciated!
kedai tayar near me
30 Aug 25 at 2:24 am
Приобрести кокаин, мефедрон, гашиш, бошки, альфа-пвп
DanielVeiff
30 Aug 25 at 2:29 am
mostbet az müsbət rəylər [url=http://mostbet4138.ru]mostbet az müsbət rəylər[/url]
mostbet_tpot
30 Aug 25 at 2:33 am
What’s up, yes this post is actually fastidious and I have learned lot of things from it regarding blogging.
thanks.
kontol besar
30 Aug 25 at 2:35 am
7 Gold Fruits online Az
Wilsonlof
30 Aug 25 at 2:36 am
Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!
remontkomand-646
30 Aug 25 at 2:36 am
gloomy
ketamine
30 Aug 25 at 2:36 am