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!
yourcreativejourney – Good pricing and clear descriptions make me feel confident to buy.
Kermit Armout
28 Oct 25 at 6:30 am
клиника наркологическая платная [url=https://narkologicheskaya-klinika-27.ru/]https://narkologicheskaya-klinika-27.ru/[/url] .
narkologicheskaya klinika_vypl
28 Oct 25 at 6:30 am
купить медицинский диплом с занесением в реестр [url=www.frei-diplom4.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_lfOl
28 Oct 25 at 6:30 am
kraken ссылка
kraken vk2
Henryamerb
28 Oct 25 at 6:31 am
наркологическая клиника [url=www.narkologicheskaya-klinika-28.ru]наркологическая клиника[/url] .
narkologicheskaya klinika_syMa
28 Oct 25 at 6:32 am
Купить диплом техникума в Одесса [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_ehea
28 Oct 25 at 6:32 am
ремонт подвала в частном доме [url=https://gidroizolyaciya-podvala-cena.ru/]https://gidroizolyaciya-podvala-cena.ru/[/url] .
gidroizolyaciya podvala cena_hnKt
28 Oct 25 at 6:33 am
online wetten ohne ausweis
My site … profi Sportwetten tipps
profi Sportwetten tipps
28 Oct 25 at 6:33 am
Обеспечьте комфорт и стиль в вашем доме с [url=https://rulonnye-shtory-umnyy-dom.ru/]электрические жалюзи рулонные Прокарниз[/url], которые идеально впишутся в современный интерьер.
Автоматические рулонные шторы становятся все более популярными в современных интерьерах. Использование таких штор позволяет не только удобно регулировать свет, но и добавить стиль в ваш дом. Подобные изделия идеально вписываются в концепцию “умного дома”.
Системы автоматизации позволяют программировать шторы с помощью смартфона. Вы можете задавать график работы штор в зависимости от времени суток. Такой подход очень удобен делает жизнь более комфортной.
Кроме того, умные рулонные шторы могут быть оснащены датчиками света и температуры. Эти датчики автоматически регулируют положение штор для достижения оптимального уровня освещенности. В результате вы можете экономить на электроэнергии благодаря естественному освещению.
Процесс установки рулонных штор с автоматизацией достаточно прост и не требует специальных навыков. Вы можете установить их самостоятельно, следуя инструкциям. После установки , вы сможете наслаждаться всеми преимуществами умного дома.
автоматические рулонные жалюзи цена
28 Oct 25 at 6:34 am
https://www.cloreleadership.org/resource/diary-clore-fellow-what-would-happen-if-museums-employed-industrial-engineers/
https://www.cloreleadership.org/resource/diary-clore-fellow-what-would-happen-if-museums-employed-industrial-engineers/
28 Oct 25 at 6:34 am
https://t.me/s/bs_1Win/1297
Georgerah
28 Oct 25 at 6:36 am
кракен
kraken обмен
Henryamerb
28 Oct 25 at 6:37 am
гидроизоляция подвала цена за м2 [url=gidroizolyaciya-cena-7.ru]гидроизоляция подвала цена за м2[/url] .
gidroizolyaciya cena_osSi
28 Oct 25 at 6:37 am
купить диплом автомобильного техникума [url=http://www.frei-diplom9.ru]купить диплом автомобильного техникума[/url] .
Diplomi_gvea
28 Oct 25 at 6:37 am
https://t.me/s/bs_1Win/351
Georgerah
28 Oct 25 at 6:37 am
Hey There. I found your blog using msn. This is a really well written article.
I will make sure to bookmark it and return to read more of your useful info.
Thanks for the post. I’ll definitely return.
Result Sydney
28 Oct 25 at 6:40 am
цена ремонта подвала [url=gidroizolyaciya-cena-7.ru]gidroizolyaciya-cena-7.ru[/url] .
gidroizolyaciya cena_opSi
28 Oct 25 at 6:40 am
клиника наркологии москва [url=narkologicheskaya-klinika-28.ru]клиника наркологии москва[/url] .
narkologicheskaya klinika_awMa
28 Oct 25 at 6:40 am
trendyfindsonline – I found a few items I’m considering buying here.
Trevor Inocencio
28 Oct 25 at 6:44 am
адреса наркологических клиник [url=https://narkologicheskaya-klinika-28.ru]адреса наркологических клиник[/url] .
narkologicheskaya klinika_quMa
28 Oct 25 at 6:44 am
You have made some decent points there. I checked on the net to find out more about the issue and found
most people will go along with your views on this site.
my site … zinnat02
zinnat02
28 Oct 25 at 6:45 am
discovergreatdeals – Checkout was simple and the delivery info looked trustworthy.
Sherill Bussell
28 Oct 25 at 6:45 am
наркологический центр москва [url=http://narkologicheskaya-klinika-27.ru]наркологический центр москва[/url] .
narkologicheskaya klinika_kkpl
28 Oct 25 at 6:45 am
кракен даркнет маркет
кракен
Henryamerb
28 Oct 25 at 6:45 am
kraken tor
kraken обмен
Henryamerb
28 Oct 25 at 6:46 am
Great post. I was checking continuously this
weblog and I am inspired! Extremely useful information specifically the ultimate
phase 🙂 I deal with such information much.
I used to be seeking this certain information for a very long time.
Thank you and good luck.
신용카드현금화
28 Oct 25 at 6:46 am
гидроизоляция цена москва [url=https://gidroizolyaciya-cena-8.ru/]https://gidroizolyaciya-cena-8.ru/[/url] .
gidroizolyaciya cena_qdKn
28 Oct 25 at 6:47 am
dreambuycollection – Overall a positive experience so far; delivery and quality will be key.
Theo Steber
28 Oct 25 at 6:47 am
theworldawaits – Quality product visuals make me confident about placing an order.
Antione Holtberg
28 Oct 25 at 6:47 am
Для сохранения приватности мы ведём коммуникацию через одного доверенного представителя, используем нейтральные формулировки в документах, а инструкции выдаём в неброском виде. При невозможности создать тишину дома (ремонт, маленькие дети, гости) предложим краткий «тихий» стационар с отдельным входом и камерным режимом, после чего сопровождение вернётся в домашний формат.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-ekaterinburge16.ru/]наркология вывод из запоя екатеринбург[/url]
GregoryBlods
28 Oct 25 at 6:48 am
OMT’ѕ emphasis on error evaluation transforms blunders іnto
finding out adventures, assisting students drop іn love with math’s flexible
nature and goal һigh in tests.
Register tⲟday іn OMT’ѕ standalone e-learning programs and see yoᥙr
grades soar tһrough limitless access tо tⲟp quality, syllabus-aligned material.
Singapore’ѕ focus on imρortant thinking through mathematics
highlights the significance ᧐f math tuition, ѡhich assists trainees develop the analytical abilities required Ьy the nation’ѕ forward-thinking syllabus.
Tuition programs fоr primary mathematics concentrate оn mistake analysis from past PSLE documents,
teaching students t᧐ ɑvoid recurring mistakes іn computations.
Comprehensive insurance coverage ⲟf thе wholе O Level syllabus іn tuition mаkes sure
no topics, from sets to vectors, ɑre neglected in a student’s
revision.
Preparing f᧐r the changability of A Level concerns,
tuition creаtes flexible analytic ɑpproaches for real-time exam circumstances.
Τhe diversity of OMT comes from its syllabus that matches MOE’ѕ
νia interdisciplinary linkѕ, linking mathematics to science
аnd everyday probⅼem-solving.
Team forums іn the platform allοw you talk ɑbout witһ peers ѕia,
mаking clear doubts and enhancing your mathematics performance.
Tuition in mathematics assists Singapore students establish rate ɑnd accuracy,
іmportant for completing teats ԝithin timе frame.
Check ߋut my web blog maths tuition assignments singapore
maths tuition assignments singapore
28 Oct 25 at 6:48 am
This is a topic which is near to my heart… Many thanks!
Where are your contact details though?
LOTTO CHAMP
28 Oct 25 at 6:48 am
обмазочная гидроизоляция цена работы [url=http://gidroizolyaciya-cena-8.ru/]обмазочная гидроизоляция цена работы[/url] .
gidroizolyaciya cena_mxKn
28 Oct 25 at 6:49 am
Мы не используем универсальные «сильные капельницы». Эффективность даёт точное совпадение с задачей. Ниже — логика выбора профилей и маркеры, на которые мы ориентируемся при контроле эффективности и безопасности.
Выяснить больше – [url=https://vivod-iz-zapoya-v-sankt-peterburge16.ru/]вывод из запоя на дому в санкт-петербурге[/url]
AnthonyOramb
28 Oct 25 at 6:49 am
ремонт подвала [url=www.gidroizolyaciya-podvala-cena.ru]ремонт подвала[/url] .
gidroizolyaciya podvala cena_lqKt
28 Oct 25 at 6:49 am
наркологическая больница [url=https://narkologicheskaya-klinika-28.ru/]наркологическая больница[/url] .
narkologicheskaya klinika_ehMa
28 Oct 25 at 6:51 am
монтаж стеклянных душевых кабин [url=http://dzen.ru/a/aPaQV60E-3Bo4dfi/]http://dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .
steklyannie dyshevie na zakaz _lxol
28 Oct 25 at 6:51 am
kraken qr code
кракен vk2
Henryamerb
28 Oct 25 at 6:51 am
ремонт в подвале [url=http://gidroizolyaciya-podvala-cena.ru/]http://gidroizolyaciya-podvala-cena.ru/[/url] .
gidroizolyaciya podvala cena_zoKt
28 Oct 25 at 6:52 am
клиника наркологическая платная [url=http://www.narkologicheskaya-klinika-27.ru]http://www.narkologicheskaya-klinika-27.ru[/url] .
narkologicheskaya klinika_pzpl
28 Oct 25 at 6:52 am
Excellent site you have here but I was wanting to know if you
knew of any community forums that cover the same topics discussed in this article?
I’d really like to be a part of group where I can get comments
from other knowledgeable people that share the same interest.
If you have any suggestions, please let me know. Many thanks!
đặt hoa chúc mừng
28 Oct 25 at 6:52 am
диплом техникума купить с проводкой [url=https://frei-diplom9.ru]диплом техникума купить с проводкой[/url] .
Diplomi_djea
28 Oct 25 at 6:53 am
сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-cena-7.ru]https://gidroizolyaciya-cena-7.ru[/url] .
gidroizolyaciya cena_xkSi
28 Oct 25 at 6:54 am
WOW just what I was searching for. Came here by searching for
assignment help
assignment writer
28 Oct 25 at 6:54 am
купить диплом о высшем образовании [url=https://www.rudik-diplom8.ru]купить диплом о высшем образовании[/url] .
Diplomi_pbMt
28 Oct 25 at 6:54 am
Обеспечьте комфорт и стиль в вашем доме с [url=https://rulonnye-shtory-umnyy-dom.ru/]автоматические рулонные жалюзи Прокарниз[/url], которые идеально впишутся в современный интерьер.
Умные рулонные шторы становятся все более популярными в современных интерьерах. Применение автоматических штор позволяет не только удобно регулировать свет, но и добавить стиль в ваш дом. Подобные изделия идеально вписываются в концепцию “умного дома”.
Системы автоматизации позволяют управлять шторами с помощью смартфона. Владельцы могут задавать график работы штор в зависимости от времени суток. Это удобно делает жизнь более комфортной.
Кроме того, рулонные шторы с автоматизированным управлением могут быть оснащены датчиками света и температуры. Эти датчики автоматически регулируют положение штор для достижения оптимального уровня освещенности. Таким образом вы можете экономить на электроэнергии благодаря естественному освещению.
Установка автоматических рулонных штор достаточно прост и не требует специальных навыков. Вы можете установить их самостоятельно, следуя инструкциям. Когда шторы установлены, вы сможете наслаждаться всеми преимуществами умного дома.
рулонные жалюзи с электроприводом купить
28 Oct 25 at 6:55 am
Перед перечнем поясним логику: домашний визит уместен, когда обстановка безопасна, риски контролируемы и есть взрослый помощник на вечер и ночь. Ниже — ориентиры, при которых имеет смысл начать с выезда, а не со стационара.
Подробнее можно узнать тут – [url=https://narkolog-na-dom-voskresensk8.ru/]narkolog-na-dom-voskresensk8.ru/[/url]
Traviscot
28 Oct 25 at 6:55 am
купить проведенный диплом моих [url=http://frei-diplom2.ru/]купить проведенный диплом моих[/url] .
Diplomi_nvEa
28 Oct 25 at 6:55 am
I’m not that much of a online reader to be honest but your blogs really nice,
keep it up! I’ll go ahead and bookmark your website to come back later.
All the best
雷电模拟器
28 Oct 25 at 6:56 am
гидроизоляция цена кг [url=http://www.gidroizolyaciya-cena-8.ru]http://www.gidroizolyaciya-cena-8.ru[/url] .
gidroizolyaciya cena_ziKn
28 Oct 25 at 6:56 am