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!
Keep on working, great job!
boobs
27 Oct 25 at 3:24 pm
There is certainly a lot to find out about this topic.
I like all of the points you’ve made.
Yupoo Burberry
27 Oct 25 at 3:24 pm
Реабилитация проходит в комфортных условиях, с постоянным наблюдением специалистов. Важным элементом является формирование новых привычек и социальных навыков, что способствует возвращению пациента к полноценной жизни.
Углубиться в тему – [url=https://narkologicheskaya-clinika-v-nizhnem-novgorode16.ru/]наркологическая клиника стационар нижний новгород[/url]
Nicolascruby
27 Oct 25 at 3:25 pm
Нарколог на дом в Челябинске — это услуга, которая позволяет получить профессиональную медицинскую помощь при алкогольной или наркотической интоксикации без необходимости посещения клиники. Такой формат особенно востребован в случаях, когда пациент не может самостоятельно прибыть в медицинское учреждение или нуждается в конфиденциальной помощи. Врач-нарколог выезжает по указанному адресу, проводит осмотр, оценивает состояние и подбирает оптимальную терапию. Квалифицированное вмешательство помогает избежать осложнений и стабилизировать состояние уже в течение первых часов после прибытия специалиста.
Ознакомиться с деталями – [url=https://narkolog-na-dom-v-chelyabinske16.ru/]частный нарколог на дом[/url]
JosephMep
27 Oct 25 at 3:25 pm
Где купить Фенибут в Краснокаменске?Обратите внимание – сайт https://best-kicks.ru
. Цены нормальные, доставку обещают. Кто-то покупал у них? Как у них с надежностью?
Stevenref
27 Oct 25 at 3:26 pm
Awesome post.
Live Draw Sydney
27 Oct 25 at 3:27 pm
kraken обмен
кракен сайт
Henryamerb
27 Oct 25 at 3:28 pm
Hey there! Someone in my Myspace group shared this website with
us so I came to take a look. I’m definitely
loving the information. I’m book-marking and will be tweeting this to my followers!
Outstanding blog and superb design.
pg slot99
27 Oct 25 at 3:29 pm
https://mannvital.com/# billig Viagra Norge
Davidjealp
27 Oct 25 at 3:29 pm
купить диплом в подольске [url=https://www.rudik-diplom12.ru]купить диплом в подольске[/url] .
Diplomi_cePi
27 Oct 25 at 3:30 pm
кто нибудь работает медсестрой по купленному диплому [url=https://frei-diplom13.ru]https://frei-diplom13.ru[/url] .
Diplomi_bmkt
27 Oct 25 at 3:32 pm
Лечение в клинике в Челябинске строится на принципах конфиденциальности, добровольности и медицинской этики. Врачи применяют доказательные методы терапии, а программы лечения адаптируются под особенности каждого пациента. Работа ведётся комплексно, включая медикаментозную помощь, психотерапию и социальную реабилитацию. Такой подход позволяет эффективно восстановить здоровье и вернуть пациента к нормальной жизни в обществе.
Углубиться в тему – https://narcologicheskaya-klinika-v-chelyabinske16.ru/chastnaya-narkologicheskaya-klinika-chelyabinsk/
Jamestug
27 Oct 25 at 3:33 pm
you can find out more
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
you can find out more
27 Oct 25 at 3:33 pm
наркологические услуги в москве [url=https://narkologicheskaya-klinika-28.ru/]narkologicheskaya-klinika-28.ru[/url] .
narkologicheskaya klinika_xwMa
27 Oct 25 at 3:34 pm
наркологическая служба [url=narkologicheskaya-klinika-25.ru]narkologicheskaya-klinika-25.ru[/url] .
narkologicheskaya klinika_xbPl
27 Oct 25 at 3:35 pm
Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.
pizzacuba-939
27 Oct 25 at 3:36 pm
кракен qr код
кракен vk4
Henryamerb
27 Oct 25 at 3:37 pm
кракен тор
kraken онлайн
Henryamerb
27 Oct 25 at 3:37 pm
rankwebdevelopers.com – Bookmarked this immediately, planning to revisit for updates and inspiration.
Meta Faries
27 Oct 25 at 3:38 pm
learnandtrade – Every article feels written with real experience, not just copied theory.
Dayna Perrot
27 Oct 25 at 3:38 pm
кракен онион
kraken
Henryamerb
27 Oct 25 at 3:42 pm
Hello would you mind sharing which blog platform you’re using?
I’m looking to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs
and I’m looking for something completely unique.
P.S My apologies for getting off-topic but I had to
ask!
lipödem entfernen
27 Oct 25 at 3:43 pm
анонимная наркологическая клиника [url=https://narkologicheskaya-klinika-25.ru/]анонимная наркологическая клиника[/url] .
narkologicheskaya klinika_ruPl
27 Oct 25 at 3:44 pm
Your means of telling the whole thing in this article is in fact pleasant, every one
be able to easily know it, Thanks a lot.
situs bokep
27 Oct 25 at 3:44 pm
http://vitalpharma24.com/# Erfahrungen mit Kamagra 100mg
Davidjealp
27 Oct 25 at 3:45 pm
Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.
pizzacuba-440
27 Oct 25 at 3:45 pm
Bʏ celebrating tiiny victories underway monitoring, OMT nurtures ɑ
favorable relationship with mathematics, motivating students fⲟr exam quality.
Transform math difficulties іnto accomplishments with OMT Math Tuition’ѕ blend of online
and օn-site choices, ƅacked Ьy a track record ߋf student quality.
In a ѕystem whеre mathematics education һas aсtually
evolved tо cultivate innovation and worldwide competitiveness, registering
in math tuition mаkes ѕure trainees stay ahead by deepening their understanding
and application of crucial principles.
Tuition emphasizes heuristic рroblem-solving аpproaches, essential fߋr
tаking on PSLE’s tough w᧐rd pгoblems that require multiple steps.
Comprehensive insurance coverage օf the
entirе O Level curriculum іn tuition mɑkes cеrtain no topics, fгom sets tο vectors,
ɑre neglected іn a trainee’ѕ alteration.
Math tuition аt the junior college degree highlights conceptual clarity оvеr rote memorization, іmportant for tackling application-based
А Level questions.
OMT’ѕ proprietary curriculum enhances MOE standards tһrough ɑn aⅼl natural approach that nurtures ƅoth scholastic
skills and an interest fоr mathematics.
OMT’s online ɑrea offers assistance leh, where yօu ϲan aѕk
concerns and enhance your understanding for much better grades.
Math tuitiion builds resilience іn facing difficult
concerns, ɑ requirement for growing in Singapore’ѕ hіgh-pressure test atmosphere.
mү web ρage :: secondary 4 math tuition singapore
secondary 4 math tuition singapore
27 Oct 25 at 3:46 pm
Nice replies in return of this matter with real arguments and explaining everything on the topic of that.
мелстрой казино 1вин
27 Oct 25 at 3:46 pm
Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.
pizzacuba-811
27 Oct 25 at 3:47 pm
Greetings! I know this is kinda off topic but I was wondering which blog platform are you using for this website?
I’m getting fed up of WordPress because I’ve had problems with hackers
and I’m looking at options for another platform. I would
be fantastic if you could point me in the direction of a good platform.
boyarka
27 Oct 25 at 3:48 pm
кракен 2025
kraken онлайн
Henryamerb
27 Oct 25 at 3:49 pm
гидроизоляция подвала цена [url=https://gidroizolyaciya-cena-7.ru/]гидроизоляция подвала цена[/url] .
gidroizolyaciya cena_miSi
27 Oct 25 at 3:50 pm
реабилитация зависимых [url=https://narkologicheskaya-klinika-28.ru/]реабилитация зависимых[/url] .
narkologicheskaya klinika_clMa
27 Oct 25 at 3:50 pm
I’ve learn a few good stuff here. Definitely price bookmarking for
revisiting. I surprise how so much attempt you put to make one
of these wonderful informative website.
slot pulsa
27 Oct 25 at 3:51 pm
наркологическая клиника в москве [url=http://narkologicheskaya-klinika-25.ru]наркологическая клиника в москве[/url] .
narkologicheskaya klinika_tyPl
27 Oct 25 at 3:52 pm
Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.
LarryHeP
27 Oct 25 at 3:53 pm
Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.
pizzacuba-253
27 Oct 25 at 3:54 pm
купить диплом в миассе [url=www.rudik-diplom12.ru/]купить диплом в миассе[/url] .
Diplomi_cgPi
27 Oct 25 at 3:55 pm
где можно купить диплом медицинского колледжа [url=http://frei-diplom10.ru/]http://frei-diplom10.ru/[/url] .
Diplomi_euEa
27 Oct 25 at 3:57 pm
кракен вход
kraken vk3
Henryamerb
27 Oct 25 at 3:57 pm
кракен сайт
kraken онлайн
Henryamerb
27 Oct 25 at 3:58 pm
Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.
LarryHeP
27 Oct 25 at 4:01 pm
купить трубку для курения
купить трубку для курения
27 Oct 25 at 4:03 pm
kraken vk2
kraken официальный
Henryamerb
27 Oct 25 at 4:03 pm
Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.
LarryHeP
27 Oct 25 at 4:04 pm
клиника вывод из запоя москва [url=https://www.narkologicheskaya-klinika-25.ru]клиника вывод из запоя москва[/url] .
narkologicheskaya klinika_poPl
27 Oct 25 at 4:08 pm
Thanks for finally talking about > PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog < Liked it!
爹地
27 Oct 25 at 4:08 pm
подвал дома ремонт [url=https://gidroizolyaciya-podvala-cena.ru]https://gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_zvKt
27 Oct 25 at 4:08 pm
вывод из запоя москва клиника [url=https://www.narkologicheskaya-klinika-28.ru]вывод из запоя москва клиника[/url] .
narkologicheskaya klinika_wmMa
27 Oct 25 at 4:09 pm
кракен qr код
kraken сайт
Henryamerb
27 Oct 25 at 4:10 pm