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!
Thank you for some other great article. Where else may just anyone get that type of info in such a perfect approach of writing?
I’ve a presentation subsequent week, and I’m on the look for such info.
Cosplay Asia
26 Oct 25 at 6:36 am
Цены на обработка от тараканов разумные, качество на высоте.
уничтожение блох
KennethceM
26 Oct 25 at 6:36 am
обработка от тараканов с гарантией для офиса, посоветуйте проверенных.
дезинфекция после ремонта
KennethceM
26 Oct 25 at 6:37 am
1xbet com giri? [url=www.1xbet-10.com]www.1xbet-10.com[/url] .
1xbet_yiea
26 Oct 25 at 6:38 am
kraken marketplace
кракен vk4
JamesDaync
26 Oct 25 at 6:38 am
mostbet kg [url=https://mostbet12032.ru/]https://mostbet12032.ru/[/url]
mostbet_kg_vnmt
26 Oct 25 at 6:41 am
bahis sitesi 1xbet [url=1xbet-16.com]bahis sitesi 1xbet[/url] .
1xbet_ntOn
26 Oct 25 at 6:42 am
1xbet t?rkiye [url=https://1xbet-12.com/]1xbet t?rkiye[/url] .
1xbet_vmSr
26 Oct 25 at 6:42 am
If you wish for to get a good deal from this piece of writing then you have to apply these
methods to your won website.
daftar qqalfa138
26 Oct 25 at 6:42 am
I’m really enjoying the design and layout of your website.
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? Exceptional work!
dump truck service near me
26 Oct 25 at 6:43 am
1xbet guncel [url=http://1xbet-10.com/]http://1xbet-10.com/[/url] .
1xbet_axea
26 Oct 25 at 6:44 am
клиники наркологические москва [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_obSr
26 Oct 25 at 6:44 am
wrestlingac – However, it’s not immediately clear what region or organization the site primarily serves, so context is a bit vague.
Nelia Rataj
26 Oct 25 at 6:48 am
Обработка дезинфекция подвалов эффективная, рекомендую.
уничтожение моли в шкафу
KennethceM
26 Oct 25 at 6:48 am
1x giri? [url=http://www.1xbet-14.com]http://www.1xbet-14.com[/url] .
1xbet_qget
26 Oct 25 at 6:48 am
кракен онлайн
кракен 2025
JamesDaync
26 Oct 25 at 6:50 am
Oh, math is thе groundwork pillar of primary schooling, aiding kids for spatial reasoning to architecture paths.
Aiyo, lacking robust maths ɗuring Junior College, regardless prestigious school youngsters ⅽould falter іn secondary algebra, ѕo develop іt pгomptly leh.
Nanyang Junior College champs bilingual quality, mixing cultural
heritage ԝith modern education tto support positive international residents.
Advanced facilities support strong programs іn STEM, arts, ɑnd liberal arts, promoting innovation ɑnd creativity.
Trainees flourish іn a lively neighborhood with opportunities fоr leadership and
international exchanges. Τһe college’ѕ emphasis
on values and strength develops character alongside scholastic
prowess. Graduates master leading institutions,
continuing а tradition of accomplishment and cultural
appreciation.
Տt. Andrew’ѕ Junior College accepts Anglican values t᧐ promote holistic
growth, cultivating principled individuals ᴡith robust character
characteristics tһrough a blend of spiritual guidance, scholastic pursuit,
and community participation іn a warm and inclusive environment.
Ꭲhе college’s contemporary amenities, consisting оf interactive class, sports complexes, аnd
imaginative arts studios, һelp witһ excellence tһroughout
academic disciplines, sports programs tһat stress physical
fitness ɑnd fair play, ɑnd artistic ventures that motivate self-expression and innovation. Neighborhood service initiatives, ѕuch as
volunteer collaborations wіtһ local companies and outreach projects,
impart empathy, social responsibility, ɑnd a sense of purpose, improving students’ instructional journeys.
А varied series of co-curricular activities, from debate societies tо musical
ensembles, promotes teamwork, leadership skills, аnd personal discovery, permitting еverү trainee to shine in theіr picked areas.
Alumni of Տt. Andrew’s Junior College consistently emerge ɑs ethical, resistant leaders ѡho make significɑnt contributions to society, reflecting the institution’ѕ profound influence on developing welⅼ-rounded,
valᥙe-driven individuals.
Оh dear, withօut strong mathematics іn Junior
College, regarԀⅼess leading school kids mɑү falter wіth high school
algebra, tһerefore cultivate іt pгomptly leh.
Listen up, Singapore moms аnd dads, maths remains lіkely the extremely impⲟrtant primary subject, encouraging innovation іn challenge-tackling fоr
groundbreaking jobs.
Aiyo, lacking robust maths аt Junior College, even prestigious establishment
kids could falter at next-level equations, tһus build thiѕ ρromptly
leh.
Вesides Ьeyond establishment facilities, concentrate ᴡith maths іn orԀer
to stop frequent mistakes suⅽh as inattentive blunders at exams.
Parents, kiasu mode engaged lah, solid primary math results
foг better science comprehension ɑs well aѕ engineering goals.
Wah, maths serves as tһe groundwork stone ߋf primary learning,
helping children ѡith dimensional analysis іn design careers.
Failing tߋ do welⅼ in A-levels might mеɑn retaking or ɡoing poly,
ƅut JC route iѕ faster іf yоu score high.
Wah, maths acts likе the foundation stone in primary learning, aiding kids ᴡith geometric analysis for building paths.
Aiyo, ѡithout solid math at Junior College, еven prestigious school children mаy struggle withh hіgh school algebra, ѕo build іt
now leh.
Ꮋere is my web-site; Raffles Institution Junior College
Raffles Institution Junior College
26 Oct 25 at 6:52 am
куплю диплом медсестры в москве [url=http://frei-diplom15.ru/]куплю диплом медсестры в москве[/url] .
Diplomi_keoi
26 Oct 25 at 6:53 am
birxbet giri? [url=1xbet-13.com]1xbet-13.com[/url] .
1xbet_mtKa
26 Oct 25 at 6:54 am
joebobsaveschristmas – Love the color scheme and graphics, very distinctive and memorable.
Fredric Orendain
26 Oct 25 at 6:55 am
I’ve been exploring for a bit for any high-quality
articles or weblog posts on this sort of area .
Exploring in Yahoo I at last stumbled upon this website. Reading this information So i am happy to show that I’ve an incredibly excellent uncanny feeling
I found out exactly what I needed. I most undoubtedly will
make certain to do not put out of your mind this web site and provides it a look regularly.
Read More Here
26 Oct 25 at 6:55 am
купить диплом повара [url=http://www.rudik-diplom12.ru]купить диплом повара[/url] .
Diplomi_edPi
26 Oct 25 at 6:56 am
1x bet giri? [url=http://www.1xbet-13.com]http://www.1xbet-13.com[/url] .
1xbet_zoKa
26 Oct 25 at 6:57 am
1xbet turkey [url=https://1xbet-16.com]1xbet turkey[/url] .
1xbet_toOn
26 Oct 25 at 6:57 am
поставка медоборудования [url=https://medoborudovanie-postavka.ru/]https://medoborudovanie-postavka.ru/[/url] .
postavka medicinskogo oborydovaniya_vxsn
26 Oct 25 at 6:58 am
bahis siteler 1xbet [url=https://1xbet-12.com]bahis siteler 1xbet[/url] .
1xbet_idSr
26 Oct 25 at 6:58 am
1x bet [url=http://www.1xbet-10.com]http://www.1xbet-10.com[/url] .
1xbet_jpea
26 Oct 25 at 6:59 am
мостбест [url=http://mostbet12031.ru/]мостбест[/url]
mostbet_kg_tfMa
26 Oct 25 at 7:00 am
1xbet turkey [url=www.1xbet-14.com/]1xbet turkey[/url] .
1xbet_kzet
26 Oct 25 at 7:01 am
https://mediuomo.shop/# ordinare Viagra generico in modo sicuro
JamesSlilk
26 Oct 25 at 7:02 am
Do you mind if I quote a few of your articles as long as I provide credit and sources back
to your blog? My website is in the exact same area of interest as yours and my visitors would really benefit from
some of the information you provide here. Please let me know
if this ok with you. Appreciate it!
buôn bán nội tạng
26 Oct 25 at 7:02 am
Нужна обработка от клопов от клещей на участке.
дезинфекция квартиры после умершего
KennethceM
26 Oct 25 at 7:02 am
кракен vk5
kraken сайт
JamesDaync
26 Oct 25 at 7:03 am
magnificent submit, very informative. I wonder why the opposite specialists of this sector
do not notice this. You should proceed your writing. I’m confident,
you’ve a great readers’ base already!
papillon elegante
26 Oct 25 at 7:04 am
1xbet [url=https://www.1xbet-10.com]1xbet[/url] .
1xbet_oyea
26 Oct 25 at 7:04 am
Good post. I learn something totally new and challenging on websites I stumbleupon on a daily basis.
It’s always exciting to read content from other writers and practice something from other websites.
immune support
26 Oct 25 at 7:06 am
медицинская техника [url=www.medicinskaya-tehnika.ru/]медицинская техника[/url] .
medicinskaya tehnika_jlEi
26 Oct 25 at 7:06 am
birxbet [url=www.1xbet-13.com/]www.1xbet-13.com/[/url] .
1xbet_czKa
26 Oct 25 at 7:06 am
I all the time used to study post in news papers but now as I am a user of internet therefore from
now I am using net for content, thanks to web.
sekabet giriş
26 Oct 25 at 7:08 am
1xbet giri? 2025 [url=https://1xbet-13.com]1xbet giri? 2025[/url] .
1xbet_cxKa
26 Oct 25 at 7:13 am
1xbet giris [url=www.1xbet-12.com/]1xbet giris[/url] .
1xbet_omSr
26 Oct 25 at 7:13 am
birxbet [url=https://1xbet-16.com/]birxbet[/url] .
1xbet_tqOn
26 Oct 25 at 7:13 am
1xbet giri? g?ncel [url=https://1xbet-14.com/]1xbet giri? g?ncel[/url] .
1xbet_llet
26 Oct 25 at 7:15 am
лечение зависимостей [url=https://narkologicheskaya-klinika-23.ru/]https://narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_hfet
26 Oct 25 at 7:15 am
foruminvestmali – Overall it’s a useful reference for “Invest in Mali” initiatives, but treat it as a starting point and cross-check other sources.
Wanetta Thatch
26 Oct 25 at 7:16 am
После дезинфекция помещений от вирусов запах исчез, дом свежий!
дезинфекция после умерших
KennethceM
26 Oct 25 at 7:20 am
кракен 2025
kraken сайт
JamesDaync
26 Oct 25 at 7:21 am
I could not resist commenting. Well written!
K. Vet Animal Care
26 Oct 25 at 7:22 am
1xbetgiri? [url=https://1xbet-10.com/]https://1xbet-10.com/[/url] .
1xbet_ytea
26 Oct 25 at 7:23 am
sega-live – No strong reviews or outside mentions found, so proceed cautiously before ordering.
Bree Justis
26 Oct 25 at 7:26 am