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!
https://kvkrasnodar.ru
HowardGoony
6 Oct 25 at 11:52 pm
купить диплом специалиста [url=http://rudik-diplom14.ru]купить диплом специалиста[/url] .
Diplomi_koea
6 Oct 25 at 11:52 pm
изготовление кухни на заказ в спб [url=kuhni-spb-4.ru]изготовление кухни на заказ в спб[/url] .
kyhni spb_vqer
6 Oct 25 at 11:52 pm
диплом техникума торгового купить [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_lzea
6 Oct 25 at 11:53 pm
купить диплом в альметьевске [url=https://www.rudik-diplom4.ru]купить диплом в альметьевске[/url] .
Diplomi_ggOr
6 Oct 25 at 11:53 pm
Good article! We are linking to this particularly great content on our site.
Keep up the good writing.
Buy Adderall Without Prescription
6 Oct 25 at 11:54 pm
купить диплом в керчи [url=https://rudik-diplom12.ru/]https://rudik-diplom12.ru/[/url] .
Diplomi_ctPi
6 Oct 25 at 11:55 pm
кухни от производителя спб недорого и качественно [url=https://www.kuhni-spb-4.ru]https://www.kuhni-spb-4.ru[/url] .
kyhni spb_yser
6 Oct 25 at 11:56 pm
купить диплом маляра [url=https://rudik-diplom3.ru]купить диплом маляра[/url] .
Diplomi_irei
6 Oct 25 at 11:57 pm
кухни спб [url=https://kuhni-spb-4.ru/]кухни спб[/url] .
kyhni spb_eoer
6 Oct 25 at 11:58 pm
It’s an amazing paragraph designed for all the online users; they will take advantage from it
I am sure.
buôn bán nội tạng
6 Oct 25 at 11:58 pm
80hg88.cc – Really cool site, I like how the pages flow smoothly when navigating.
Mozella Bonillo
7 Oct 25 at 12:00 am
https://clomicareusa.shop/# buy clomid
DavidThink
7 Oct 25 at 12:01 am
Someone essentially assist to make significantly articles I might state.
That is the very first time I frequented your
web page and up to now? I surprised with the research you made to make this actual put up extraordinary.
Fantastic job!
Aviator Predictor APK
7 Oct 25 at 12:01 am
купить диплом техникума или колледжа [url=www.frei-diplom10.ru]www.frei-diplom10.ru[/url] .
Diplomi_xjEa
7 Oct 25 at 12:02 am
OMT’ѕ exclusive analytic stratyegies mɑke tackling challenging concerns гeally feel
lіke a game, assisting trainees develop ɑ real love fοr mathematics аnd ideas to shine іn exams.
Change mathematics challenges into accomplishments ѡith OMT Math
Tuition’ѕ blend օf online ɑnd ߋn-site options,
Ьacked by a performance history οf student quality.
Consіdered tһat mathematics plays а critical role іn Singapore’ѕ financial advancement ɑnd development, investing іn specialized math tuition gears
ᥙp students ԝith the problem-solving abilities neeⅾed to grow in a competitive landscape.
Ꮃith PSLE math evolving tο include more interdisciplinary elements, tuition keeps trainees upgraded ⲟn incorporated concerns mixing mathematics ԝith science contexts.
Math tuition teaches effective tіme management techniques, aiding
secondary pupils ⅽomplete Օ Level exams witһin the assigned period wіthout
hurrying.
Junior college math tuition promotes crucial believing abilities required tⲟ address non-routine
ⲣroblems that оften sһow up in A Level mathematics analyses.
Τhe originality of OMT exists in itѕ custom-made educational program tһat links
MOE syllabus voids ᴡith supplementary resources ⅼike
exclusive worksheets ɑnd options.
OMT’s online tuition conserves cash oon transportation lah, enabling mߋre concentrate on studies and improved math
outcomes.
Ԝith progressing MOE guidelines, math tuition maintains Singapore pupils upgraded οn syllabus adjustments for examination preparedness.
Аlso visit my web-site – a level maths tuition near me
a level maths tuition near me
7 Oct 25 at 12:02 am
купить диплом тренера [url=https://rudik-diplom5.ru/]купить диплом тренера[/url] .
Diplomi_hvma
7 Oct 25 at 12:02 am
That is a very good tip especially to those new to the blogosphere.
Simple but very accurate information…
Many thanks for sharing this one. A must read article!
emergency water damage restoration
7 Oct 25 at 12:03 am
Купить диплом техникума в Винница [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_kcea
7 Oct 25 at 12:03 am
купить диплом в рязани [url=http://www.rudik-diplom4.ru]купить диплом в рязани[/url] .
Diplomi_rdOr
7 Oct 25 at 12:03 am
купить диплом в великих луках [url=www.rudik-diplom14.ru]купить диплом в великих луках[/url] .
Diplomi_ioea
7 Oct 25 at 12:03 am
The Minotaurus presale vesting program is a game-changer for early birds. Extend for bonuses and avoid FOMO on post-TGE pumps. $MTAUR could be the dark horse in blockchain games.
minotaurus presale
WilliamPargy
7 Oct 25 at 12:04 am
купить диплом в ялте [url=www.rudik-diplom3.ru]купить диплом в ялте[/url] .
Diplomi_moei
7 Oct 25 at 12:05 am
купить диплом о средне специальном образовании реестр [url=http://frei-diplom4.ru/]купить диплом о средне специальном образовании реестр[/url] .
Diplomi_qtOl
7 Oct 25 at 12:06 am
купить диплом зарегистрированный в реестре [url=https://frei-diplom6.ru]https://frei-diplom6.ru[/url] .
Diplomi_ddOl
7 Oct 25 at 12:06 am
OMT’s community discussion forums ɑllow peer motivation, ԝһere
shared mathematics insights spark love аnd collective drive fоr examination excellence.
Discover the convenience οf 24/7 online math tuition at OMT, wheгe appealing resources mɑke learning enjoyable ɑnd reliable for аll levels.
Singapore’ѕ wߋrld-renowned mathematics curriculum highlights conceptual understanding օνeг simple calculation, mаking math
tuition important for students to grasp deep concepts аnd excel in national exams
like PSLE ɑnd О-Levels.
Ϝor PSLE achievers, tuition оffers mock tests аnd feedback,
helping fine-tune responses for maximum marks in bօtһ multiple-choice
and opеn-endeԁ areas.
With the O Level mathematics syllabus periodically advancing, tuition қeeps pupils
upgraded on сhanges, ensuring tһey are
welⅼ-prepared for existing layouts.
Junior college math tuition іѕ critical for A Degrees as it deepens understanding
ⲟf sophisticated calculus subjects ⅼike assimilation strategies аnd differential equations, whіch are main to the exam syllabus.
OMT’ѕ proprietary educational program boosts MOE requirements ѵia аn alternative strategy that nurtures both academic abilities аnd a passion for mathematics.
OMT’s online ѕystem matches MOE syllabus ⲟne, assisting you takе on PSLE math ԝith convenience and much bеtter scores.
Math tuition ցrows perseverance, assisting Singapore trainees tackle marathon test sessions ԝith continual focus.
Feel free tо surf to my blog … jc maths tuition bishan
jc maths tuition bishan
7 Oct 25 at 12:07 am
кухни в спб на заказ [url=https://kuhni-spb-4.ru/]https://kuhni-spb-4.ru/[/url] .
kyhni spb_kger
7 Oct 25 at 12:08 am
Госпитализация в стационар помогает быстрее и надежнее справиться с последствиями запоя.
Разобраться лучше – [url=https://vyvod-iz-zapoya-v-stacionare22.ru/]быстрый вывод из запоя в стационаре в нижний новгороде[/url]
Nathangeash
7 Oct 25 at 12:08 am
Keep on writing, great job!
Shisha điện tử lậu
7 Oct 25 at 12:09 am
куплю диплом кандидата наук [url=www.rudik-diplom5.ru/]куплю диплом кандидата наук[/url] .
Diplomi_xtma
7 Oct 25 at 12:10 am
купить диплом врача с занесением в реестр [url=http://frei-diplom4.ru/]купить диплом врача с занесением в реестр[/url] .
Diplomi_ukOl
7 Oct 25 at 12:13 am
qyrhjd.top – The tone is casual but still informative, good balance.
Devon Wettach
7 Oct 25 at 12:13 am
Если нужно вывести из запоя, в Екатеринбурге можно вызвать специалистов Stop-Alko на дом.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]вывод из запоя на дому круглосуточно екатеринбург[/url]
Alfredoneisy
7 Oct 25 at 12:13 am
Клиника «Детокс» в Сочи проводит вывод из запоя в стационаре. Все процедуры проходят под наблюдением квалифицированного персонала и с полным медицинским сопровождением.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-sochi23.ru/]вывод из запоя с выездом[/url]
RandySed
7 Oct 25 at 12:13 am
купить диплом специалиста [url=http://rudik-diplom15.ru]купить диплом специалиста[/url] .
Diplomi_vnPi
7 Oct 25 at 12:14 am
кухни спб [url=http://kuhni-spb-4.ru/]кухни спб[/url] .
kyhni spb_uoer
7 Oct 25 at 12:14 am
купить диплом энергетика [url=http://rudik-diplom5.ru/]купить диплом энергетика[/url] .
Diplomi_gtma
7 Oct 25 at 12:15 am
https://kcsodoverie.ru
HowardGoony
7 Oct 25 at 12:18 am
купить диплом пту в реестре [url=http://frei-diplom4.ru]купить диплом пту в реестре[/url] .
Diplomi_kiOl
7 Oct 25 at 12:18 am
кухни на заказ питер [url=http://kuhni-spb-4.ru/]кухни на заказ питер[/url] .
kyhni spb_ucer
7 Oct 25 at 12:18 am
купить официальный диплом с занесением в реестр [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_ulOl
7 Oct 25 at 12:20 am
спортивные новости сегодня [url=https://novosti-sporta-7.ru/]novosti-sporta-7.ru[/url] .
novosti sporta_ipOt
7 Oct 25 at 12:20 am
купить диплом в елабуге [url=http://www.rudik-diplom6.ru]http://www.rudik-diplom6.ru[/url] .
Diplomi_lqKr
7 Oct 25 at 12:20 am
кухни на заказ спб [url=http://www.kuhni-spb-4.ru]кухни на заказ спб[/url] .
kyhni spb_xher
7 Oct 25 at 12:20 am
«Частный Медик 24» в стационаре помогает начать жизнь заново — с чистого листа, без последствий запоя.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]вывод из запоя в стационаре анонимно в нижний новгороде[/url]
TimothyWic
7 Oct 25 at 12:21 am
best casino bonus new zealand, australian roulette rules and australian casino
chips, or blackjack cosh uk
My web site … goplayslots.net
goplayslots.net
7 Oct 25 at 12:21 am
вывод из запоя круглосуточно калуга
vivod-iz-zapoya-kaluga013.ru
вывод из запоя
narkologiyakalugaNeT
7 Oct 25 at 12:22 am
Вызов нарколога на дом в Краснодаре доступен в любое время суток. Клиника «Детокс» гарантирует профессиональную помощь.
Детальнее – [url=https://narkolog-na-dom-krasnodar27.ru/]нарколог на дом вывод из запоя[/url]
Charlesshofe
7 Oct 25 at 12:23 am
Врачи «Частного Медика?24» контролируют состояние организма и предотвращают осложнения при выводе из запоя.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре анонимно[/url]
JosephZek
7 Oct 25 at 12:25 am
https://amoxdirectusa.shop/# Amoxicillin 500mg buy online
DavidThink
7 Oct 25 at 12:30 am