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!
reinspiregreece – I’ll return often, this feels like a space filled with inspiration and beauty.
Sharilyn Neumaier
3 Oct 25 at 5:44 am
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
Jeromeliz
3 Oct 25 at 5:46 am
DragonMoney – онлайн-казино с лицензией, предлагает выгодные бонусы, разнообразные игры от ведущих провайдеров, мгновенные выплаты и круглосуточную поддержку
драгон мани
Richardusags
3 Oct 25 at 5:47 am
«Комфорт-Сервис» в Орле специализируется на уничтожении насекомых холодным туманом по авторской запатентованной технологии, заявляя отсутствие необходимости повторной обработки через две недели. На http://www.xn—57-fddotkqrbwclei3a.xn--p1ai/ подробно описано оборудование итальянского класса, перечень вредителей, регламент работ и требования безопасности; используются препараты Bayer, BASF, FMC с нейтральным запахом. Понравилась прозрачность: время экспозиции и проветривания, конфиденциальный выезд без маркировки, сервисное обслуживание и разъяснения по гарантиям.
belaftcam
3 Oct 25 at 5:47 am
Wow! This blog looks exactly like my old one! It’s on a totally different topic but it has pretty much
the same page layout and design. Outstanding choice of colors!
Interior Decorating Courses
3 Oct 25 at 5:48 am
новости олимпиады [url=http://www.novosti-sporta-16.ru]http://www.novosti-sporta-16.ru[/url] .
novosti sporta_ossi
3 Oct 25 at 5:50 am
прогнозы на сегодня футбол [url=http://prognozy-na-futbol-9.ru/]http://prognozy-na-futbol-9.ru/[/url] .
prognozi na fytbol_cjea
3 Oct 25 at 5:52 am
bigprintnewspapers – The brand projection seems serious, visuals support the message strongly.
Luther Willmore
3 Oct 25 at 5:52 am
Casinos that accept a wide range of cryptocurrencies provide greater flexibility.
web site
3 Oct 25 at 5:53 am
ставка прогноз ру [url=www.stavka-10.ru/]www.stavka-10.ru/[/url] .
stavka_dcSi
3 Oct 25 at 5:54 am
Обратился за продвижением сайта в поисковых системах, потому что клиентов практически не было. После проведённых работ пошёл рост позиций и увеличился поток заказов. Сейчас бизнес чувствует себя гораздо увереннее, спасибо за качественную работу: https://mihaylov.digital/
Steventob
3 Oct 25 at 5:54 am
https://webyourself.eu/blogs/1579372/1xBet-Promo-Code-Free-Bet-Unlock-Exclusive-Bonuses-in-2025
https://webyourself.eu/blogs/1579372/1xBet-Promo-Code-Free-Bet-Unlock-Exclusive-Bonuses-in-2025
3 Oct 25 at 5:54 am
OMT’s appealing video clip lessons tᥙrn complex math concepts іnto amazing stories,
helping Singapore trainees love tһe subject and rеally feel influenced to
ace tһeir tests.
Prepare fօr success іn upcoming examinations witһ OMT Math Tuition’ѕ exclusive curriculum, developed to foster crucial thinking аnd confidence іn every
trainee.
Cօnsidered thɑt mathematics plays a critical function in Singapore’ѕ
economic advancement and development, investing in specialized math tuition gears սp trainees
ԝith the prоblem-solving abilities required tο thrive in а
competitive landscape.
primary school math tuition builds exam endurance tһrough timed drills,
imitating tһe PSLE’s two-paper format and assisting trainees handle tіme effectively.
Tuition assists secondary students ⅽreate exam strategies, ѕuch
as time allowance foг Ƅoth O Level mathematics papers, ƅring about much better generaⅼ
efficiency.
Tuition incorporates pure ɑnd applied mathematics effortlessly, preparing students fⲟr the interdisciplinary nature оf A Level issues.
The distinctiveness ᧐f OMT comes from its proprietary math curriculum tһat
prolongs MOE material ᴡith project-based knowing f᧐r functional application.
Multi-device compatibility leh, ѕo change
from laptop to phone and keep increasing tһose grades.
With limited class time іn schools, math tuition expands finding ߋut hօurs, essential fߋr understanding tһe substantial Singapore mathematics curriculum.
Տtop by my ρage best jc math tuition
best jc math tuition
3 Oct 25 at 5:54 am
DragonMoney – лицензированное казино с щедрыми бонусами, топовыми играми, быстрыми выплатами и круглосуточной поддержкой
драгон мани официальный сайт
EdgarPak
3 Oct 25 at 5:54 am
прогнозы на ставки спорт [url=www.stavka-12.ru]www.stavka-12.ru[/url] .
stavka_ldSi
3 Oct 25 at 5:55 am
JEETA से जुड़ें और ऑनलाइन गेमिंग की एक नई
दुनिया का अनुभव करें।
JEETA ऑफिशियल | बांग्लादेश में सर्वश्रेष्ठ लाइव बेटिंग और कैसीनो
3 Oct 25 at 5:56 am
Hi I am so excited I found your blog page, I really found you by error, while I was searching on Google for something else, Anyhow I
am here now and would just like to say thanks for a fantastic post and a all round exciting blog (I also love the theme/design),
I don’t have time to read through it all at the moment but I
have book-marked it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the
superb work.
Visit Website
3 Oct 25 at 5:56 am
купить свидетельство о заключении брака [url=https://rudik-diplom1.ru]купить свидетельство о заключении брака[/url] .
Diplomi_qwer
3 Oct 25 at 5:57 am
прогноз ставки [url=https://stavka-12.ru/]прогноз ставки[/url] .
stavka_ccSi
3 Oct 25 at 6:01 am
футбол сегодня прогнозы [url=https://prognozy-na-futbol-9.ru/]prognozy-na-futbol-9.ru[/url] .
prognozi na fytbol_auea
3 Oct 25 at 6:02 am
прогнозы ставки на спорт сайт [url=https://stavka-10.ru/]https://stavka-10.ru/[/url] .
stavka_pwSi
3 Oct 25 at 6:02 am
Generic Cialis without a doctor prescription [url=https://tadalmedspharmacy.shop/#]Generic Cialis without a doctor prescription[/url] Buy Tadalafil 20mg
TimothyArrar
3 Oct 25 at 6:04 am
в прогнозе [url=stavka-12.ru]stavka-12.ru[/url] .
stavka_gzSi
3 Oct 25 at 6:05 am
JEETA-তে যোগ দিন এবং অনলাইন গেমিংয়ের এক নতুন জগতের অভিজ্ঞতা নিন।
JEETA অফিসিয়াল | বাংলাদেশের সেরা লাইভ বেটিং এবং ক্যাসিনো
3 Oct 25 at 6:06 am
ставки и прогнозы букмекеров на футбол сегодня [url=www.stavka-10.ru/]www.stavka-10.ru/[/url] .
stavka_fsSi
3 Oct 25 at 6:06 am
Закупки и официальный импорт из Китая
GeraldObedo
3 Oct 25 at 6:07 am
прогнозы на сегодня футбол [url=www.prognozy-na-futbol-9.ru/]www.prognozy-na-futbol-9.ru/[/url] .
prognozi na fytbol_aeea
3 Oct 25 at 6:07 am
https://www.blogger.com/profile/01590323918489352113
https://www.blogger.com/profile/01590323918489352113
3 Oct 25 at 6:08 am
купить диплом в серове [url=https://rudik-diplom15.ru/]купить диплом в серове[/url] .
Diplomi_cpPi
3 Oct 25 at 6:08 am
true vital meds: Sildenafil 100mg price – sildenafil
BruceMaivy
3 Oct 25 at 6:10 am
ставки на спорт прогноз [url=https://stavka-10.ru/]stavka-10.ru[/url] .
stavka_obSi
3 Oct 25 at 6:10 am
новости футбольных клубов [url=https://novosti-sporta-16.ru]https://novosti-sporta-16.ru[/url] .
novosti sporta_djsi
3 Oct 25 at 6:10 am
I think that is among the most important info for me.
And i’m glad studying your article. However wanna commentary on some common issues, The
website taste is perfect, the articles is actually great : D.
Good process, cheers
Sheffield Escorts
3 Oct 25 at 6:10 am
Приобрести онлайн кокаин, мефедрон, гашиш, бошки
Jeromeliz
3 Oct 25 at 6:11 am
прогноз ставок на футбол [url=www.prognozy-na-futbol-9.ru/]www.prognozy-na-futbol-9.ru/[/url] .
prognozi na fytbol_coea
3 Oct 25 at 6:13 am
tadalafil: Generic tadalafil 20mg price – tadalafil uk generic
MartinJaive
3 Oct 25 at 6:14 am
Kaizenaire.com is yⲟur go-to resource in Singapore fоr the most current shopping promotions, unique deals,
аnd muѕt-attend events.
Singaporeans ɑlways focus оn worth, flourishing іn Singapore’ѕ environment аs
a promotions-packed shopping heaven.
Singaporeans typically participate іn digital photography walks t᧐ record the city’ѕ stunning horizon, and keep
іn mind to remаin updated on Singapore’ѕ
most current promotions ɑnd shopping deals.
Bigo ɡives online streaming аnd social amusement applications, enjoyed Ƅy Singaporeans for tһeir interactive ϲontent and aгea involvement.
Klarra сreates contemporary women’ѕ clothes with clean lines one, treasured
byy mіnimal Singaporeans fоr tһeir versatile, premium items mah.
Benefit Tong Kee conveniences ᴡith silky poultry rice
ɑnd sideѕ, cherished by family membeгѕ for pleasant flavors and generous sections.
Aiyo, sharp leh, brand-neᴡ ρrice cuts on Kaizenaire.сom
one.
Also visit my web blog … singapore promos
singapore promos
3 Oct 25 at 6:15 am
прогноз на спорт на сегодня от профессионалов [url=www.prognozy-na-sport-11.ru/]www.prognozy-na-sport-11.ru/[/url] .
prognozi na sport_qePa
3 Oct 25 at 6:16 am
купить аттестат за классов [url=www.rudik-diplom14.ru/]купить аттестат за классов[/url] .
Diplomi_vtea
3 Oct 25 at 6:16 am
спорт онлайн [url=https://novosti-sporta-16.ru/]novosti-sporta-16.ru[/url] .
novosti sporta_ixsi
3 Oct 25 at 6:16 am
stavka prognoz [url=http://www.stavka-10.ru]http://www.stavka-10.ru[/url] .
stavka_cgSi
3 Oct 25 at 6:17 am
Hey are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and create my
own. Do you require any html coding knowledge to make your
own blog? Any help would be really appreciated!
dewascatter slot
3 Oct 25 at 6:19 am
прогнощы [url=www.stavka-12.ru]www.stavka-12.ru[/url] .
stavka_mcSi
3 Oct 25 at 6:20 am
прогнозы на спорт с высокой проходимостью бесплатно [url=http://prognozy-na-sport-11.ru/]http://prognozy-na-sport-11.ru/[/url] .
prognozi na sport_enPa
3 Oct 25 at 6:20 am
sliv.fun [url=www.sliv.fun/]www.sliv.fun/[/url] .
Sliv kyrsov_ywEn
3 Oct 25 at 6:21 am
https://www.sarbc.ru/link_articles/kak-vybrat-server-dlya-malogo-biznesa-osnovnye-parametry-i-oshibki-pri-pokupke.html
GeraldObedo
3 Oct 25 at 6:22 am
новости чемпионатов [url=http://novosti-sporta-15.ru]http://novosti-sporta-15.ru[/url] .
novosti sporta_gema
3 Oct 25 at 6:22 am
прогнозы букмекеров на сегодня [url=https://www.stavka-10.ru]https://www.stavka-10.ru[/url] .
stavka_iwSi
3 Oct 25 at 6:22 am
купить диплом в бузулуке [url=https://rudik-diplom3.ru]купить диплом в бузулуке[/url] .
Diplomi_jhei
3 Oct 25 at 6:22 am
I think that is one of the most significant information for me.
And i am satisfied studying your article. But wanna observation on few common things, The site taste is ideal, the articles is in point of fact great : D.
Just right process, cheers
бесплатные вращения
3 Oct 25 at 6:24 am