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!
seo продвижение рейтинг компаний [url=https://reiting-seo-kompaniy.ru]seo продвижение рейтинг компаний[/url] .
reiting seo kompanii_udon
23 Oct 25 at 6:36 am
Que ce soit pour un mariage, une fête ou une simple sortie
entre amis, elles ajoutent toujours une touche d’élégance et de
singularité.
Eleanore
23 Oct 25 at 6:36 am
My relatives always say that I am wasting my time here at net, however I know I am getting familiarity all
the time by reading such pleasant articles.
https://www.exotic-africa.com/
23 Oct 25 at 6:39 am
Article writing is also a fun, if you be acquainted with afterward you can write or else it is complicated to write.
industrial kitchen exhaust
23 Oct 25 at 6:40 am
Installation: using, open the [url=https://christinamcondreay.com/wp/1xbet-malaysia-betting-an-in-depth-guide/]https://christinamcondreay.com/wp/1xbet-malaysia-betting-an-in-depth-guide/[/url] and run its installation. Download the 1xbet app: Launch the 1xbet download.
RebeccaAudic
23 Oct 25 at 6:41 am
Because the admin of this web page is working, no doubt very rapidly it will be
renowned, due to its quality contents.
Trang chủ 32win
23 Oct 25 at 6:44 am
I’m really loving the theme/design of your website. Do you ever run into
any internet browser compatibility problems?
A few of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Chrome.
Do you have any recommendations to help fix this problem?
sbmarketinggroup
23 Oct 25 at 6:46 am
купить диплом математика [url=http://www.rudik-diplom13.ru]купить диплом математика[/url] .
Diplomi_xvon
23 Oct 25 at 6:48 am
Если вы ищете безопасный вывод из запоя, обратитесь в Екатеринбурге в «Похмельную Службу». Медики приедут в течение часа.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]вывод из запоя вызов в екатеринбурге[/url]
ClydeLak
23 Oct 25 at 6:50 am
trendyfindshub – Very user-friendly interface, things load fast, content is engaging and fresh.
Julietta Henesey
23 Oct 25 at 6:52 am
Nice answers in return of this query with genuine arguments and describing the whole thing regarding that.
xn88.com
23 Oct 25 at 6:53 am
I believe this is among the most significant information for me.
And i’m happy studying your article. But want
to remark on few general things, The website style
is perfect, the articles is really nice : D.
Just right job, cheers
exterior painting
23 Oct 25 at 6:54 am
An outstanding share! I have just forwarded this onto a co-worker who was doing a
little research on this. And he actually ordered me
breakfast simply because I found it for him… lol.
So let me reword this…. Thanks for the meal!! But yeah, thanks for spending the time to discuss this subject
here on your web site.
32win vip
23 Oct 25 at 6:58 am
1xbet mobil giri? [url=1xbet-giris-4.com]1xbet-giris-4.com[/url] .
1xbet giris_xhSa
23 Oct 25 at 6:58 am
компания seo [url=www.reiting-seo-kompaniy.ru]www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_nyon
23 Oct 25 at 6:59 am
войти в 1win [url=www.1win5519.ru]войти в 1win[/url]
1win_kg_miEr
23 Oct 25 at 7:01 am
купить диплом в новом уренгое [url=http://rudik-diplom9.ru/]http://rudik-diplom9.ru/[/url] .
Diplomi_edei
23 Oct 25 at 7:03 am
http://www.lenotoplenie.ru свежие акции и инструкции по использованию промокодов
Aaronawads
23 Oct 25 at 7:03 am
Hello! I’m at work surfing around your blog from my new iphone 3gs!
Just wanted to say I love reading through your blog and look forward to all your posts!
Carry on the superb work!
kra40 at
23 Oct 25 at 7:03 am
https://lemoncasinomagyar.com/
1-gocasino.com
23 Oct 25 at 7:07 am
Excellent article. Keep writing such kind of info on your page.
Im really impressed by your blog.
Hey there, You’ve performed an incredible job.
I’ll certainly digg it and for my part recommend to my friends.
I’m confident they’ll be benefited from this web
site.
advice
23 Oct 25 at 7:07 am
купить диплом в южно-сахалинске [url=http://rudik-diplom13.ru]купить диплом в южно-сахалинске[/url] .
Diplomi_pdon
23 Oct 25 at 7:07 am
Преимущества домашнего лечения также заключаются в индивидуальном подходе. Врач, находясь в вашем доме, может более тщательно изучить ситуацию, провести необходимую диагностику и подобрать курс лечения, который идеально подойдет вашему состоянию. В отличие от клиники, где внимание врача часто ограничено временем, на дому можно уделить пациенту больше времени, подбирая лечение с учетом его особенностей.
Получить больше информации – https://narcolog-na-dom-moskva55.ru/vyzov-narkologa-na-dom-moskva/
Bretttah
23 Oct 25 at 7:11 am
Этот обзор предлагает структурированное изложение информации по актуальным вопросам. Материал подан так, чтобы даже новичок мог быстро освоиться в теме и начать использовать полученные знания в практике.
Только для своих – https://duiksport.nl/dazenval/?product=zwarte-bal-voor-dazenval
Josephhip
23 Oct 25 at 7:14 am
остался дико не рад, но селлер быстро пообещал кидануть бонуса при следующей покупке. надеюсь, не пожадничают
Онлайн магазин – купить мефедрон, кокаин, бошки
, обычно мин 20-40
Thomasneump
23 Oct 25 at 7:16 am
you’re really a good webmaster. The site loading pace is amazing.
It kind of feels that you’re doing any unique trick.
In addition, The contents are masterwork. you’ve performed a
wonderful process on this subject!
Gay
23 Oct 25 at 7:22 am
Китайское дунхуа стремительно покоряет мир — и лучшее место, чтобы открыть для себя его масштаб и стиль, это AniChi. Здесь удобно смотреть и скачивать любимые сериалы и фильмы, от эпических фэнтези до исторических драм, с регулярными обновлениями новых серий и аккуратной навигацией по жанрам. В середине пути вас уже затянет «Боевой континент» или «Противостояние святого», а перейти к коллекции просто: https://anichi.fun/ — сообщество, рейтинги и быстрый поиск сделают просмотр по-настоящему комфортным. Откройте дунхуа так, как его задумывали авторы.
liwyrtelarl
23 Oct 25 at 7:22 am
топ seo агентств мира [url=https://reiting-seo-kompaniy.ru/]https://reiting-seo-kompaniy.ru/[/url] .
reiting seo kompanii_qfon
23 Oct 25 at 7:28 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Узнайте всю правду – https://rkcorporationbag.com/plastic-packaging-strip
Wilmereveni
23 Oct 25 at 7:28 am
Օpen Singapore’ѕ event deals tһrough Kaizenaire.com,
the supreme promotions collector.
From Orchard Road to Marina Bay, Singapore personifies ɑ shopping heaven ԝhere
residents stress oveг thе newеst promotions and unequalled deals.
Singaporeans unwind ԝith symphonic music concerts
ɑt Victoria Theatre, аnd keep in mind tо гemain upgraded ߋn Singapore’s lateѕt promotions аnd shopping deals.
Workshop HHFZ produces bold, imaginative fashion products, enjoyed Ƅy innovative Singaporeans for tһeir unique patterns аnd expressive styles.
Grab оffers ride-hailing, food shipment, ɑnd financial solutions lor, adored Ьу Singaporeans foг their benefit in daily commutes аnd
dishes leh.
Asian Home Gourmet simmers spice pastes fоr curries, valued foг genuine Asian tastes
withоut inconvenience.
Bеtter be aⅼl set lah, Kaizenaire.com updates promotions frequently leh.
Feel free tօ visit mү site; promos
promos
23 Oct 25 at 7:28 am
1win скачать на айфон бесплатно [url=https://www.1win5518.ru]https://www.1win5518.ru[/url]
1win_kg_mrkl
23 Oct 25 at 7:28 am
1win ставки зеркало [url=https://1win5519.ru]https://1win5519.ru[/url]
1win_kg_zlEr
23 Oct 25 at 7:29 am
Мебельная фабрика «Подольск» более 20 лет создаёт кухни на заказ — от лаконичной классики до современного МДФ с краской, пластиком и патиной. Точные замеры, собственное производство, проверенная фурнитура и доставка со сборкой превращают проект в комфортный опыт. В середине планирования интерьера просто откройте https://mf-podolsk.ru/ — выберите стиль, материалы и фасады, а конструкторы подготовят эскиз под ваши размеры. Эргономично, доступно и честно по срокам.
vixenglisp
23 Oct 25 at 7:31 am
1xbet ?yelik [url=http://www.1xbet-giris-4.com]http://www.1xbet-giris-4.com[/url] .
1xbet giris_riSa
23 Oct 25 at 7:34 am
бонусный счет ван вин [url=https://1win5518.ru]https://1win5518.ru[/url]
1win_kg_fekl
23 Oct 25 at 7:38 am
Этот подход имеет несколько ключевых преимуществ, которые обеспечивают комфорт, безопасность и эффективность лечения.
Подробнее можно узнать тут – http://narcolog-na-dom-moskva55.ru
Bretttah
23 Oct 25 at 7:39 am
Great beat ! I wish to apprentice at the same time as you amend your website,
how could i subscribe for a blog website? The account helped
me a acceptable deal. I were a little bit acquainted of this your broadcast
provided vibrant transparent concept
folie für arbeitsplatte
23 Oct 25 at 7:40 am
Operation Game Canada: A classic, fun-filled board game where players test their precision by removing ailments from the patient without triggering the buzzer: official Operation game site
GabrielLyday
23 Oct 25 at 7:41 am
You’ve made some decent points there. I looked on the net for
more information about the issue and found most people will go along with your views on this website.
32win top
23 Oct 25 at 7:43 am
1xbet com giri? [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .
1xbet giris_cxSa
23 Oct 25 at 7:44 am
Hi, i think that i saw you visited my web site so i came to “return the
favor”.I’m trying to find things to enhance my
site!I suppose its ok to use some of your ideas!!
Lueur Fluxor Avis
23 Oct 25 at 7:45 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Посмотреть всё – https://ccmdaci.org/irfmda
Frankcox
23 Oct 25 at 7:46 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Ознакомиться с теоретической базой – https://nclunlimited.com/la-liberte
Davidnam
23 Oct 25 at 7:47 am
http://www.lenotoplenie.ru подробная информация о регистрации и бонусных кодах
Aaronawads
23 Oct 25 at 7:48 am
1xbet guncel [url=https://www.1xbet-giris-1.com]https://www.1xbet-giris-1.com[/url] .
1xbet giris_bekt
23 Oct 25 at 7:50 am
SanteHommeFrance: Viagra homme prix en pharmacie – Viagra sans ordonnance avis
AnthonySep
23 Oct 25 at 7:50 am
I’m now not positive where you are getting your info, but good topic.
I must spend a while studying much more or working out more.
Thank you for fantastic info I was on the lookout for this
info for my mission.
kra36 сс
23 Oct 25 at 7:51 am
OMT’s recorded sessions аllow trainees tɑke another look at
motivating explanations anytime, deepening tһeir love for
mathematics ɑnd fueling their aspiration for exam accomplishments.
Discover tһe convenience of 24/7 online math tuition ɑt OMT, where engaging resources mɑke discovering enjoyable and effective for ɑll levels.
Singapore’ѕ focus оn vital thinking tһrough mathematics highlights tһе valᥙe of math tuition, ѡhich
assists students establish thе analytical skills required ƅy thе country’s forward-thinking curriculum.
Tuition іn primary school math іs crucial foг PSLE preparation,
as it prеsents sophisticated techniques fօr dealing ᴡith non-routine issues tһat stump numerous
candidates.
Structure confidence via regular tuition assistance is crucial, as O Levels can Ƅe
stressful, and positive students perform mսch
better under stress.
Inevitably, junior college math tuition іѕ vital tߋ safeguarding toρ A Level resuⅼtѕ, opening up doors to prestigious scholarships аnd college chances.
Eventually, OMT’ѕ distinct proprietary curriculum
enhances tһe Singapore MOE curriculum Ьy fostering independent thinkers furnished fօr ⅼong-lasting mathematical success.
OMT’ѕ online math tuition ⅼets you chɑnge at your very own rate lah, sо say ցoodbye to rushing
and your mathematics qualities ԝill skyrocket progressively.
Tuition promotes independent analytical, ɑ skill very valued in Singapore’s application-based mathematics exams.
my web blog: h1 math tuition singapore – paintingsofdecay.net –
paintingsofdecay.net
23 Oct 25 at 7:52 am
рейтинг seo студий [url=www.reiting-seo-kompaniy.ru/]рейтинг seo студий[/url] .
reiting seo kompanii_aoon
23 Oct 25 at 7:52 am
Приветственные бонусы также варьируются по виду. Определённые акции предлагаются новым клиентам. При регистрации на 1xBet, используйте промокод и оформите удвоенный стартовый бонус в размере 32500 рублей.Компания 1xBet даёт возможность пользователям ставить и выигрывать с использованием акционных предложений. Это повышает интерес к ставкам и гарантирует надежность игры.Действующий код 1xBet можно получить на странице регистрации: промокод на 1xbet зеркало.
WilliamFaw
23 Oct 25 at 7:53 am