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=https://narkolog-na-dom-serpuhov6.ru/]врач нарколог на дом[/url]
SamuelClosy
15 Oct 25 at 4:12 am
OMT’s ɑll natural approach nurtures not ϳust skills ƅut delight іn mathematics, motivating pupils tߋ accept tһe subject ɑnd shine in their exams.
Discover tһe convenience οf 24/7 online math tuition at OMT, wһere
appealing resources maке finding оut fun аnd efficient for alⅼ levels.
As mathematics underpins Singapore’ѕ reputation for quality in international criteria lіke PISA, math tuition iѕ key
t᧐ unlocking a kid’s potential and protecting scholastic benefits іn tһis core subject.
Tuition emphasizes heuristic analytical ɑpproaches, crucial fⲟr tɑking ᧐n PSLE’s tough
word issues tһat need numerous steps.
Ⲣresenting heuristic methods early in secondary tuition prepares trainees fоr the non-routine
troubles tһat frequently show սp in O Level assessments.
Witһ regular simulated examinations ɑnd thоrough responses, tuition helps junior college students
determine аnd correct weaknesses prior tо the real A Levels.
Ƭhe exclusive OMTeducational program distinctively improves tһe MOE curriculum ᴡith
focused practice on heuristic ɑpproaches, preparing
pupils ƅetter for exam difficulties.
OMT’ѕ online system enhances MOE syllabus one, assisting ʏou tackle PSLE math ᴡith ease and
far Ьetter ratings.
Ԍroup math tuition in Singapore cultivates peer understanding, encouraging pupils
tⲟ press mⲟre challenging fⲟr exceptional test outcomes.
Αlso visit my web pаge :: math e-learning
math e-learning
15 Oct 25 at 4:12 am
Brit Meds Direct [url=https://britmedsdirect.com/#]pharmacy online UK[/url] Brit Meds Direct
Jameshoasy
15 Oct 25 at 4:14 am
куплю диплом младшей медсестры [url=https://frei-diplom13.ru]https://frei-diplom13.ru[/url] .
Diplomi_dykt
15 Oct 25 at 4:15 am
компания потолочкин [url=http://natyazhnye-potolki-samara-2.ru]http://natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_hgPi
15 Oct 25 at 4:17 am
Чтобы у семьи было чёткое понимание, что и в какой последовательности мы делаем, ниже — рабочий алгоритм для стационара и для выезда на дом (шаги идентичны, различается только объём мониторинга и доступная диагностика).
Разобраться лучше – https://kapelnica-ot-zapoya-vidnoe7.ru/prokapatsya-ot-alkogolya-v-vidnom
Walterral
15 Oct 25 at 4:17 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
tripscan
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.
KennethElasy
15 Oct 25 at 4:17 am
ラブドール 激安t be in the streets alone,Petersburg is an awful place in thatway.
ダッチワイフ
15 Oct 25 at 4:18 am
купить диплом медсестры [url=https://frei-diplom15.ru/]купить диплом медсестры[/url] .
Diplomi_pdoi
15 Oct 25 at 4:18 am
Good site you’ve got here.. It’s hard to
find good quality writing like yours nowadays. I truly appreciate individuals like you!
Take care!!
Velantrexis TEST
15 Oct 25 at 4:19 am
ラブドール 最新andthere are rivulets and springs above the cathedral,sufficient to fill alarge reservoir with excellent water,
ダッチワイフ
15 Oct 25 at 4:21 am
https://telegra.ph/Kupit-teplovizor-otzyvy-10-13-3
RonaldZer
15 Oct 25 at 4:22 am
オナドールis not so considerable,as that one man can thereupon claim to himselfe any benefit,
ダッチワイフ
15 Oct 25 at 4:23 am
Prednisolone tablets UK online: Prednisolone tablets UK online – MedRelief UK
Brettesofe
15 Oct 25 at 4:25 am
купить диплом с занесением в реестр [url=www.frei-diplom1.ru/]купить диплом с занесением в реестр[/url] .
Diplomi_whOi
15 Oct 25 at 4:25 am
купить диплом техникума ссср в волжске [url=http://www.frei-diplom11.ru]купить диплом техникума ссср в волжске[/url] .
Diplomi_hdsa
15 Oct 25 at 4:25 am
купить диплом в белово [url=http://rudik-diplom2.ru/]http://rudik-diplom2.ru/[/url] .
Diplomi_gtpi
15 Oct 25 at 4:26 am
had received him very kindly,promised not to forget him,美人 せっくす
ダッチワイフ
15 Oct 25 at 4:26 am
купить диплом спортивного техникума [url=frei-diplom9.ru]купить диплом спортивного техникума[/url] .
Diplomi_nqea
15 Oct 25 at 4:29 am
which twocenturies of systematic legal defilement of Negro women had stampedupon his race,meant not only the loss of ancient African chastity,ロボット セックス
ダッチワイフ
15 Oct 25 at 4:29 am
купить диплом менеджера [url=http://rudik-diplom7.ru/]купить диплом менеджера[/url] .
Diplomi_gkPl
15 Oct 25 at 4:31 am
セックス ロボットwith a Christian mildness that expressed forgiveness of hisindiscretion,nodded and said: “I hope to see you again,
ダッチワイフ
15 Oct 25 at 4:32 am
купить диплом в челябинске [url=www.rudik-diplom9.ru/]купить диплом в челябинске[/url] .
Diplomi_mcei
15 Oct 25 at 4:34 am
whichsettling of significations,they call Definitions,えろ 人形
ダッチワイフ
15 Oct 25 at 4:34 am
купить диплом товароведа [url=http://www.rudik-diplom10.ru]купить диплом товароведа[/url] .
Diplomi_jvSa
15 Oct 25 at 4:35 am
Amazing blog! Do you have any helpful hints for aspiring writers?
I’m planning to start my own blog soon but I’m a little lost on everything.
Would you suggest starting with a free platform
like WordPress or go for a paid option? There
are so many options out there that I’m completely confused
.. Any tips? Thanks a lot!
The Water Heater Warehouse
15 Oct 25 at 4:38 am
сколько стоит купить диплом в колледже [url=https://frei-diplom11.ru]https://frei-diplom11.ru[/url] .
Diplomi_bqsa
15 Oct 25 at 4:38 am
потолочкин натяжные потолки самара отзывы клиентов [url=www.natyazhnye-potolki-samara-2.ru]www.natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_cqPi
15 Oct 25 at 4:38 am
купить диплом в кургане занесением в реестр [url=http://frei-diplom1.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_prOi
15 Oct 25 at 4:39 am
купить диплом в кропоткине [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .
Diplomi_sbpi
15 Oct 25 at 4:39 am
можно ли купить диплом медсестры [url=www.frei-diplom13.ru]можно ли купить диплом медсестры[/url] .
Diplomi_njkt
15 Oct 25 at 4:39 am
купить диплом техникума открыто [url=www.frei-diplom9.ru]купить диплом техникума открыто[/url] .
Diplomi_ihea
15 Oct 25 at 4:39 am
Сериалы 2025 скачать торрент Скачать сериалы торрент Сериалы стали неотъемлемой частью нашей жизни, позволяя нам погружаться в увлекательные истории и переживать за любимых персонажей. На нашем сайте вы найдете огромную коллекцию сериалов на любой вкус: от захватывающих детективных историй и фантастических саг до комедийных ситкомов и мелодраматических драм. Мы предлагаем скачать сериалы торрент в высоком качестве, чтобы вы могли наслаждаться каждым эпизодом в полной мере. У нас вы найдете как популярные новинки, так и классические сериалы, завоевавшие любовь миллионов зрителей. Наша коллекция постоянно пополняется, поэтому вы всегда сможете найти что-то интересное для себя. Благодаря удобной системе поиска и фильтрации вы легко сможете найти нужный сериал по названию, жанру, году выпуска, рейтингу и другим критериям. Скачивайте сериалы торрент быстро и безопасно с нашего сайта! Мы гарантируем высокое качество файлов и отсутствие вирусов. Наслаждайтесь просмотром любимых сериалов в любое время и в любом месте!
Raymondcoedo
15 Oct 25 at 4:39 am
купить диплом в омске [url=www.rudik-diplom13.ru/]купить диплом в омске[/url] .
Diplomi_tnon
15 Oct 25 at 4:40 am
купить диплом в соликамске [url=https://www.rudik-diplom7.ru]купить диплом в соликамске[/url] .
Diplomi_irPl
15 Oct 25 at 4:41 am
More Tips
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
More Tips
15 Oct 25 at 4:46 am
можно купить диплом медсестры [url=www.frei-diplom13.ru]можно купить диплом медсестры[/url] .
Diplomi_ikkt
15 Oct 25 at 4:49 am
Кодирование подходит не только для тех, кто страдает тяжёлой зависимостью с частыми рецидивами, но и для тех, кто хочет закрепить результат длительной ремиссии, повысить личную мотивацию, снизить риск срыва и облегчить адаптацию к жизни без спиртного. Решение о выборе методики принимается только после осмотра врача и сбора полного анамнеза.
Изучить вопрос глубже – [url=https://kodirovanie-ot-alkogolizma-dolgoprudnyj6.ru/]centr-kodirovaniya-ot-alkogolizma[/url]
ArthurKalse
15 Oct 25 at 4:50 am
купить диплом в гуково [url=https://rudik-diplom10.ru/]купить диплом в гуково[/url] .
Diplomi_edSa
15 Oct 25 at 4:50 am
купить диплом в новоуральске [url=https://rudik-diplom13.ru/]https://rudik-diplom13.ru/[/url] .
Diplomi_tson
15 Oct 25 at 4:52 am
купить диплом юриста [url=www.rudik-diplom2.ru/]купить диплом юриста[/url] .
Diplomi_lfpi
15 Oct 25 at 4:54 am
https://telegra.ph/Kvadrokopter-dji-mini-2-pro-kupit-10-12-3
RonaldZer
15 Oct 25 at 4:54 am
$MTAUR presale is flying under radar but shouldn’t—80% discount is insane value. In-game mini-games unlocked by tokens add replayability. Bullish on its 9% annual market growth projection.
minotaurus coin
WilliamPargy
15 Oct 25 at 4:54 am
натяжные потолки дешево самара [url=www.natyazhnye-potolki-samara-2.ru/]натяжные потолки дешево самара[/url] .
natyajnie potolki samara_auPi
15 Oct 25 at 4:58 am
купить диплом в троицке [url=https://rudik-diplom13.ru/]https://rudik-diplom13.ru/[/url] .
Diplomi_qaon
15 Oct 25 at 5:03 am
купить диплом в славянске-на-кубани [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_axSa
15 Oct 25 at 5:04 am
купить диплом историка [url=http://rudik-diplom6.ru/]купить диплом историка[/url] .
Diplomi_xaKr
15 Oct 25 at 5:06 am
купить диплом в коврове [url=http://rudik-diplom9.ru/]купить диплом в коврове[/url] .
Diplomi_awei
15 Oct 25 at 5:11 am
I really like your blog.. very nice colors & theme. Did you
make this website yourself or did you hire someone to do it for you?
Plz answer back as I’m looking to create my own blog and
would like to find out where u got this from.
appreciate it
site
15 Oct 25 at 5:12 am
Great delivery. Sound arguments. Keep up the great effort.
Extra resources
15 Oct 25 at 5:14 am