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!
The $MTAUR token seems like a solid pick for anyone into casual gaming with crypto twists. Navigating mazes as a minotaur while earning in-game currency sounds addictive and rewarding. With the presale offering 80% off, it’s hard not to jump in early.
mtaur token
WilliamPargy
22 Oct 25 at 10:05 pm
Having read this I thought it was really informative.
I appreciate you spending some time and energy to put this information together.
I once again find myself spending a lot of time both reading and leaving comments.
But so what, it was still worthwhile!
backlink
22 Oct 25 at 10:06 pm
How to win in Calgary Lottery: Boost your chances by playing consistently, joining lottery pools, and choosing less popular combinations. Remember, winning requires luck and responsible play: win prizes in Calgary Alberta
GabrielLyday
22 Oct 25 at 10:08 pm
купить диплом машиниста [url=http://www.rudik-diplom7.ru]купить диплом машиниста[/url] .
Diplomi_fwPl
22 Oct 25 at 10:08 pm
J’ai une passion jazzy pour BassBet Casino, c’est une plateforme qui vibre comme un saxophone. La selection de jeux est melodieuse, proposant des jeux de table elegants. Amplifiant le plaisir de jeu. Le service est disponible 24/7, offrant des reponses claires. Les gains arrivent sans delai, de temps a autre des offres plus genereuses seraient jazzy. Au final, BassBet Casino est une plateforme qui groove pour ceux qui aiment parier en crypto ! En bonus le design est moderne et jazzy, facilite une immersion totale. A souligner les options de paris sportifs variees, renforce le sentiment de communaute.
bassbetcasinologinfr.com|
BassRhythmA1zef
22 Oct 25 at 10:08 pm
Госпитализация в стационаре «Частного Медика 24» позволяет стабилизировать состояние, снять интоксикацию и начать новую жизнь.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]нарколог вывод из запоя в стационаре[/url]
GeraldHom
22 Oct 25 at 10:09 pm
Je suis accro a Spinit Casino, on ressent une ambiance de livre. La selection de jeux est enchantee, avec des slots aux designs enchantes. Le bonus de bienvenue est magique. Le service est disponible 24/7, avec une aide precise. Les transactions sont fiables, parfois des recompenses additionnelles seraient narratives. Pour conclure, Spinit Casino offre une experience memorable pour les amateurs de sensations enchantees ! Par ailleurs l’interface est fluide comme un conte, ajoute une touche de mystere. A souligner le programme VIP avec des niveaux exclusifs, propose des avantages personnalises.
spinitcasinologinfr.com|
FortuneFableC4zef
22 Oct 25 at 10:11 pm
OMT’s taped sessions aⅼlow pupils review motivating explanations
anytime, deepening tһeir love fⲟr mathematics and fueling thеіr aspiration fοr exam triumphs.
Enlist tⲟday іn OMT’s standalone e-learning programs ɑnd enjoy your graces
skyrocket throuցh limitless access to tߋp quality, syllabus-aligned ϲontent.
In Singapore’ѕ strenuous education sʏstem, wheгe mathematics іs compulsory ɑnd taҝes in ɑround 1600 һοurs of curriculum time in primary
school ɑnd secondary schools, math tuition еnds uⲣ being imⲣortant to
assist trainees develop ɑ strong foundation forr lifelong
success.
Тhrough math tuition, trainees practice PSLE-style concerns typicallies ɑnd graphs, improving precision and speed under exam conditions.
Routine mock Ⲟ Level examinations іn tuition setups imitate genuine conditions, enabling traines tߋ refine tһeir technique and minimize errors.
Tuition integrates pure аnd ᥙsed mathematics seamlessly, preparing trainees fоr thе interdisciplinary nature ᧐f A
Level issues.
OMT sets іtself apart ᴡith a curriculum tһat improves
MOE curriculum ѵia collective on-line discussion forums f᧐r
going over exclusive math obstacles.
Adaptive tests readjust tо yoᥙr degree lah, challenging yⲟu simply right
tο steadily increase ʏour examination scores.
Ԝith mathematics bеing a core topic tһаt affects oᴠerall academic streaming, tuition assists
Singapore students secure fаr bеtter grades аnd brighter future
possibilities.
Feel free t᧐ visit mү webpage math tuition singapore
math tuition singapore
22 Oct 25 at 10:11 pm
диплом техникума с отличием купить [url=www.frei-diplom7.ru]диплом техникума с отличием купить[/url] .
Diplomi_ynei
22 Oct 25 at 10:11 pm
Если близкий человек в состоянии запоя, закажите нарколога на дом в Краснодаре от клиники «Детокс». Круглосуточно и конфиденциально.
Подробнее можно узнать тут – [url=https://narkolog-na-dom-krasnodar25.ru/]помощь нарколога на дому краснодар[/url]
AndrewENlit
22 Oct 25 at 10:13 pm
что такое медицинский перевод [url=http://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16]http://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .
Medicinskii perevod_gzEr
22 Oct 25 at 10:14 pm
Цікавитесь кулінарією? Завітайте на кулінарний блог MeatPortal – https://meatportal.com.ua/ Знайдіть нові рецепти, корисні поради починаючим і досвідченим кулінарам. Збирайте нові рецепти до своєї колекції, щоб смачно і корисно годувати сім’ю.
woruhrdOdora
22 Oct 25 at 10:14 pm
Технический перевод [url=www.dzen.ru/a/aPFFa3ZMdGVq1wVQ/]www.dzen.ru/a/aPFFa3ZMdGVq1wVQ/[/url] .
Tehnicheskii perevod_xkml
22 Oct 25 at 10:15 pm
купить диплом строителя [url=rudik-diplom7.ru]купить диплом строителя[/url] .
Diplomi_fzPl
22 Oct 25 at 10:17 pm
перевод медицинских терминов [url=https://teletype.in/@alexd78/HN462R01hzy]https://teletype.in/@alexd78/HN462R01hzy[/url] .
Vidi perevodov v buro Perevod i Pravo_eqst
22 Oct 25 at 10:17 pm
купить диплом в новом уренгое [url=https://www.rudik-diplom12.ru]https://www.rudik-diplom12.ru[/url] .
Diplomi_tkPi
22 Oct 25 at 10:18 pm
J’adore l’aura divine d’ Olympe Casino, ca offre un plaisir immortel. Le catalogue est riche en epopees, proposant des jeux de table glorieux. Amplifiant l’aventure de jeu. L’assistance est efficace et sage, avec une aide precise. Les retraits sont rapides comme un eclair de Zeus, cependant plus de promos regulieres ajouteraient de la gloire. En resume, Olympe Casino est un incontournable pour les joueurs pour ceux qui aiment parier en crypto ! Par ailleurs le site est rapide et glorieux, ajoute une touche de mythologie. Particulierement captivant les evenements communautaires engageants, assure des transactions fiables.
olympefr.com|
ZeusThunderA4zef
22 Oct 25 at 10:20 pm
wetten auf späte tore
Review my site; online sportwette
online sportwette
22 Oct 25 at 10:21 pm
discoveryourmoment.shop – The packaging was neat and delivery prompt—very low fuss shopping experience.
Elenore Creecy
22 Oct 25 at 10:22 pm
медицинский перевод на английский [url=http://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16]http://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .
Medicinskii perevod_rxEr
22 Oct 25 at 10:22 pm
Hello would you mind sharing which blog platform you’re working with?
I’m looking to start my own blog soon but I’m having a difficult
time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design seems different then most blogs and I’m looking for something completely
unique. P.S Apologies for being off-topic but I had
to ask!
cannabis
22 Oct 25 at 10:23 pm
купить vip диплом техникума ссср [url=frei-diplom7.ru]купить vip диплом техникума ссср[/url] .
Diplomi_xkei
22 Oct 25 at 10:23 pm
что такое технические перевод [url=https://www.dzen.ru/a/aPFFa3ZMdGVq1wVQ]https://www.dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_numl
22 Oct 25 at 10:23 pm
smartchoiceoutlet.shop – Friendly interface and responsive support, made me feel confident about buying.
Stevie Ballowe
22 Oct 25 at 10:27 pm
медицинский перевод справок [url=www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/[/url] .
Medicinskii perevod_gqEr
22 Oct 25 at 10:29 pm
что такое технические перевод [url=http://dzen.ru/a/aPFFa3ZMdGVq1wVQ]http://dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_tnml
22 Oct 25 at 10:30 pm
вопросы юридического перевода [url=http://teletype.in/@alexd78/HN462R01hzy]http://teletype.in/@alexd78/HN462R01hzy[/url] .
Vidi perevodov v buro Perevod i Pravo_ggst
22 Oct 25 at 10:30 pm
this says that user who makes bets as before has a chance to win, even when not any of his chosen [url=https://www.windowgallery.in/the-excitement-of-live-cricket-a-comprehensive-2.html]https://www.windowgallery.in/the-excitement-of-live-cricket-a-comprehensive-2.html[/url] they will be correct.
JonathanNeutt
22 Oct 25 at 10:34 pm
Для восстановления после запоя выбирайте стационар клиники «Детокс» в Сочи. Здесь пациентам обеспечивают качественную помощь и поддержку на каждом этапе.
Узнать больше – [url=https://vyvod-iz-zapoya-sochi22.ru/]вывод из запоя недорого сочи[/url]
Jamesdug
22 Oct 25 at 10:34 pm
Где купить Метадон в Заозёрном?Наткнулся на https://NewFinBiz.ru
– приличные отзывы и цены. Доставка работает. Кто-то пробовал их услугами? Насколько качественный товар?
Stevenref
22 Oct 25 at 10:37 pm
https://factava.com.ua/vidpovidy/v-ch-a-4638-de-znakhodytsia-vazhlyva-informatsiia-ta-adresa-viyskovoi-chastyny-v-ukraini/
JessieVinge
22 Oct 25 at 10:41 pm
Keep on writing, great job!
alternatif sor777
22 Oct 25 at 10:41 pm
особенности медицинского перевода [url=https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16]https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .
Medicinskii perevod_afEr
22 Oct 25 at 10:45 pm
тусишка хороша, я как го грешил что нирвановская была какая то тёмная, так вот у чемикала она вообще практически бежевая 😀 качество порадовало, хорошая вещь )
Онлайн магазин – купить мефедрон, кокаин, бошки
Заказал, оплатил, получил, Радуюсь… !:D Норм магаз приятно иметь дело..! !!
Thomasneump
22 Oct 25 at 10:45 pm
технический перевод особенности [url=dzen.ru/a/aPFFa3ZMdGVq1wVQ]dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_pfml
22 Oct 25 at 10:45 pm
pharmacie française agréée en ligne: SanteHommeFrance – pharmacie française agréée en ligne
AnthonySep
22 Oct 25 at 10:47 pm
В Нижнем Новгороде клиника «Частный Медик 24» предлагает вывод из запоя в стационаре с полным медицинским контролем и комфортом.
Получить больше информации – http://vyvod-iz-zapoya-v-stacionare21.ru
RichardHig
22 Oct 25 at 10:48 pm
Alas, famous establishments havе guidance programs, leading children ɑcross stress fοr improved emotional well-being and academics.
Oh, top schools deliver water sports, enhancing health fоr athletic management jobs.
Alas, ᴡithout strong math ɑt primary school, гegardless tⲟp establishment
children mіght falter ԝith secondary algebra, tһerefore build it promptly leh.
Guardians, worry аbout the difference hor, mathematics foundation гemains essential at primary school іn comprehending figures, essential ᴡithin today’s tech-driven market.
Αvoid take lightly lah, combine а good primary school
ⲣlus math proficiency to assure elevated PSLE scores
ρlus effortless transitions.
Folks, worry ɑbout the disparity hor, arithmetic groundwork proves essential
ԁuring primary school to understanding data, essential іn modern digital market.
Folks, competitive mode оn lah, robust primary mathematics leads іn improved scientific grasp ρlus construction goals.
Mayflower Primary School promotes ɑ favorable neighborhood encouraging scholastic
success.
Dedicated instructors assist support ѡell-rounded individuals.
Fern Green Primary School ߋffers nature-inspired knowing fⲟr young children.
With outdoor activities, іt promotes holistic advancement.
Ӏt’s ideal fоr parents desiring environment-friendly education.
mʏ blog post: Bukit Panjang Govt. Ꮋigh School (Chauncey)
Chauncey
22 Oct 25 at 10:49 pm
thebestplacetoshop.shop – User-friendly website, easy to navigate and find desired items.
Olen Menge
22 Oct 25 at 10:53 pm
I am truly grateful to the holder of this
website who has shared this great piece
of writing at here.
bokep hot
22 Oct 25 at 10:58 pm
медицинский перевод выписок [url=http://www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16]http://www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .
Medicinskii perevod_hvEr
22 Oct 25 at 11:02 pm
виды технического перевода [url=https://dzen.ru/a/aPFFa3ZMdGVq1wVQ]https://dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_bcml
22 Oct 25 at 11:03 pm
научно технический перевод английский [url=http://teletype.in/@alexd78/HN462R01hzy/]http://teletype.in/@alexd78/HN462R01hzy/[/url] .
Vidi perevodov v buro Perevod i Pravo_jyst
22 Oct 25 at 11:04 pm
бюро переводов Перевод и Право [url=teletype.in/@alexd78/HN462R01hzy]teletype.in/@alexd78/HN462R01hzy[/url] .
Vidi perevodov v buro Perevod i Pravo_abst
22 Oct 25 at 11:08 pm
В стационаре пациент получает и физиологическую помощь, и психологическое сопровождение, что важно для долгосрочного восстановления.
Получить больше информации – https://vyvod-iz-zapoya-v-stacionare-samara25.ru
GeraldHom
22 Oct 25 at 11:08 pm
online wetten schleswig holstein
My web site – Betsson Sportwetten Bonus
Betsson Sportwetten Bonus
22 Oct 25 at 11:15 pm
bestdealsforlife.click – Found some really solid deals here, made my day discovering them.
Kayla Biehn
22 Oct 25 at 11:17 pm
особенности медицинского перевода [url=https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/[/url] .
Medicinskii perevod_flEr
22 Oct 25 at 11:18 pm
Minotaurus coin’s 60% allocation fair. ICO’s roadmap clear. Play rewards real.
minotaurus coin
WilliamPargy
22 Oct 25 at 11:19 pm
технический перевод в нефтяной промышленности [url=https://dzen.ru/a/aPFFa3ZMdGVq1wVQ/]dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .
Tehnicheskii perevod_viml
22 Oct 25 at 11:19 pm