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=www.sliv.fun]www.sliv.fun[/url] .
Sliv kyrsov_hxEn
3 Oct 25 at 10:19 am
диплом техникума купить в украине [url=www.frei-diplom9.ru]диплом техникума купить в украине[/url] .
Diplomi_czea
3 Oct 25 at 10:19 am
прогнозы на спорт бесплатно на сегодня [url=prognozy-na-sport-11.ru]прогнозы на спорт бесплатно на сегодня[/url] .
prognozi na sport_glPa
3 Oct 25 at 10:19 am
диплом жд техникума купить [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_okea
3 Oct 25 at 10:19 am
Inspiring story there. What occurred after? Thanks!
تعمیر مایکروفر ال جی
3 Oct 25 at 10:20 am
Greetings from Idaho! I’m bored at work so I decided to browse
your blog on my iphone during lunch break.
I really like the info you provide here and can’t wait to take a
look when I get home. I’m amazed at how quick your blog loaded on my cell phone ..
I’m not even using WIFI, just 3G .. Anyways, amazing blog!
бездепозитный бонус
3 Oct 25 at 10:20 am
спорт 24 часа [url=http://novosti-sporta-15.ru]http://novosti-sporta-15.ru[/url] .
novosti sporta_qxma
3 Oct 25 at 10:21 am
купить диплом в горно-алтайске [url=http://rudik-diplom14.ru]http://rudik-diplom14.ru[/url] .
Diplomi_tzea
3 Oct 25 at 10:21 am
https://tadalmedspharmacy.com/# Buy Tadalafil online
Williamjib
3 Oct 25 at 10:22 am
новости футбольных клубов [url=https://novosti-sporta-17.ru/]https://novosti-sporta-17.ru/[/url] .
novosti sporta_juOi
3 Oct 25 at 10:23 am
спорт онлайн [url=http://novosti-sporta-16.ru]http://novosti-sporta-16.ru[/url] .
novosti sporta_pssi
3 Oct 25 at 10:23 am
https://www.wildberries.ru/catalog/514992745/detail.aspx
Kevinsaush
3 Oct 25 at 10:24 am
прогноз на спорт от профессионалов [url=http://prognozy-na-sport-12.ru]прогноз на спорт от профессионалов[/url] .
prognozi na sport_sxMn
3 Oct 25 at 10:25 am
Thanks in support of sharing such a fastidious opinion, post is nice,
thats why i have read it entirely
online casino ohne oasis
3 Oct 25 at 10:26 am
обзор спортивных событий [url=http://novosti-sporta-17.ru/]http://novosti-sporta-17.ru/[/url] .
novosti sporta_eiOi
3 Oct 25 at 10:27 am
новости чемпионатов [url=https://novosti-sporta-15.ru/]https://novosti-sporta-15.ru/[/url] .
novosti sporta_rema
3 Oct 25 at 10:28 am
точные прогнозы на спорт [url=https://prognozy-na-sport-12.ru]точные прогнозы на спорт[/url] .
prognozi na sport_tsMn
3 Oct 25 at 10:30 am
купить диплом менеджера [url=http://rudik-diplom15.ru]купить диплом менеджера[/url] .
Diplomi_rnPi
3 Oct 25 at 10:30 am
Курс по осознанному движению научил меня двигаться с радостью. Рекомендую!
как избавиться от напряжения в теле
Arthuraduch
3 Oct 25 at 10:30 am
Мы заказали в компании СтройСинтез коттедж из кирпича на три этажа. Результат впечатлил: просторные комнаты, удобная планировка и красивая архитектура. Работы выполнены профессионально. Подробности доступны здесь: https://stroysyntez.com/
Brianvop
3 Oct 25 at 10:31 am
Приобрести MEF GASH SHIHSKI ALFA – ОТЗЫВЫ, ГАРАНТРР, КАЧЕСТВО
Jeromeliz
3 Oct 25 at 10:31 am
Excited about $MTAUR’s potential in the $14.78B gaming sector. Presale perks like value appreciation are drawing me. Game’s minotaur hero is iconic.
mtaur coin
WilliamPargy
3 Oct 25 at 10:31 am
This article was really well written and easy to follow.
I enjoyed the way you explained the details step by step, which made it much easier for
me to understand.
I’ve read many posts on similar topics, but this one stood out because it felt more practical.
Thanks for sharing and I’ll definitely be checking back for more
updates.
7meter slot
3 Oct 25 at 10:31 am
бесплатные прогнозы на ставки [url=https://www.prognozy-na-sport-11.ru]https://www.prognozy-na-sport-11.ru[/url] .
prognozi na sport_evPa
3 Oct 25 at 10:32 am
[url=https://madcasino.top]mad casino[/url]
Horacesax
3 Oct 25 at 10:32 am
спорт сегодня [url=novosti-sporta-17.ru]novosti-sporta-17.ru[/url] .
novosti sporta_raOi
3 Oct 25 at 10:33 am
These are truly impressive ideas in concerning blogging.
You have touched some nice points here. Any way
keep up wrinting.
Zeno Flow Engine
3 Oct 25 at 10:33 am
Disney made a smart choice’
Despite the comparisons, Abu Dhabi isn’t positioning itself as a direct rival to Orlando — it’s aiming to be something more. The emirate sees its theme parks as part of a bigger portfolio of attractions, alongside cultural landmarks, luxury hotels, pristine beaches, and desert adventures.
[url=http://trips45.cc]трип скан[/url]
A 15-minute drive from Yas Island, Saadiyat Island is home to the Louvre Abu Dhabi, a franchised outpost of the famous Paris art museum, which welcomed 1.4 million visitors last year, 84% from abroad. The Guggenheim Abu Dhabi and Zayed National Museum are both under construction, adding to a cultural district that will be one of the region’s most concentrated hubs of art and heritage.
“Abu Dhabi’s unique appeal lies in the diversity of our tourism offering,” Al Geziry added. “For thrill-seekers, we have record-breaking roller coasters and dune bashing in the desert. For culture lovers, historic sites like Al Ain Oasis and institutions like the Saadiyat museums. And for luxury travelers, world-class dining, private island resorts, and high-end shopping.
“Where else can you start your day under the Louvre’s iconic rain-of-light dome and end it in the immersive, story-driven worlds of Warner Bros. World or Ferrari World?”
http://trips45.cc
трипскан вход
Still, not everyone is convinced that Disney’s expansion into the Middle East is a sure bet.
“The region has seen its share of false starts,” says Dennis Speigel, founder of the International Theme Park Services consultancy, comparing it to neighboring Dubai’s patchy record with theme park expansion ambitions in the mid-2010s. “Several of them struggled for profitability in their first decade.”
Related article
Saadiyat Cultural District in Abu Dhabi is set to become one of the world’s preeminent arts and culture hubs, with one of the highest concentrations of cultural institutions globally. But the area isn’t just for art connoisseurs. Explore what to do in the new district, from iconic museums to luxurious beach days to decadent dining options.
You can walk between the Louvre and the Guggenheim in this new art district
Spiegel believes Abu Dhabi is different. “Disney made a smart choice. The infrastructure, safety, and existing leisure developments create an ideal entry point,” he told CNN earlier this year. “It’s a much more controlled and calculated move.”
Under its Tourism Strategy 2030, Abu Dhabi aims to grow annual visitors from 24 million in 2023 to more than 39 million by the end of the decade. With Disneyland as a centerpiece, those targets may well be surpassed. The city’s population has already grown from 2.7 million in 2014 to more than 4.1 million today, a reflection of its rising profile as a regional hub.
Yas Island alone has been transformed in the space of a decade from a largely undeveloped stretch of sand to a self-contained resort destination, complete with golf courses, marinas, a mall, more than 160 restaurants, and a cluster of high-end hotels.
Orlando’s head start remains formidable — it still offers multiple Disney and Universal parks, has decades of brand loyalty, and an infrastructure built to handle tens of millions of tourists annually.
But Abu Dhabi is catching up fast. Its combination of frictionless travel, year-round comfort, cutting-edge attractions, and a cultural scene that adds depth to the experience gives Abu Dhabi its own unique selling point, potentially offering a model for the next generation of theme park capital.
KeithUnlah
3 Oct 25 at 10:34 am
Курс по улучшению самочувствия для женщин — это забота о себе. Чувствую себя лучше!
курс по танцевальной терапии
Arthuraduch
3 Oct 25 at 10:35 am
I loved as much as you’ll receive carried out right here.
The sketch is tasteful, your authored material stylish.
nonetheless, you command get bought an shakiness over that you wish be delivering the following.
unwell unquestionably come more formerly again since
exactly the same nearly a lot often inside case you shield this hike.
trip scan
3 Oct 25 at 10:35 am
прогнозы на сегодня на спорт [url=https://prognozy-na-sport-12.ru/]prognozy-na-sport-12.ru[/url] .
prognozi na sport_mzMn
3 Oct 25 at 10:36 am
купить диплом инженера строителя [url=https://rudik-diplom1.ru]купить диплом инженера строителя[/url] .
Diplomi_ruer
3 Oct 25 at 10:37 am
Мир гаджетов без воды https://indevices.ru честные обзоры, реальные замеры, фото/видео-примеры. Смартфоны, планшеты, аудио, гейминг, аксессуары. Сравнения моделей, советы по апгрейду, трекер цен и уведомления о скидках. Помогаем выбрать устройство под задачи.
ShermanRacle
3 Oct 25 at 10:37 am
MyEtherWallet is a secure and easy-to-use Ethereum wallet that lets
you store, send, and receive Ether safely. With MEW wallet, you
control your crypto without limits, making MEW crypto management simple.
ethereum wallet
3 Oct 25 at 10:38 am
The nurturing atmosphere аt OMT motivates inquisitiveness іn mathematics, tսrning Singapore pupils гight into enthusiastic learners motivated tо attain leading examination гesults.
Experience versatile learning anytime, аnywhere
tһrough OMT’s comprehensive online е-learning platform, including unljmited access tօ video lessons аnd interactive tests.
Singapore’ѕ emphasis on іmportant thinking tһrough mathematics highlights tһe significance оf math tuition, whicһ assists students develop tһe analytical skills required Ƅy the nation’s forward-thinking syllabus.
Witһ PSLE mathematics concerns typically involving real-ԝorld
applications, tuition ⲣrovides targeted practice t᧐ develop
critical believing skills essential fοr һigh scores.
Secondary math tuition conquers the limitations оf bіg class sizes, offering concentrated
attention tһat improves understanding fоr O Level preparation.
Ϝor tһose ɡoing after H3 Mathematics, junior college tuition supplies sophisticated assistance
ߋn reseaгch-level subjects tо master thіѕ
challenging extension.
Ꭲhe proprietary OMT curriculum distinctly enhances tһe
MOE syllabus with concentrated practice оn heuristic
approaches, preparing trainees bеtter fοr exam challenges.
Personalized development monitoring іn OMT’s system reveals y᧐ur vulnerable
рoints sia, permitting targeted technique fоr grade renovation.
Bү incorporating innovation, оn the internet math tuition engages digital-native Singapore trainees f᧐r interactive examination alteration.
Check ⲟut my web blog – jc math tuition assignment
jc math tuition assignment
3 Oct 25 at 10:38 am
купить диплом в альметьевске [url=https://rudik-diplom8.ru/]купить диплом в альметьевске[/url] .
Diplomi_dfMt
3 Oct 25 at 10:39 am
Everyone loves what you guys tend to be up too. Such clever work and reporting!
Keep up the amazing works guys I’ve added you guys to my blogroll.
turkey visa for australian
3 Oct 25 at 10:40 am
Ваш портал о стройке https://gidfundament.ru и ремонте: материалы, инструменты, сметы и бюджеты. Готовые решения для кухни, ванной, спальни и террасы. Нормы, чертежи, контроль качества, приёмка работ. Подбор подрядчика, прайсы, акции и полезные образцы документов.
WilliamLaria
3 Oct 25 at 10:40 am
свежие новости спорта [url=novosti-sporta-15.ru]novosti-sporta-15.ru[/url] .
novosti sporta_bmma
3 Oct 25 at 10:40 am
Наш интернет-магазин требовал внимания, так как заказы падали. Mihaylov Digital провели оптимизацию, добавили описания товаров и настроили аналитику. Через три месяца мы увидели рост продаж и возвращение клиентов. Это лучший результат за последнее время – https://mihaylov.digital/
Steventob
3 Oct 25 at 10:40 am
Мир гаджетов без воды https://indevices.ru честные обзоры, реальные замеры, фото/видео-примеры. Смартфоны, планшеты, аудио, гейминг, аксессуары. Сравнения моделей, советы по апгрейду, трекер цен и уведомления о скидках. Помогаем выбрать устройство под задачи.
ShermanRacle
3 Oct 25 at 10:40 am
Ремонт и стройка https://remontkit.ru без лишних затрат: инструкции, таблицы расхода, сравнение цен, контроль скрытых работ. База подрядчиков, отзывы, чек-листы, калькуляторы. Тренды дизайна, 3D-планировки, лайфхаки по хранению и зонированию. Практика и цифры.
VincentjOrry
3 Oct 25 at 10:41 am
купить диплом в коврове [url=https://rudik-diplom15.ru]купить диплом в коврове[/url] .
Diplomi_vtPi
3 Oct 25 at 10:41 am
Ваш портал о стройке https://gidfundament.ru и ремонте: материалы, инструменты, сметы и бюджеты. Готовые решения для кухни, ванной, спальни и террасы. Нормы, чертежи, контроль качества, приёмка работ. Подбор подрядчика, прайсы, акции и полезные образцы документов.
WilliamLaria
3 Oct 25 at 10:43 am
I all the time used to study paragraph in news papers but now as I am
a user of net so from now I am using net for content,
thanks to web.
Feel free to visit my web site This article
This article
3 Oct 25 at 10:43 am
Ремонт и стройка https://remontkit.ru без лишних затрат: инструкции, таблицы расхода, сравнение цен, контроль скрытых работ. База подрядчиков, отзывы, чек-листы, калькуляторы. Тренды дизайна, 3D-планировки, лайфхаки по хранению и зонированию. Практика и цифры.
VincentjOrry
3 Oct 25 at 10:44 am
Your style is so unique compared to other folks I’ve read stuff from.
Many thanks for posting when JAKKOUTTHEBXX’S All-Over Print Artful Tough Magnetic Cases | Sold At Artsulli and Now on Amazon | You can’t spell Artsulli without Art!‘ve got the opportunity,
Guess I’ll just book mark this blog.
JAKKOUTTHEBXX'S All-Over Print Artful Tough Magnetic Cases | Sold At Artsulli and Now on Amazon | You can't spell Artsulli without Art!
3 Oct 25 at 10:44 am
новости мирового спорта [url=http://novosti-sporta-17.ru/]http://novosti-sporta-17.ru/[/url] .
novosti sporta_xzOi
3 Oct 25 at 10:45 am
экспресс прогнозы на спорт [url=prognozy-na-sport-11.ru]prognozy-na-sport-11.ru[/url] .
prognozi na sport_eePa
3 Oct 25 at 10:45 am
Мы понимали, что сайт требует SEO, но не знали, кому доверить. В середине поисков выбрали Mihaylov Digital и попали в точку. Команда сделала оптимизацию и выстроила стратегию продвижения. Теперь мы в топе и получаем клиентов стабильно – https://mihaylov.digital/
Steventob
3 Oct 25 at 10:45 am