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://frei-diplom8.ru]диплом техникума проведенный купить[/url] .
Diplomi_gpsr
19 Oct 25 at 12:56 am
I every time emailed this weblog post page to all my friends, for
the reason that if like to read it next my friends will too.
نکات طلایی تبلیغات پزشکی با کمک شبکه های اجتماعی
19 Oct 25 at 12:57 am
диплом занесен в реестр купить [url=www.frei-diplom3.ru/]диплом занесен в реестр купить[/url] .
Diplomi_noKt
19 Oct 25 at 12:57 am
https://pilloleverdi.shop/# PilloleVerdi
MickeySum
19 Oct 25 at 12:57 am
With $MTAUR coin, collecting in-game currency while running mazes is addictive. Presale bonuses for vesting make holding appealing. Team’s track record impresses me.
minotaurus ico
WilliamPargy
19 Oct 25 at 12:58 am
купить диплом вуза занесением реестр [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_taOl
19 Oct 25 at 12:58 am
купить диплом в ялте [url=www.rudik-diplom1.ru]купить диплом в ялте[/url] .
Diplomi_maer
19 Oct 25 at 12:58 am
купить диплом в анжеро-судженске [url=rudik-diplom10.ru]rudik-diplom10.ru[/url] .
Diplomi_yuSa
19 Oct 25 at 12:58 am
перепланировка помещений [url=https://soglasovanie-pereplanirovki-kvartiry3.ru]https://soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _omPi
19 Oct 25 at 12:58 am
Spinrise
Angelolix
19 Oct 25 at 12:59 am
Intimi Santé [url=https://intimisante.com/#]IntimiSanté[/url] cialis prix
GeorgeHot
19 Oct 25 at 1:00 am
купить диплом в октябрьском [url=www.rudik-diplom4.ru]купить диплом в октябрьском[/url] .
Diplomi_ppOr
19 Oct 25 at 1:00 am
бонус в мелбет [url=https://melbetbonusy.ru]бонус в мелбет[/url] .
melbet_gwOi
19 Oct 25 at 1:00 am
перепланировка квартиры цена [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_tiet
19 Oct 25 at 1:00 am
услуги по узакониванию перепланировки [url=http://soglasovanie-pereplanirovki-kvartiry11.ru]http://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _kkMi
19 Oct 25 at 1:00 am
проект перепланировки квартиры для согласования цена [url=http://proekt-pereplanirovki-kvartiry17.ru/]http://proekt-pereplanirovki-kvartiry17.ru/[/url] .
proekt pereplanirovki kvartiri_jhml
19 Oct 25 at 1:01 am
Spinrise Casino
Angelolix
19 Oct 25 at 1:02 am
купить диплом в нижним тагиле [url=www.rudik-diplom13.ru/]купить диплом в нижним тагиле[/url] .
Diplomi_inon
19 Oct 25 at 1:02 am
перепланировки квартир [url=https://www.soglasovanie-pereplanirovki-kvartiry14.ru]https://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _fyEl
19 Oct 25 at 1:03 am
прогноз на хоккей на сегодня [url=https://prognozy-na-khokkej4.ru/]прогноз на хоккей на сегодня[/url] .
prognozi na hokkei_hnOl
19 Oct 25 at 1:04 am
перепланировка и согласование [url=https://soglasovanie-pereplanirovki-kvartiry4.ru]https://soglasovanie-pereplanirovki-kvartiry4.ru[/url] .
soglasovanie pereplanirovki kvartiri _oyOr
19 Oct 25 at 1:04 am
купить диплом в усть-илимске [url=www.rudik-diplom1.ru/]www.rudik-diplom1.ru/[/url] .
Diplomi_pter
19 Oct 25 at 1:05 am
проект по перепланировке квартиры цена [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_awPt
19 Oct 25 at 1:06 am
Secondary school math tuition іs vital foг Secondary 1students, helping tһem integrate technology іn math learning.
Steady lah, Singapore’ѕ math ranking at the tⲟр globally, no joke
one!
Fօr moms and dads, development fuel ԝith Singapore math
tuition’ѕ enthusiasm. Secondary math tuition іnterest sparks.
Ꭲhrough secondary 1 math tuition, clearness algebraic.
Selecting tһe rіght secondary 2 math tuition ϲan maҝе all the difference in a student’s
journey. Secondary 2 math tuition programs оften consist of mock exams tօ imitate test conditions.
Ᏼy strengthening principles like indices and surds, secondary 2 math tuition builds ɑ solid base.
Families worth secondary 2 math tuition ffor іts function in cultivating independent students.
Performing ѕtrongly inn secondary 3 math exams іѕ vital, as thіs stage is the final buildup bеfore O-Levels,ԝһere
spaces ⅽan be pricey. It enables trainees t᧐ trү out rеsearch study methods that wіll settle іn the һigh-stakes finals.
Ιn Singapore, ѕuch outcomes aгe often a predictor of post-secondary
pathways ⅼike polytechnics օr JCs.
Singapore’s ѕystem enhances secondary 4 exams smartly.
Secondary 4 math tuition algorithms adapt. Ƭhis knowing boosts
Ⲟ-Level. Secondary 4 math tuition smarts.
Exams build proficiency, ʏet mathematics іѕ a fundamental skill in thе
ᎪI surge, facilitating crop yield predictions.
Τo thrive in mathematics, love іt and learn tо use math
principles in dzily real w᧐rld.
Students preparing in Singapore can improve their speed-accuracy balance ᴠia pаst papers from multiple secondary schools.
Online math tuition e-learning in Singapore contributes t᧐ Ƅetter performance tһrough subscription models fߋr unlimited access.
Yߋu knoᴡ ah, don’t worry ѕia, secondary school life balanced, ⅼet your kid enjoy
ԝithout pressure.
Project-based learning ɑt OMT transforms mathematics іnto
hands-on fun, triggering enthusiasm іn Singapore pupjls
fοr impressive test rеsults.
Dive intߋ self-paced mathematics proficiency ԝith OMT’s
12-month е-learning courses, tߋtal wіtһ practice worksheets аnd taped sessions for
comprehensive modification.
Тhe holistic Singapore Math technique, ᴡhich constructs multilayered analytical abilities,
underscores ԝhy math tuition іѕ indispensable fⲟr masterng the curriculum and preparing
fⲟr future professions.
Ꮃith PSLE mathematics contributing considerably t᧐
general scores, tuition supplies extra resources ⅼike
design responses fⲟr pattern acknowledgment ɑnd algebraic thinking.
Connecting math concepts tߋ real-world situations witһ tuition strengthens understanding, mɑking O
Level application-based concerns mᥙch morе friendly.
Planning for the unpredictability οf A Level questions, tuition develops
flexible pгoblem-solving techniques for real-time test scenarios.
OMT’ѕ exclusive mathematics program matches MOE standards Ьy emphasizing theoretical proficiency օνeг roe discovering, causing mսch deeper long-lasting retention.
The self-paced e-learning syѕtem from OMT is super versatile lor, mаking it ⅼess conplicated to juggle school
and tuition fоr һigher mathematics marks.
Inevitably, math tuition іn Singapore transforms poѕsible right into
success, guaranteeing trainees not јust pass bսt master their mathematics tests.
Feel free to visit my webpage … Parents Looking For Tutors In Singapore
Parents Looking For Tutors In Singapore
19 Oct 25 at 1:06 am
оборудование для клиник [url=www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/]www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/[/url] .
oborydovanie medicinskoe_haOn
19 Oct 25 at 1:06 am
купить диплом с занесением в реестр самара [url=https://www.frei-diplom6.ru]https://www.frei-diplom6.ru[/url] .
Diplomi_nkOl
19 Oct 25 at 1:06 am
Thanks for your personal marvelous posting! I truly enjoyed reading it,
you can be a great author.I will ensure that I bookmark your blog and
will eventually come back someday. I want to
encourage one to continue your great writing, have a nice morning!
togel online
19 Oct 25 at 1:07 am
как купить диплом в колледже [url=https://www.frei-diplom8.ru]как купить диплом в колледже[/url] .
Diplomi_hhsr
19 Oct 25 at 1:07 am
екатеринбург купить диплом в реестр [url=http://www.frei-diplom5.ru]екатеринбург купить диплом в реестр[/url] .
Diplomi_jgPa
19 Oct 25 at 1:08 am
The Minotaurus presale raffle has me buzzing—$100K chance. $MTAUR’s utility real. Maze runner vibe addictive.
minotaurus ico
WilliamPargy
19 Oct 25 at 1:08 am
купить диплом пту в реестре [url=http://www.frei-diplom4.ru]купить диплом пту в реестре[/url] .
Diplomi_hsOl
19 Oct 25 at 1:09 am
купить диплом в белгороде [url=www.rudik-diplom5.ru/]купить диплом в белгороде[/url] .
Diplomi_yoma
19 Oct 25 at 1:09 am
farmacia online italiana Cialis [url=https://pilloleverdi.com/#]farmacia online italiana Cialis[/url] cialis generico
GeorgeHot
19 Oct 25 at 1:09 am
https://www.rwaq.org/users/gdw1p5e16m-20250722110058
Anthonycam
19 Oct 25 at 1:09 am
букмекерская контора мелбет [url=http://melbetbonusy.ru]букмекерская контора мелбет[/url] .
melbet_czOi
19 Oct 25 at 1:10 am
купить диплом в благовещенске [url=https://www.rudik-diplom1.ru]купить диплом в благовещенске[/url] .
Diplomi_fber
19 Oct 25 at 1:10 am
куплю диплом кандидата наук [url=www.rudik-diplom11.ru]куплю диплом кандидата наук[/url] .
Diplomi_tkMi
19 Oct 25 at 1:11 am
Восстановление после запоя в владимире требует комплексного подхода. Врач нарколог на дом владимир предоставляет услуги, включая лечение запоя и медицинскую реабилитацию. Персонализированный подход к лечению и помощь врача нарколога способствуют пониманию психологии зависимостей. Семейная поддержка играет важную роль в предотвращении рецидивов. Центр реабилитации в владимире предоставляет программы восстановления, включая лечение алкоголизма в анонимном форматечто способствует повышению качества жизни и психологическому комфорту.
lechenievladimirNeT
19 Oct 25 at 1:12 am
согласование перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _msEl
19 Oct 25 at 1:13 am
узаконить перепланировку стоимость [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru]http://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_deet
19 Oct 25 at 1:14 am
Если вы ищете надежную клинику для вывода из запоя, обратитесь в «Детокс» в Краснодаре. Услуга вызова нарколога на дом доступна круглосуточно. Врачи приедут к вам в течение 1–2 часов и окажут необходимую помощь.
Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnodar29.ru/]нарколог на дом круглосуточно цены[/url]
StevenPrabY
19 Oct 25 at 1:14 am
купить диплом в усть-илимске [url=www.rudik-diplom8.ru/]www.rudik-diplom8.ru/[/url] .
Diplomi_hqMt
19 Oct 25 at 1:14 am
купить диплом об образовании с занесением в реестр [url=http://frei-diplom6.ru]купить диплом об образовании с занесением в реестр[/url] .
Diplomi_fvOl
19 Oct 25 at 1:14 am
перепланировка офиса согласование [url=soglasovanie-pereplanirovki-kvartiry3.ru]soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _qtPi
19 Oct 25 at 1:15 am
перепланировка [url=soglasovanie-pereplanirovki-kvartiry14.ru]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _edEl
19 Oct 25 at 1:15 am
ABDreams is a premier site for ABDL content, creating immersive age regression stories that frequently include spanking as a core element of the disciplinary experience. [url=https://ataspanking.com/category/abdreams/]ABDreams Spanking video[/url]
Danielbuh
19 Oct 25 at 1:16 am
перепланировка квартиры цена оформления москва [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_liPt
19 Oct 25 at 1:16 am
купить диплом с реестром [url=http://rudik-diplom3.ru/]купить диплом с реестром[/url] .
Diplomi_woei
19 Oct 25 at 1:16 am
согласованте [url=www.soglasovanie-pereplanirovki-kvartiry3.ru/]www.soglasovanie-pereplanirovki-kvartiry3.ru/[/url] .
soglasovanie pereplanirovki kvartiri _rjPi
19 Oct 25 at 1:17 am
купить диплом в туле [url=http://rudik-diplom4.ru/]купить диплом в туле[/url] .
Diplomi_rcOr
19 Oct 25 at 1:19 am