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!
1вин слоты [url=https://1win5510.ru]1вин слоты[/url]
1win_uz_ccsi
19 Oct 25 at 11:22 am
brittanydominguez.shop – The color scheme is subtle and soothing, doesn’t strain the eyes at all.
Ray Alig
19 Oct 25 at 11:22 am
можно ли купить диплом медсестры [url=http://www.frei-diplom13.ru]можно ли купить диплом медсестры[/url] .
Diplomi_unkt
19 Oct 25 at 11:24 am
1вин лайв ставки [url=http://1win5510.ru/]http://1win5510.ru/[/url]
1win_uz_ixsi
19 Oct 25 at 11:24 am
z9hl4.info – Visuals complement the text nicely; the design feels polished and thought-out.
Susana Zackery
19 Oct 25 at 11:25 am
Hola! I’ve been following your blog for a while
now and finally got the courage to go ahead and give you
a shout out from Dallas Texas! Just wanted to mention keep up the fantastic work!
trading platform with demo account
19 Oct 25 at 11:25 am
1win uz promo kod [url=https://1win5509.ru]https://1win5509.ru[/url]
1win_uz_ziKt
19 Oct 25 at 11:27 am
Hmm it looks like your site ate my first comment (it was extremely long) so I guess
I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog.
I too am an aspiring blog blogger but I’m still new to everything.
Do you have any tips for beginner blog writers?
I’d genuinely appreciate it.
kra41
19 Oct 25 at 11:27 am
Для безопасного выхода из запоя в Сочи воспользуйтесь услугами стационара клиники «Детокс». Опытные врачи окажут помощь быстро и анонимно.
Узнать больше – [url=https://vyvod-iz-zapoya-sochi24.ru/]вывод из запоя вызов город[/url]
Bryankax
19 Oct 25 at 11:28 am
1win ro‘yxatdan o‘tish orqali bonus [url=http://1win5509.ru]http://1win5509.ru[/url]
1win_uz_bnKt
19 Oct 25 at 11:28 am
1win o‘zbek tilida sayt [url=https://1win5510.ru]https://1win5510.ru[/url]
1win_uz_mksi
19 Oct 25 at 11:30 am
купить диплом в асбесте [url=rudik-diplom13.ru]купить диплом в асбесте[/url] .
Diplomi_beon
19 Oct 25 at 11:30 am
купить диплом в улан-удэ [url=http://rudik-diplom6.ru/]купить диплом в улан-удэ[/url] .
Diplomi_ogKr
19 Oct 25 at 11:32 am
Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
mtaur coin
WilliamPargy
19 Oct 25 at 11:33 am
кракен vk6
kraken qr code
JamesDaync
19 Oct 25 at 11:36 am
мелбет ру официальный сайт [url=http://www.melbetbonusy.ru]http://www.melbetbonusy.ru[/url] .
melbet_vdOi
19 Oct 25 at 11:36 am
Если нужен профессиональный вывод из запоя, обращайтесь в стационар клиники «Детокс» в Сочи. Все процедуры проводятся анонимно и под наблюдением специалистов.
Детальнее – [url=https://vyvod-iz-zapoya-sochi24.ru/]скорая вывод из запоя в сочи[/url]
Bryankax
19 Oct 25 at 11:37 am
https://imageevent.com/keonnasurau/enafd
Anthonycam
19 Oct 25 at 11:38 am
Sou fazaco do DazardBet Casino, parece uma tempestade de diversao. O catalogo de jogos do cassino e colossal, com jogos de cassino perfeitos para criptomoedas. O atendimento ao cliente do cassino e fora da curva, com uma ajuda que e um show a parte. O processo do cassino e limpo e sem complicacao, as vezes queria mais promocoes de cassino que arrebentam. No fim das contas, DazardBet Casino e um cassino online que e pura dinamite para os amantes de cassinos online! De bonus a navegacao do cassino e facil como brincar, da um toque de classe ao cassino.
dazardbet casino bonus|
sparklemoth8zef
19 Oct 25 at 11:39 am
купить диплом программиста [url=http://rudik-diplom13.ru]купить диплом программиста[/url] .
Diplomi_hton
19 Oct 25 at 11:39 am
1вин казино уз [url=https://www.1win5509.ru]1вин казино уз[/url]
1win_uz_eqKt
19 Oct 25 at 11:42 am
купить аттестаты за 9 [url=www.rudik-diplom9.ru]купить аттестаты за 9[/url] .
Diplomi_jaei
19 Oct 25 at 11:43 am
1win uz [url=https://1win5510.ru/]1win uz[/url]
1win_uz_rtsi
19 Oct 25 at 11:44 am
мелбет дают ли фрибет [url=https://melbetbonusy.ru/]мелбет дают ли фрибет[/url] .
melbet_fkOi
19 Oct 25 at 11:49 am
1вин поддержка [url=www.1win5509.ru]www.1win5509.ru[/url]
1win_uz_unKt
19 Oct 25 at 11:50 am
Wah, a gooԁ Junior College remɑins superb, уet math acts ⅼike thee dominant topic
tһere, cultivating rational cognition ᴡhich sets
уоur kid ᥙp tօ achieve Ⲟ-Level success and ahead.
St. Joseph’s Institution Junior College embodies Lasallian traditions, highlighting faith, service, аnd intellectual
pursuit. Integrated programs ᥙse seamless development wіth concentrate ⲟn bilingualism ɑnd innovation. Facilities lіke performing arts centers enhance imaginative expression. Worldwide immersions аnd
resеarch study opportunities broaden perspectives. Graduates ɑre compassionate achievers, mastering universities аnd careers.
River Valley Hiցh School Junior College flawlessly incⅼudes bilingual education ԝith a strong
dedication tо ecological stewardship, nurturing eco-conscious leaders ѡho have sharp international
рoint of views and а commitment to sustainable practices in аn progressively interconnected
ԝorld. Ꭲhe school’ѕ innovative labs, green innovation centers, аnd environment-friendly campus designs support pioneering
knowing іn sciences, liberal arts, and ecological studies,
motivating students tօ engage in hands-օn experiments ɑnd innovative solutions tօ real-wߋrld obstacles.
Cultural immersion programs, ѕuch аs language exchanges and heritage trips, combined ѡith community
service projects concentrated օn preservation, boost trainees’ compassion, cultural intelligence,
ɑnd useful skills for positive social еffect. Within a unified and supportive community, participation іn sports gгoups, arts societies, аnd management
workshops promotes physical ԝell-being, teamwork,аnd resilience,
developing healthy individuals ready fߋr future undertakings.
Graduates from River Valley Нigh School Junior College
arе preferably plɑced for success in leading universities and
professions, embodying tһе school’s core values of fortitude, cultural acumen, аnd
a proactive approach tⲟ global sustainability.
Eh eh, composed pom ρi pі, mathematics іs among from the hiցhest disciplines duriung Junior College,
laying groundwork fօr Α-Level calculus.
Apart from institution amenities, concentrate ᥙpon maths for avοid typical mistakes ⅼike
inattentive blunders іn tests.
Folks, dread tһe difference hor, math foundation іs
essential іn Junior College to comprehending data, crucial ᴡithin current online economy.
Goodness, no matter ѡhether institution proves fancy, maths
іs the mаke-or-break discipline fоr building
assurance regarding numЬers.
Parents, dread tһe disparity hor, maths foundation іѕ critical ԁuring Junior College to
grasping data, essential fօr toԁay’s online economy.
A-level success correlates ѡith higһеr starting salaries.
Folks, kiasu style activated lah, robust primary mathematics guides tօ improved science understanding ɑs weⅼl as tech dreams.
Օh, maths acts like tһe groundwork pillar fоr primary schooling, aiding kids іn spatial reasoning
foг building routes.
my web рage; National Junior College
National Junior College
19 Oct 25 at 11:50 am
https://t.me/s/official_1win_aviator
HighRollerMage
19 Oct 25 at 11:51 am
кракен маркетплейс
кракен зеркало
JamesDaync
19 Oct 25 at 11:55 am
Выездная наркологическая помощь в Нижнем Новгороде — капельница от запоя с выездом на дом. Мы обеспечиваем быстрое и качественное лечение без необходимости посещения клиники.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]вывод из запоя капельница в нижний новгороде[/url]
Miltondiolo
19 Oct 25 at 11:56 am
купить диплом о среднем образовании [url=rudik-diplom9.ru]купить диплом о среднем образовании[/url] .
Diplomi_ikei
19 Oct 25 at 11:57 am
trendandstyle – Excellent customer service, quick responses and helpful support.
Vivian Silovich
19 Oct 25 at 11:57 am
brittanydominguez.shop – I just visited and the site feels sleek with a very modern clean layout.
Chas Weeden
19 Oct 25 at 11:58 am
nathanjones.shop – Visuals complement the text nicely; the design feels polished and thought-out.
Arletta Colpi
19 Oct 25 at 11:59 am
купить диплом в владивостоке [url=www.rudik-diplom6.ru]купить диплом в владивостоке[/url] .
Diplomi_jyKr
19 Oct 25 at 12:01 pm
z9hl4.info – Visuals complement the text nicely; the design feels polished and thought-out.
Leeanna Sumstad
19 Oct 25 at 12:03 pm
букмекерская контора melbet [url=https://melbetbonusy.ru]букмекерская контора melbet[/url] .
melbet_kwOi
19 Oct 25 at 12:04 pm
купить свидетельство о браке [url=https://rudik-diplom9.ru]купить свидетельство о браке[/url] .
Diplomi_rhei
19 Oct 25 at 12:05 pm
Greetings! Very useful advice in this particular article!
It’s the little changes that produce the most important changes.
Thanks for sharing!
forex broker
19 Oct 25 at 12:05 pm
В автомобиле находятся:
Подробнее – http://
JosephNoirl
19 Oct 25 at 12:08 pm
Minotaurus coin’s ecosystem fun-focused. ICO’s legal green light. DAO votes exciting.
minotaurus presale
WilliamPargy
19 Oct 25 at 12:10 pm
https://t.me/s/official_1win_aviator
RoyalFlusher
19 Oct 25 at 12:11 pm
Estou completamente enfeiticado por SpellWin Casino, e um cassino online que brilha como uma pocao encantada. A selecao de titulos do cassino e um caldeirao de emocoes, com jogos de cassino perfeitos pra criptomoedas. O servico do cassino e confiavel e encantador, dando solucoes na hora e com precisao. Os saques no cassino sao velozes como um feitico de teletransporte, mesmo assim mais giros gratis no cassino seria uma loucura magica. Resumindo, SpellWin Casino vale demais explorar esse cassino para os magos do cassino! De lambuja o design do cassino e um espetaculo visual encantado, o que torna cada sessao de cassino ainda mais encantadora.
george spellwin|
zestycandycrow6zef
19 Oct 25 at 12:11 pm
мелбет бонус правила [url=http://melbetbonusy.ru]мелбет бонус правила[/url] .
melbet_urOi
19 Oct 25 at 12:13 pm
Ich liebe die Pracht von King Billy Casino, es ist ein Online-Casino, das wie ein Konig regiert. Die Casino-Optionen sind vielfaltig und prachtig, inklusive eleganter Casino-Tischspiele. Der Casino-Service ist zuverlassig und furstlich, antwortet blitzschnell wie ein koniglicher Erlass. Auszahlungen im Casino sind schnell wie ein koniglicher Marsch, ab und zu wurde ich mir mehr Casino-Promos wunschen, die glanzvoll sind. Alles in allem ist King Billy Casino ein Casino mit einem Spielspa?, der wie ein Kronungsfest funkelt fur Fans moderner Casino-Slots! Zusatzlich die Casino-Plattform hat einen Look, der wie ein Kronungsmantel glanzt, einen Hauch von Majestat ins Casino bringt.
avis king billy casino|
goofybeetle9zef
19 Oct 25 at 12:14 pm
Wonderful blog! I found it while searching
on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Many thanks
Naperville Lockout Services
19 Oct 25 at 12:15 pm
1win uz [url=www.1win5510.ru]1win uz[/url]
1win_uz_dmsi
19 Oct 25 at 12:16 pm
В момент вызова важно сообщить:
Ознакомиться с деталями – [url=https://narkologicheskaya-klinika-rostov13.ru/]запой наркологическая клиника в ростове-на-дону[/url]
JosephNoirl
19 Oct 25 at 12:16 pm
Представляем вашему вниманию национальные парки и заповедники России.
Для тех, кто ищет информацию по теме “Изучение ООПТ России: парки, заповедники, водоемы”, там просто кладезь информации.
Вот, можете почитать:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Природа – наш главный учитель и защитник. Берегите её!
fixRow
19 Oct 25 at 12:16 pm
We’re a group of volunteers and starting a new scheme in our community.
Your web site offered us with valuable information to
work on. You have done an impressive job and our entire
community will be grateful to you.
tekun777
19 Oct 25 at 12:16 pm
можно купить диплом медсестры [url=www.frei-diplom13.ru/]можно купить диплом медсестры[/url] .
Diplomi_uykt
19 Oct 25 at 12:17 pm