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!
На сторінці zebraschool.com.ua замовляв ремонт автомагнітоли у Вінниці — зробили якісно
zebraschool-454
26 Oct 25 at 8:18 am
What a information of un-ambiguity and preserveness
of valuable familiarity on the topic of unpredicted feelings.
sugar daddy
26 Oct 25 at 8:18 am
1xbet yeni giri? adresi [url=https://1xbet-14.com]1xbet yeni giri? adresi[/url] .
1xbet_jiet
26 Oct 25 at 8:19 am
J-center Studio — школа, где учат профессии парикмахера на практике с четвёртого дня: работа с клиентами, колористика, мужские и женские стрижки, укладки, стажировка в салонах. Прозрачные цены, маленькие группы, инструменты и материалы — за счёт школы. Записаться и узнать ближайший старт можно на https://j-center.ru/ — расписание, форматы (группы, индивидуально, экстерн) и контакты на странице. Диплом и реальный опыт дают выпускникам быстрый вход в индустрию красоты.
cipymeRed
26 Oct 25 at 8:24 am
На сайті zebraschool.com.ua лагодили генератор у Сумах — сервіс на висоті
zebraschool-651
26 Oct 25 at 8:25 am
1x bet giri? [url=www.1xbet-12.com]www.1xbet-12.com[/url] .
1xbet_dtSr
26 Oct 25 at 8:26 am
На сторінці zebraschool.com.ua замовив ремонт електросамоката в Полтаві — результат чудовий
zebraschool-596
26 Oct 25 at 8:28 am
1xbet yeni giri? [url=http://1xbet-12.com]1xbet yeni giri?[/url] .
1xbet_hySr
26 Oct 25 at 8:28 am
farmacia con entrega rápida: farmacia online para hombres – pastillas de potencia masculinas
Jesuskax
26 Oct 25 at 8:28 am
Piece of writing writing is also a excitement, if you be
familiar with after that you can write or else it is complex to write.
toto slot
26 Oct 25 at 8:29 am
1 x bet giri? [url=www.1xbet-16.com]1 x bet giri?[/url] .
1xbet_xzOn
26 Oct 25 at 8:29 am
1xbet tr giri? [url=https://1xbet-10.com]https://1xbet-10.com[/url] .
1xbet_thea
26 Oct 25 at 8:29 am
kraken vk5
kraken онлайн
JamesDaync
26 Oct 25 at 8:30 am
Если вы ищете информацию о бонусах при регистрации, прочитайте наши рекомендации о видах вознаграждений; в одном из разделов статьи естественно упомянут https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html для получения приветственного бонуса. Редакция объясняем, как вводить данные при регистрации и какие правила нужно выполнить для отыгрыша.
PatrickDrymn
26 Oct 25 at 8:30 am
1 x bet giri? [url=http://1xbet-13.com]http://1xbet-13.com[/url] .
1xbet_aoKa
26 Oct 25 at 8:31 am
Отзывы о обработка от клопов с гарантией реальные? Делитесь.
дезинфекция после потопа
KennethceM
26 Oct 25 at 8:32 am
Hurrah! At last I got a blog from where I can really obtain useful facts concerning my
study and knowledge.
유흥알바
26 Oct 25 at 8:32 am
На сайті zebraschool.com.ua побачив послугу ремонту дитячих колясок — дійсно зручно
zebraschool-454
26 Oct 25 at 8:34 am
оборудование для больниц [url=medicinskoe–oborudovanie.ru]medicinskoe–oborudovanie.ru[/url] .
medicinskoe oborydovanie_ppei
26 Oct 25 at 8:34 am
Everything in One Place: https://www.home-truths.co.uk
BryanAlarl
26 Oct 25 at 8:35 am
частная наркологическая клиника в москве анонимное [url=https://narkologicheskaya-klinika-23.ru/]https://narkologicheskaya-klinika-23.ru/[/url] .
narkologicheskaya klinika_tpet
26 Oct 25 at 8:35 am
букмекерская контора теннесси скачать [url=mostbet12032.ru]mostbet12032.ru[/url]
mostbet_kg_xfmt
26 Oct 25 at 8:36 am
mostbet kg [url=https://mostbet12031.ru/]mostbet kg[/url]
mostbet_kg_igMa
26 Oct 25 at 8:37 am
1 x bet [url=www.1xbet-14.com]1 x bet[/url] .
1xbet_oset
26 Oct 25 at 8:39 am
1 xbet giri? [url=https://1xbet-12.com]https://1xbet-12.com[/url] .
1xbet_ehSr
26 Oct 25 at 8:39 am
1x bet [url=https://1xbet-10.com/]1xbet-10.com[/url] .
1xbet_djea
26 Oct 25 at 8:42 am
mostbets [url=https://mostbet12031.ru/]https://mostbet12031.ru/[/url]
mostbet_kg_kxMa
26 Oct 25 at 8:42 am
Hi there, just became alert to your blog through Google,
and found that it’s really informative. I am going to watch out for brussels.
I’ll appreciate if you continue this in future. A lot of people will be benefited from your writing.
Cheers!
https://vmv88.com/
26 Oct 25 at 8:42 am
1 x bet [url=http://1xbet-16.com/]1 x bet[/url] .
1xbet_vlOn
26 Oct 25 at 8:44 am
1xbet lite [url=http://1xbet-16.com]1xbet lite[/url] .
1xbet_hgOn
26 Oct 25 at 8:47 am
букмекерская контора теннесси скачать [url=http://mostbet12031.ru]http://mostbet12031.ru[/url]
mostbet_kg_kzMa
26 Oct 25 at 8:47 am
köpa Viagra online Sverige: Sildenafil-tabletter pris – MannensApotek
Jesuskax
26 Oct 25 at 8:47 am
kraken онлайн
kraken vk3
JamesDaync
26 Oct 25 at 8:48 am
1xbet resmi sitesi [url=https://1xbet-13.com/]https://1xbet-13.com/[/url] .
1xbet_lqKa
26 Oct 25 at 8:50 am
Ресторан чистый после профессиональная дератизация.
уничтожение муравьев
KennethceM
26 Oct 25 at 8:51 am
go source
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
go source
26 Oct 25 at 8:51 am
После дезинфекция помещений от вирусов запах исчез, дом свежий!
уничтожение тараканов
KennethceM
26 Oct 25 at 8:52 am
Alas, primary math instructs real-worⅼd uѕеs suсh ɑs financial planning, sօ guarantee үour
kid grasps tһis rіght starting eɑrly.
Listen ᥙp, composed pom pi pі, math remаins among fгom the leading
disciplines ɗuring Junior College, building foundation іn A-Level calculus.
St. Andrew’ѕ Junior College fosters Anglican worths ɑnd holistic development, developing
principled individuals ᴡith strong character.
Modern amenities support excellence іn academics, sports,
аnd arts.Community service and leadership programs impart compassion аnd duty.
Diverse ϲo-curricular activities promote teamwork ɑnd sеlf-discovery.
Alumni emerge аs ethical leaders, contributing meaningfully t᧐ society.
Ⴝt. Joseph’ѕ Institution Junior College promotes cherished Lasallian traditions оf faith, service, and intellectual curiosity,
producing ɑn empowering environment ᴡhere trainees
pursue knowledge ԝith passion and devote
tһemselves to uplifting οthers tһrough caring actions.
Τhe incorporated program makеs ѕure a fluid
development fгom secondary to pre-university levels, ԝith a concentrate
οn multilingual proficiency ɑnd innovative curricula supported ƅy centers
ⅼike stɑte-of-the-art performing arts centers аnd science гesearch labs that influence imaginative ɑnd analytical quality.
Worldwide immersion experiences, including
international service trips аnd cultural exchange programs,
expand students’ horizons, enhance linguistic skills, аnd cultivate а deep appreciation fοr varied
worldviews. Opportunities fߋr advanced гesearch study,
management functions іn trainee companies, аnd mentorship fгom accomplished professors develop confidence,
vital thinking, ɑnd a dedication tо ⅼong-lasting
knowing. Graduates ɑre understood for theіr compassion and
hіgh accomplishments, protecting plaϲes іn prominent universities аnd mastering careers that align wifh tһe college’ѕ ethos օf service
and intellectual rigor.
Wah, math acts ⅼike thе foundation block in primary learning, aiding
kids іn spatial analysis fօr design routes.
Alas, lacking robust mathematics аt Junior College, еven prestigious
institution kids сould falter ԝith secondary equations, tһus cultivate thіs now leh.
Dοn’t take lightly lah, pair ɑ reputable
Junior College alongside mathematics excellence fοr guarantee superior А Levels гesults and smooth transitions.
Oһ dear, lacking solid math аt Junior College, eѵеn leading institution children mаү falter іn neхt-level algebra, so cultivate it noѡ leh.
Good grades іn A-levels mеan less debt from loans if ʏou get merit-based
aid.
Oһ, maths is the base block for primary learning, assisting kids ѡith spatial reasoning tο architecture paths.
Ⲟh dear, without solid maths іn Junior College,
no matter leading establishment kids ϲould struggle wіtһ next-level equations,
tһus cultivate іt now leh.
Here is my blog :: Math tuition for ip students at east
Math tuition for ip students at east
26 Oct 25 at 8:53 am
платная наркологическая клиника [url=http://www.narkologicheskaya-klinika-23.ru]http://www.narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_mset
26 Oct 25 at 8:54 am
1xbet yeni adresi [url=1xbet-14.com]1xbet yeni adresi[/url] .
1xbet_adet
26 Oct 25 at 8:54 am
Appreciate this post. Let me try it out.
98WIN
26 Oct 25 at 8:56 am
https://directory-broker.com/listings13371116/code-promo-1xbet-cote-d-ivoire
vrltdhu
26 Oct 25 at 8:56 am
Hello, i think that i saw you visited my site so i came to “return the favor”.I’m attempting to find things to improve my website!I suppose its ok to use a few of your
ideas!!
website
26 Oct 25 at 8:58 am
kraken обмен
кракен актуальная ссылка
JamesDaync
26 Oct 25 at 9:01 am
xbet [url=www.1xbet-16.com/]xbet[/url] .
1xbet_eiOn
26 Oct 25 at 9:01 am
мелбет kg [url=https://www.mostbet12032.ru]https://www.mostbet12032.ru[/url]
mostbet_kg_nrmt
26 Oct 25 at 9:01 am
1xbet giri? [url=1xbet-12.com]1xbet giri?[/url] .
1xbet_pdSr
26 Oct 25 at 9:03 am
После санэпидемстанция цены дом безопасный для детей.
уничтожение клопов холодным туманом
KennethceM
26 Oct 25 at 9:04 am
mostbet сайт [url=mostbet12032.ru]mostbet12032.ru[/url]
mostbet_kg_fvmt
26 Oct 25 at 9:04 am
мостбет официальный сайт вход [url=https://mostbet12032.ru]https://mostbet12032.ru[/url]
mostbet_kg_ijmt
26 Oct 25 at 9:04 am