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!
Uk Meds Guide: Uk Meds Guide – safe place to order meds UK
HaroldSHems
2 Nov 25 at 3:58 pm
купить диплом о высшем образовании с занесением в реестр владивосток [url=https://frei-diplom4.ru/]https://frei-diplom4.ru/[/url] .
Diplomi_ujOl
2 Nov 25 at 4:00 pm
Hi, all is going perfectly here and ofcourse every one is sharing
data, that’s in fact fine, keep up writing.
đặt hoa viếng đám tang
2 Nov 25 at 4:01 pm
I absolutely love your blog and find many of your post’s to be just what I’m looking for.
Would you offer guest writers to write content for yourself?
I wouldn’t mind composing a post or elaborating
on many of the subjects you write regarding here. Again, awesome website!
Professional Translation Services Registered in London
2 Nov 25 at 4:01 pm
Undeniably believe that which you stated. Your favorite justification appeared to be on the
net the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they just don’t know
about. You managed to hit the nail upon the top and defined out the
whole thing without having side-effects , people can take a signal.
Will likely be back to get more. Thanks
بهترین دستگاه اکسیژن ساز نی نی سایت
2 Nov 25 at 4:02 pm
купить дипломы о высшем с занесением [url=http://www.rudik-diplom6.ru]купить дипломы о высшем с занесением[/url] .
Diplomi_wsKr
2 Nov 25 at 4:03 pm
сео продвижение компания [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение компания[/url] .
agentstvo poiskovogo prodvijeniya_mvKt
2 Nov 25 at 4:06 pm
I savor, result in I discovered just what I used to be having a look for.
You’ve ended my four day long hunt! God
Bless you man. Have a nice day. Bye
Also visit my webpage … балансировка карданного вала
балансировка карданного вала
2 Nov 25 at 4:06 pm
I’m gone to say to my little brother, that he should also pay
a quick visit this weblog on regular basis to get updated
from hottest news.
مشاوره رایگان سئو سایت
2 Nov 25 at 4:07 pm
online pharmacy: irishpharmafinder – irishpharmafinder
HaroldSHems
2 Nov 25 at 4:09 pm
купить аттестат [url=www.rudik-diplom6.ru]купить аттестат[/url] .
Diplomi_zmKr
2 Nov 25 at 4:11 pm
купить украинский диплом техникума [url=www.frei-diplom12.ru/]купить украинский диплом техникума[/url] .
Diplomi_cdPt
2 Nov 25 at 4:12 pm
1xbet g?ncel adres [url=https://1xbet-giris-5.com/]1xbet g?ncel adres[/url] .
1xbet giris_xiSa
2 Nov 25 at 4:16 pm
https://yurhelp.in.ua/
SteveWex
2 Nov 25 at 4:17 pm
This article will help the internet viewers for setting up new web site or even a blog from start to end.
uu88.com
2 Nov 25 at 4:18 pm
seo продвижение сайта агентство [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo продвижение сайта агентство[/url] .
agentstvo poiskovogo prodvijeniya_joKt
2 Nov 25 at 4:19 pm
What we’re covering
[url=https://megaweb-15at.com]mgmarket 5at[/url]
• Israel is facing growing condemnation after it attacked Hamas leadership in the capital of Qatar, a US ally and key mediator in Gaza ceasefire talks — putting hostage negotiations at risk.
[url=https://mega-sb.net]mgmarket4 at[/url]
• Hamas said the strike killed five members but failed to assassinate the negotiating delegation, the target of the strikes.
• US President Donald Trump has criticized the strike, saying that by the time his administration learned of the attack and told the Qataris, there was little he could do to stop it.
• The attack is the first publicly acknowledged strike on a Gulf state by Israel. Qatar’s prime minister was visibly angry and said his country’s tradition of diplomacy “won’t be deterred.”
https://megaweb-7at.com
mgmarket 6at
JamesBus
2 Nov 25 at 4:19 pm
Я уверен, что Вы заблуждаетесь.
Set up alerts that you want raise (trading signals, balance updates, etc.). Easy replenishment and withdrawal of winnings: Secure management of funds through plastic cards, electronic wallets or cryptocurrencies, [url=https://web-pocketoption.com/]web-pocketoption.com[/url] without commissions.
ElizabethRon
2 Nov 25 at 4:20 pm
Piece of writing writing is also a excitement, if
you be familiar with then you can write or else it is complicated
to write.
سایت طراحی لباس فوتبال با هوش مصنوعی رایگان
2 Nov 25 at 4:20 pm
bahis sitesi 1xbet [url=https://1xbet-giris-5.com]bahis sitesi 1xbet[/url] .
1xbet giris_nkSa
2 Nov 25 at 4:22 pm
купить диплом менеджера по туризму [url=https://rudik-diplom13.ru/]купить диплом менеджера по туризму[/url] .
Diplomi_mqon
2 Nov 25 at 4:22 pm
Не могу решить.
доставка здійснюється в понеділок, [url=https://sonechko.webboard.org/post116.html]https://sonechko.webboard.org/post116.html[/url] Середу і п’ятницю. Prague homemade kitchen-це смачна традиційна домашня їжа.
AliceLog
2 Nov 25 at 4:23 pm
Eski ama asla eskimeyen 90’lar modas?n?n guzellik s?rlar?yla dolu bu yaz?da bulusal?m.
Особенно понравился раздел про Evinizde Estetik ve Fonksiyonu Birlestirin: Ipuclar? ve Trendler.
Вот, делюсь ссылкой:
[url=https://anadolustil.com]https://anadolustil.com[/url]
Tarz?n?zda 90’lar?n esintilerini hissetmeye baslad?g?n?za eminim. Gecmisin izlerini tas?maktan korkmay?n!
Josephassof
2 Nov 25 at 4:24 pm
глядишь к новому году договоримся, а там и к 2020 посылка придет… https://priv-church.ru/ahtubinsk.html Ты в какой скайп то ломишься? перепроверь!!!
ThomasronsE
2 Nov 25 at 4:27 pm
Hello there! This is kind of off topic but I need some advice from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any ideas or suggestions? With thanks
https://nauttes.com/skachat-melbet-bukmekerskaya-na-android/
OLaneDrync
2 Nov 25 at 4:27 pm
«Мебельный базар» — это интернет-магазин и офлайн-салон на Каширском шоссе, где можно собрать интерьер от классики до лофта: спальни, кухни, гостиные, шкафы-купе по индивидуальным размерам, столы и стулья, мягкая мебель, матрасы. Регулярные акции, готовые комплекты и доставка по всей России делают обновление дома прозрачным по срокам и бюджету, а ассортимент российских и европейских фабрик позволяет точно попасть в стиль. Удобнее всего начать с витрины предложений и каталога на https://bazar-mebel.ru/ — и оформить заказ онлайн или в салоне.
mibacpsype
2 Nov 25 at 4:29 pm
https://apexsenterprises.com/1xbet-codigo-promocional-2026-e130-bono-para-registro/
jxfykct
2 Nov 25 at 4:31 pm
agency seo [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]agency seo[/url] .
agentstvo poiskovogo prodvijeniya_pqKt
2 Nov 25 at 4:31 pm
Increíble artículo sobre los juegos más populares de Pin-Up Casino en México.
Me sorprendió ver cómo títulos como Gates of Olympus y
Sweet Bonanza siguen dominando entre los jugadores mexicanos.
La información sobre los multiplicadores, rondas de bonificación y pagos en cascada fue muy
útil.
Recomiendo leer el artículo completo si quieres descubrir qué juegos están marcando tendencia en Pin Up Casino.
Se agradece ver una mezcla entre títulos nostálgicos y nuevas propuestas en el mercado mexicano de apuestas.
Puedes leer el artículo completo aquí y descubrir todos los detalles sobre los juegos más jugados en Pin Up México.
info
2 Nov 25 at 4:31 pm
I’m excited to uncover this web site. I need to to thank you
for ones time for this wonderful read!! I definitely savored every little bit of it and
i also have you book-marked to look at new information in your
blog.
situs123
2 Nov 25 at 4:32 pm
online pharmacy ireland: top-rated pharmacies in Ireland – irishpharmafinder
HaroldSHems
2 Nov 25 at 4:34 pm
best Irish pharmacy websites
Edmundexpon
2 Nov 25 at 4:35 pm
купить диплом в тюмени [url=http://rudik-diplom14.ru]купить диплом в тюмени[/url] .
Diplomi_gyea
2 Nov 25 at 4:37 pm
купить диплом в славянске-на-кубани [url=https://www.rudik-diplom13.ru]https://www.rudik-diplom13.ru[/url] .
Diplomi_uson
2 Nov 25 at 4:37 pm
legitimate pharmacy sites UK [url=https://ukmedsguide.com/#]UkMedsGuide[/url] online pharmacy
Hermanengam
2 Nov 25 at 4:39 pm
Курсы гитары с опытными педагогами — ваш путь от первых аккордов до уверенной игры на сцене. https://shkola-vocala.ru/shkola-igry-na-gitare.php
https://shkola-vocala.ru/shkola-igry-na-gitare.php
2 Nov 25 at 4:41 pm
discount pharmacies in Ireland
Edmundexpon
2 Nov 25 at 4:42 pm
1xbet giri? linki [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .
1xbet giris_qdSa
2 Nov 25 at 4:44 pm
Live Draw Hk Lotto
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
Live Draw Hk Lotto
2 Nov 25 at 4:44 pm
купить сертификат специалиста [url=https://rudik-diplom13.ru/]купить сертификат специалиста[/url] .
Diplomi_eqon
2 Nov 25 at 4:45 pm
купить диплом с занесением в реестр отзывы [url=https://frei-diplom4.ru/]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_ypOl
2 Nov 25 at 4:46 pm
купить свидетельство о рождении [url=https://rudik-diplom6.ru/]купить свидетельство о рождении[/url] .
Diplomi_ujKr
2 Nov 25 at 4:49 pm
1 xbet [url=https://1xbet-giris-5.com]https://1xbet-giris-5.com[/url] .
1xbet giris_jiSa
2 Nov 25 at 4:53 pm
I’m really enjoying the design and layout of your
blog. It’s a very easy on the eyes which makes it much more pleasant for
me to come here and visit more often. Did you
hire out a designer to create your theme?
Outstanding work!
kra3
2 Nov 25 at 4:55 pm
диплом колледжа 2016 купить [url=www.frei-diplom10.ru]www.frei-diplom10.ru[/url] .
Diplomi_beEa
2 Nov 25 at 4:56 pm
Hey hey, Singapore parents, math rеmains prоbably tһe extremely
impoгtant primary subject, promoting imagination fоr challenge-tackling f᧐r groundbreaking jobs.
Don’t mess ɑrⲟund lah, combine a good Junior College
ⲣlus maths superiority tο guarantee superior А
Levels scores aѕ wеll aѕ smooth cһanges.
Folks, worry about the difference hor, mathematics foundation гemains essential durіng Junior College tο grasping data, vital іn modern digital ѕystem.
Dunman Hіgh School Junior College stands оut in bilingual
education, mixing Eastern ɑnd Western viewpoints to cultivate culturally astute аnd ingenious thinkers.
Ƭhe integrated program οffers seamless development
ѡith enriched curricula in STEM аnd humanities, supported Ьy innovative
facilities ⅼike гesearch laboratories. Students grow іn a harmonious environment thаt highlights
creativity, leadership, and community involvement tһrough varied activities.
Worldwide immersion programs boost cross-cultural understanding аnd prepare trainees for global success.
Graduates consistently attain tοр outcomes, ѕhowing the school’ѕ dedication tօ academic rigor аnd personal excellence.
Catholic Junior College ߋffers a transformative educational
experience focused օn timeless worths ߋf compassion, stability,
ɑnd pursuit of fɑct, cultivating а close-knit neighborhood
where students feel supported аnd influenced to grow both intellectually and
spiritually іn a serene and inclusive setting.
The college supplies thorough academic programs in the liberal
arts, sciences, аnd solcial sciences, delivered Ьy passionate
and skilled mentors who utilize innovative mentor ɑpproaches tօ stimulate іnterest аnd
motivate deep, meaningful knowing tһаt extends faг bеyond
assessments. An vibrant selection of co-curricular activities, consisting оf competiitive sports teams tһat promote physical health
ɑnd camaraderie, as well as artistic societies tһаt support innovative expression tһrough
drama and visual arts, maкeѕ it possibⅼе for students tо explore their іnterests and establish ᴡell-rounded personalities.
Opportunities fοr siɡnificant neighborhood service,
ѕuch ɑs collaborations wіth regional charities and
worldwide humanitarian journeys, һelp develop empathy, management skills, аnd a
real dedication to makіng а difference іn the lives оf օthers.
Alumni from Catholic Junior College frequently emerge аѕ caring and
ethical leaders іn ѵarious professional
fields, equipped ѡith thе understanding, resilience,
and moral compass tο contribute favorably ɑnd sustainably tߋ society.
Folks, competitive approach activated lah, strong primary maths results in improved STEM grasp ρlus tech goals.
Ꭰo not tɑke lightly lah, pair a g᧐od
Junior College alongside mathematics excellence tо assure elevated Α Levels marks ɑnd seamless transitions.
Hey hey, Singapore moms аnd dads, math proves perһaps the extremely essential primary discipline, fostering creativity fоr ρroblem-solving tо innovative jobs.
Ⅾo not play play lah, combine ɑ excellent Junior College ѡith mathematics proficiency іn oгder to ensure elevated A Levels marks аnd effortless shifts.
Іn our kiasu society, Ꭺ-level distinctions mɑke you stand out in job
interviews eνen yеars later.
Oh no, primary math teaches practical applications ⅼike financial planning, thuѕ ensure ʏour kid grasps this properly Ƅeginning young age.
Also visit mу web blog; list of secondary school
list of secondary school
2 Nov 25 at 4:59 pm
qcxrmyy.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.
Gil Grewell
2 Nov 25 at 5:00 pm
1x giri? [url=https://1xbet-giris-5.com]https://1xbet-giris-5.com[/url] .
1xbet giris_zwSa
2 Nov 25 at 5:04 pm
seo agentura [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_puKt
2 Nov 25 at 5:06 pm
Курсы гитары с лучшими преподавателями — это гарантия качества и удовольствия от каждого урока. https://shkola-vocala.ru/shkola-igry-na-gitare.php
https://shkola-vocala.ru/shkola-igry-na-gitare.php
2 Nov 25 at 5:06 pm