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://www.frei-diplom1.ru]купить диплом москва с занесением в реестр[/url] .
Diplomi_ubOi
29 Sep 25 at 5:05 pm
услуги онлайн трансляции [url=http://zakazat-onlayn-translyaciyu.ru/]услуги онлайн трансляции[/url] .
zakazat onlain translyaciu _lbka
29 Sep 25 at 5:05 pm
Метод и срок подбираются после очного осмотра и исключения противопоказаний. Возможны медикаментозные и психотерапевтические подходы, а также комбинированные программы. Мы объясняем плюсы и ограничения каждого метода, помогаем подготовиться (диета, анализы, отмена определённых препаратов), а затем сопровождаем пациента в период адаптации к трезвости. Кодирование — часть комплексного плана, а не «волшебная кнопка»: устойчивый результат достигается, когда его дополняют поддерживающая терапия и работа с триггерами.
Получить дополнительную информацию – http://narkologicheskaya-klinika-balashiha0.ru
JoshuaCet
29 Sep 25 at 5:08 pm
Hello, Neat post. There is a problem with your site in internet explorer, could test this?
IE still is the market chief and a good part of people will pass over your magnificent
writing because of this problem.
Luvox Bit
29 Sep 25 at 5:08 pm
Mikigaming Merupakan Sebuah Situs Tempat Bermain Games Slot Yang
Amat Sangat Lengkap Dan Juga Menyediakan Metode Pembayaran Terbaik.
Mikigaming
29 Sep 25 at 5:11 pm
Mikigaming: Link Daftar Situs Slot Online Gacor
Resmi Terpercaya 2025
Mikigaming
29 Sep 25 at 5:15 pm
I’m not that much of a internet reader to be honest but your
sites really nice, keep it up! I’ll go ahead and bookmark your website to come back in the future.
Many thanks
seobests.com
29 Sep 25 at 5:16 pm
заказать трансляцию мероприятия [url=www.zakazat-onlayn-translyaciyu.ru/]заказать трансляцию мероприятия[/url] .
zakazat onlain translyaciu _sgka
29 Sep 25 at 5:20 pm
купить диплом техника [url=http://rudik-diplom10.ru]купить диплом техника[/url] .
Diplomi_obSa
29 Sep 25 at 5:22 pm
Купить диплом колледжа в Кривой Рог [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_byea
29 Sep 25 at 5:22 pm
купить диплом товароведа [url=https://www.rudik-diplom8.ru]купить диплом товароведа[/url] .
Diplomi_riMt
29 Sep 25 at 5:22 pm
http://www.pageorama.com/?p=vefuuogegadz
Carlosquapy
29 Sep 25 at 5:23 pm
OMT’s multimedia sources, like involving videos, mаke math ϲome alive, helping Singapore
trainees fаll passionately crazy ԝith it fߋr test success.
Experience flexible learning anytime, ɑnywhere throuɡh OMT’sthorough
online е-learning platform, featuring unlimited access to
video lessons ɑnd interactive tests.
Ꮃith mathematics incorporated effortlessly іnto Singapore’s class settings
tߋ benefit ƅoth teachers and students, devoted math tuition amplifies tһese gains Ƅy offering customized support f᧐r continual accomplishment.
Improving primary education ѡith math tuition prepares
students fοr PSLE Ƅy cultivating a growth mindset tοward tough subjects like proportion and improvements.
Ⅾetermining ɑnd remedying details weaknesses, ⅼike іn chance or coordinate geometry,
mаkes secondary tuition indispensable for O Level excellence.
Ԝith A Levels demanding proficiency іn vectors and complicated numЬers,
math tuition supplies targeted method tօ handle these
abstract principles efficiently.
Unique fгom others, OMT’ѕ syllabus complements MOE’ѕ through a focus on resilience-building workouts, assisting students tаke оn difficult рroblems.
Parental accessibility tο progress reports one, allowing
assistance in the house for sustained grade enhancement.
Math tuition satisfies diverse discovering styles, guaranteeing no Singapore pupil іs left
in the race for examination success.
my web-site – math tuition singapore (Luca)
Luca
29 Sep 25 at 5:26 pm
Hi my family member! I want to say that this post is awesome,
great written and include almost all significant
infos. I would like to look extra posts like this .
A Perfect Finish cabinet painting near me
29 Sep 25 at 5:29 pm
Перед тем как перейти к описанию конкретных методов, следует понимать, что успешное лечение требует комплексного взаимодействия специалистов разных профилей и активного участия самого пациента.
Узнать больше – [url=https://lechenie-narkomanii-omsk0.ru/]лечение наркомании[/url]
Martinron
29 Sep 25 at 5:29 pm
диплом настоящий купить с занесением в реестр [url=http://www.frei-diplom2.ru]http://www.frei-diplom2.ru[/url] .
Diplomi_rnEa
29 Sep 25 at 5:31 pm
joszaki regisztracio joszaki
joszaki-292
29 Sep 25 at 5:32 pm
купить диплом в магадане [url=rudik-diplom15.ru]купить диплом в магадане[/url] .
Diplomi_jdPi
29 Sep 25 at 5:32 pm
Что включено на практике
Углубиться в тему – https://narkologicheskaya-klinika-odincovo0.ru/narkologicheskaya-klinika-narkolog-v-odincovo
KendallVex
29 Sep 25 at 5:35 pm
Наркологическая помощь в Самаре представляет собой комплекс медицинских мероприятий, направленных на лечение алкогольной и наркотической зависимости, а также восстановление физического и психического здоровья пациентов. В наркологической клинике «Согласие» применяются современные методики диагностики, детоксикации и комплексной терапии, учитывающие индивидуальные особенности каждого пациента, тяжесть зависимости и наличие сопутствующих заболеваний. Основная цель — восстановление здоровья, предупреждение осложнений и снижение риска рецидивов.
Изучить вопрос глубже – [url=https://narkologicheskaya-pomoshh-samara0.ru/]оказание наркологической помощи в самаре[/url]
Taylorfag
29 Sep 25 at 5:38 pm
Hey there! Do you use Twitter? I’d like to follow you if that would be okay.
I’m undoubtedly enjoying your blog and look forward to new updates.
강남가라오케
29 Sep 25 at 5:41 pm
Very soon this web site will be famous amid all blog visitors,
due to it’s pleasant articles
web site
29 Sep 25 at 5:41 pm
купить диплом врача [url=https://rudik-diplom14.ru]купить диплом врача[/url] .
Diplomi_ufea
29 Sep 25 at 5:43 pm
Он также может быть полезен для людей, которые занимаются медитацией, йогой
или другими способами расслабления.
https://blog.devmizanur.com/2025/07/16/najlepsze-internetowe-recenzje-i-funkcje-26/
29 Sep 25 at 5:43 pm
купить телефон спб [url=https://kupit-telefon-samsung-2.ru]купить телефон спб[/url] .
kypit telefon samsyng_bven
29 Sep 25 at 5:46 pm
Forest Maiden играть
JohnnyHiecy
29 Sep 25 at 5:47 pm
https://pubhtml5.com/homepage/jcthk
Carlosquapy
29 Sep 25 at 5:48 pm
Hello there, You have done a great job. I
will definitely digg it and personally suggest
to my friends. I am confident they will be benefited from this
site.
Trezik Forge GPT
29 Sep 25 at 5:48 pm
Коллеги!
Хочу рассказать полезной находкой оформления событий в Москве.
Задача была – провести семейное торжество для большой компании. Собственной мебели не хватало.
Покупать мебель не оправдывалось для единичного события. Стали изучать альтернативы и узнали о компанию по аренде мебели.
Читал информацию: компания по аренде мебели – детальная информация о услугах.
**Итог:**
– Сэкономили около 60% бюджета
– Профессиональное обслуживание
– Полный сервис включен
– Положительная обратная связь
– Возможность продления или выкупа
Теперь всегда обращаемся к ним. В различных ситуациях – это идеальное решение.
А как вы решаете такие задачи? Делитесь в комментариях!
Albertjalty
29 Sep 25 at 5:50 pm
купить диплом медсестры [url=rudik-diplom14.ru]купить диплом медсестры[/url] .
Diplomi_xcea
29 Sep 25 at 5:56 pm
Extra Win 1xbet AZ
TommyCap
29 Sep 25 at 5:56 pm
сделать онлайн трансляцию мероприятия [url=https://zakazat-onlayn-translyaciyu.ru/]https://zakazat-onlayn-translyaciyu.ru/[/url] .
zakazat onlain translyaciu _iyka
29 Sep 25 at 5:57 pm
Лечение не заканчивается после завершения курса. Напротив — начинается наиболее ответственный период, когда пациент возвращается в привычную среду, сталкиваясь с соблазнами и старыми моделями. В «РеабПермь» предусмотрен целый блок постлечебной адаптации. Пациенту помогают составить маршрут восстановления: восстановление трудовых или учебных навыков, корректировка окружения, выработка устойчивых альтернатив зависимому поведению (спорт, волонтёрство, хобби). При необходимости предоставляется поддержка в трудоустройстве или обучении.
Изучить вопрос глубже – https://lechenie-narkomanii-perm0.ru/perm-narkologiya/
MichaelPycle
29 Sep 25 at 5:58 pm
I am sure this paragraph has touched all the internet visitors,
its really really pleasant article on building up new weblog.
لیست تمام الگوریتم های گوگل
29 Sep 25 at 5:58 pm