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!
Thanks for the auspicious writeup. It in fact used to be a enjoyment
account it. Look advanced to more delivered agreeable from you!
However, how could we keep up a correspondence?
read more here
17 Sep 25 at 4:44 pm
фильмы ужасов смотреть онлайн [url=https://kinogo-15.top]фильмы ужасов смотреть онлайн[/url] .
kinogo_dssa
17 Sep 25 at 4:46 pm
всезаймыонлайн [url=http://zaimy-11.ru]http://zaimy-11.ru[/url] .
zaimi_wnPt
17 Sep 25 at 4:46 pm
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Ознакомиться с теоретической базой – https://elcom-team.com/product/avast
ThomasHer
17 Sep 25 at 4:47 pm
https://xn--krken21-bn4c.com
Howardreomo
17 Sep 25 at 4:47 pm
Great article! This is the kind of info that are meant to be shared
across the net. Shame on Google for now not positioning this put up upper!
Come on over and seek advice from my web site .
Thank you =)
roofing near me
17 Sep 25 at 4:49 pm
Every weekend i used to pay a quick visit this site,
for the reason that i want enjoyment, as this this web site conations genuinely pleasant funny data
too.
turkey visa for australian
17 Sep 25 at 4:49 pm
My partner and I stumbled over here coming from a
different web address and thought I might check things out.
I like what I see so now i’m following you. Look forward to looking over your web
page again.
Paito Singapore Pools
17 Sep 25 at 4:50 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
17 Sep 25 at 4:50 pm
аниме смотреть онлайн [url=www.kinogo-15.top]аниме смотреть онлайн[/url] .
kinogo_dtsa
17 Sep 25 at 4:51 pm
аниме смотреть онлайн [url=https://kinogo-14.top]аниме смотреть онлайн[/url] .
kinogo_bhEl
17 Sep 25 at 4:51 pm
мфо займ [url=http://www.zaimy-11.ru]http://www.zaimy-11.ru[/url] .
zaimi_jtPt
17 Sep 25 at 4:51 pm
купить диплом высшего образования с занесением в реестр [url=http://www.educ-ua13.ru]купить диплом высшего образования с занесением в реестр[/url] .
Diplomi_clpn
17 Sep 25 at 4:51 pm
Oh my goodness! Incredible article dude! Thank you,
However I am encountering problems with your RSS. I don’t know the reason why I can’t subscribe to it.
Is there anybody else getting identical RSS issues?
Anybody who knows the solution can you kindly
respond? Thanks!!
دعا برای موفقیت در امتحانات
17 Sep 25 at 4:54 pm
документы военная ипотека
Brentagila
17 Sep 25 at 4:54 pm
Каждый новый круг отображает цвет и текстуру из предыдущего круга, что создает необычный и увлекательный эффект.
http://firewall-en.uptozion.org/2025/07/22/osobennosti-onlajnkazino-s-pribylnymi-slotami/
17 Sep 25 at 4:54 pm
Thanks for your marvelous posting! I definitely enjoyed reading it, you’re a great
author. I will be sure to bookmark your blog and will come back from
now on. I want to encourage one to continue your great writing, have a nice weekend!
Spot Hiberix Opt
17 Sep 25 at 4:54 pm
аниме смотреть онлайн [url=kinogo-15.top]аниме смотреть онлайн[/url] .
kinogo_dksa
17 Sep 25 at 4:55 pm
займы все [url=www.zaimy-11.ru/]www.zaimy-11.ru/[/url] .
zaimi_llPt
17 Sep 25 at 4:55 pm
Semoga artikel seperti ini terus hadir agar semakin banyak pembaca yang mendapatkan informasi akurat mengenai KUBET dan Situs Judi Bola.
Situs Parlay Gacor
17 Sep 25 at 4:56 pm
смотреть фильмы онлайн [url=www.kinogo-12.top]смотреть фильмы онлайн[/url] .
kinogo_pxol
17 Sep 25 at 4:56 pm
фильмы онлайн без подписки [url=https://kinogo-14.top]https://kinogo-14.top[/url] .
kinogo_fsEl
17 Sep 25 at 4:56 pm
Мы готовы предложить документы учебных заведений, которые находятся на территории всей Российской Федерации. Купить диплом университета:
[url=http://karagandasobaka.kabb.ru/posting.php?mode=post&f=43&sid=7d82d8658675dec7fd4fc690a2ba8125/]купить аттестат 11 класс цена[/url]
Diplomi_luPn
17 Sep 25 at 4:57 pm
Way cool! Some extremely valid points! I appreciate you penning this article and the rest of the site is extremely good.
Fundspire Axivon
17 Sep 25 at 4:57 pm
все микрозаймы на карту [url=http://www.zaimy-11.ru]http://www.zaimy-11.ru[/url] .
zaimi_kdPt
17 Sep 25 at 5:00 pm
аниме смотреть онлайн [url=http://www.kinogo-15.top]аниме смотреть онлайн[/url] .
kinogo_rpsa
17 Sep 25 at 5:00 pm
сериалы онлайн [url=www.kinogo-14.top/]www.kinogo-14.top/[/url] .
kinogo_caEl
17 Sep 25 at 5:00 pm
смотреть мультфильмы онлайн бесплатно [url=https://kinogo-12.top]https://kinogo-12.top[/url] .
kinogo_xaol
17 Sep 25 at 5:00 pm
1win на айфон [url=https://1win12014.ru/]https://1win12014.ru/[/url]
1win_sxOl
17 Sep 25 at 5:02 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
17 Sep 25 at 5:03 pm
kinogo [url=www.kinogo-12.top]kinogo[/url] .
kinogo_pool
17 Sep 25 at 5:03 pm
купить диплом с проводкой меня [url=https://arus-diplom33.ru]купить диплом с проводкой меня[/url] .
Diplomi_vdSa
17 Sep 25 at 5:03 pm
купить диплом занесенный в реестр [url=educ-ua13.ru]educ-ua13.ru[/url] .
Diplomi_typn
17 Sep 25 at 5:03 pm
Что такое Agile https://agile-metod.ru и как его внедрить? Подробные статьи о гибких методологиях, инструментах и практиках. Scrum, Kanban и Lean — всё о современном управлении проектами.
EdwardVor
17 Sep 25 at 5:05 pm
киного [url=www.kinogo-14.top]киного[/url] .
kinogo_gcEl
17 Sep 25 at 5:06 pm
I’m amazed, I have to admit. Rarely do I come across a blog that’s both equally
educative and entertaining, and without a doubt, you’ve hit the nail on the head.
The problem is an issue that too few folks are speaking intelligently about.
Now i’m very happy I found this in my search for something regarding this.
roofing company near me
17 Sep 25 at 5:06 pm
Что такое Agile https://agile-metod.ru и как его внедрить? Подробные статьи о гибких методологиях, инструментах и практиках. Scrum, Kanban и Lean — всё о современном управлении проектами.
EdwardVor
17 Sep 25 at 5:07 pm
Что такое Agile https://agile-metod.ru и как его внедрить? Подробные статьи о гибких методологиях, инструментах и практиках. Scrum, Kanban и Lean — всё о современном управлении проектами.
EdwardVor
17 Sep 25 at 5:07 pm
https://push-network-rankings.com/
Brianfub
17 Sep 25 at 5:11 pm
Wah lao, math serves as ɑmong in the extremely
іmportant subjects dսring Junior College, assisting children understand patterns tһаt prove essential іn STEM jobs afterwardѕ ahead.
St. Andrew’s Junior College cultivates Anglican values
аnd holistic growth, constructing principled people ᴡith strong character.
Modern facilities support excellence іn academics, sports, аnd arts.
Social ԝork and leadership programs instill compassion ɑnd duty.
Varied co-curricular activities promote teamwork аnd ѕelf-discovery.
Alumni become ethical leaders, contributing meaningfully tօ society.
Catholic Junior College սses a transformative educational experience centered οn ageless
worths оf empathy, integrity, and pursuit ߋf reality, cultivating ɑ
close-knit neighborhood wһere trainees feel supported ɑnd inspired tօ grow both intellectually and spiritually in a serene
and inclusive setting. Ꭲhe college ρrovides comprehensive scholastic
programs іn the liberal arts, sciences, аnd social sciences, delivered Ƅy enthusiastic and experienced coaches ᴡһo employ innovative teaching ɑpproaches to stimulate curiosity ɑnd motivate
deep, meaningful knowing tһat extends fаr Ьeyond assessments.
Ꭺn lively selection оf cⲟ-curricular activities, including competitive sports
ցroups that promote physical health аnd sociability, аlong ᴡith creative
societies that support creative expression thгough
drama аnd visual arts, alⅼows trainees tо explore tһeir intеrests and
develop welⅼ-rounded personalities. Opportunities for ѕignificant neighborhood service, ѕuch
as collaborations with regional charities аnd worldwide humanitarian trips, һelp
construct empathy, management skills, аnd a authenticc commitment tߋ making
a distinction in the lives of оthers. Alumni fгom
Catholic Junior College ⲟften emerge as caring and ethical leaders іn various
professional fields, equipped ѡith the knowledge, resilience, and ethical compass t᧐ contribute positively and sustainably tο society.
Aρart beyond establishment facilities, emphasize օn mathematics in ᧐rder to aᴠoid typical pitfalls likе inattentive errors ɑt assessments.
Parents, competitive style engaged lah, robust primary math results t᧐ improved
scientific grasp ρlus tech aspirations.
Parents, fear the disparity hor, maths foundation proves vital ɗuring Junior College in comprehending data,
vital ԝithin todɑy’s digital economy.
Wah lao, no matter ԝhether school proves fancy, math acts ⅼike tһe decisive discipline
tⲟ cultivates poise ᴡith numberѕ.
Math mastery іn JC prepares үou for the quantitative demands of
business degrees.
Оh, mathematics acts ⅼike the foundation pillar іn primary learning, helping kids іn geometric analysis іn building careers.
Feel free tο surf to my web-site: Anglo-Chinese School (Independent)
Anglo-Chinese School (Independent)
17 Sep 25 at 5:14 pm
смотреть комедии онлайн [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .
kinogo_bqol
17 Sep 25 at 5:14 pm
исторические фильмы [url=www.kinogo-15.top/]исторические фильмы[/url] .
kinogo_upsa
17 Sep 25 at 5:15 pm
все микрозаймы [url=http://zaimy-11.ru]http://zaimy-11.ru[/url] .
zaimi_qbPt
17 Sep 25 at 5:15 pm
купить дипломы о высшем образовании в киеве [url=http://educ-ua18.ru]http://educ-ua18.ru[/url] .
Diplomi_vzPi
17 Sep 25 at 5:15 pm
Мы можем предложить документы ВУЗов, которые находятся на территории всей России. Заказать диплом о высшем образовании:
[url=http://vseamoskva.flybb.ru/viewtopic.php?f=2&t=1256/]корочка для аттестата 11 класс купить[/url]
Diplomi_prPn
17 Sep 25 at 5:16 pm
займы онлайн [url=zaimy-11.ru]zaimy-11.ru[/url] .
zaimi_dyPt
17 Sep 25 at 5:19 pm
сериалы онлайн [url=https://kinogo-15.top]https://kinogo-15.top[/url] .
kinogo_phsa
17 Sep 25 at 5:19 pm
Затяжной запой опасен для жизни. Врачи наркологической клиники в Краснодаре проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-krasnodar11.ru/]vyvod-iz-zapoya-krasnodar11.ru[/url]
QuincyTrine
17 Sep 25 at 5:20 pm
Hello there, I found your blog by the use of
Google even as looking for a similar subject, your web site got here up, it seems to be good.
I have bookmarked it in my google bookmarks.
Hi there, simply was alert to your blog via Google, and found that it
is truly informative. I am gonna watch out for brussels.
I will be grateful when you continue this
in future. A lot of other folks will probably be benefited from your writing.
Cheers!
28bet88.com
17 Sep 25 at 5:20 pm
It’s hard to find knowledgeable people about this subject,
however, you sound like you know what you’re talking about!
Thanks
new casino online
17 Sep 25 at 5:21 pm