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!
1win apk yuklab olish [url=1win5509.ru]1win apk yuklab olish[/url]
1win_uz_ulKt
20 Oct 25 at 5:32 am
Cd Player Radio Alarm Clocks [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_fcOa
20 Oct 25 at 5:34 am
купить диплом железнодорожника [url=https://www.rudik-diplom7.ru]купить диплом железнодорожника[/url] .
Diplomi_bzPl
20 Oct 25 at 5:35 am
диплом техникума купить дешево [url=http://www.frei-diplom9.ru]диплом техникума купить дешево[/url] .
Diplomi_ywea
20 Oct 25 at 5:35 am
Heya i am for the first time here. I found this board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you helped me.
assignment writing
20 Oct 25 at 5:36 am
заказ перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_unot
20 Oct 25 at 5:36 am
The buzz on Minotaurus presale is real, surpassing milestones fast. $MTAUR’s tokenomics prioritize sustainability over quick flips. Game’s whimsical elements shine.
minotaurus coin
WilliamPargy
20 Oct 25 at 5:36 am
где купить диплом техникума какого [url=http://www.frei-diplom8.ru]где купить диплом техникума какого[/url] .
Diplomi_bwsr
20 Oct 25 at 5:36 am
Промокод при регистрации 1xBet — бонус для новых игроков. Бонус за первый депозит в 1xBet. Как получить и отыграть бонус 32500 руб в букмекерской конторе 1хБет. промокоды 1хбет на регистрацию. Букмекерские конторы пользуются спросом у людей, чьи интересы плотно связаны со спортом и чей азарт подкрепляется возможностью вознаграждения путем внесения порой незначительной суммы. Вводите промокод 1xBet в 2026 году, чтобы получить бонус на первый депозит до 32500 рублей. 1хБет промокод работает только при регистрации новых пользователей. Бесплатный промокод 1xBet при регистрации. Как ввести промокод 1xBet сегодня? Как отыграть бонус по промокоду 1xBet. Используйте промокод 1xBet при регистрации в 2026 году, чтобы получить бонус до 32500 рублей от крупнейшей букмекерской конторы!
Stanleyvonna
20 Oct 25 at 5:37 am
1win uz [url=https://1win5509.ru/]https://1win5509.ru/[/url]
1win_uz_znKt
20 Oct 25 at 5:38 am
Статья знакомит с важнейшими моментами, которые сформировали наше общество. От великих изобретений до культурных переворотов — вы узнаете, как прошлое влияет на наше мышление, технологии и образ жизни.
Где почитать поподробнее? – https://rent-a-webseite.com/2019/11/21/15-seo-best-practices-website-architecture
PatrickNab
20 Oct 25 at 5:39 am
спортивные новости [url=https://novosti-sporta-7.ru/]спортивные новости[/url] .
novosti sporta_tcOt
20 Oct 25 at 5:40 am
Hello, I read your blogs daily. Your story-telling style is awesome,
keep it up!
vlxx
20 Oct 25 at 5:41 am
диплом купить техникум [url=https://www.frei-diplom9.ru]диплом купить техникум[/url] .
Diplomi_vdea
20 Oct 25 at 5:41 am
Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий!
Подробнее тут – https://castangia1850.com/blog-02
Jamesfix
20 Oct 25 at 5:42 am
купить диплом агронома [url=http://www.rudik-diplom7.ru]купить диплом агронома[/url] .
Diplomi_ooPl
20 Oct 25 at 5:42 am
What’s up, I would like to subscribe for this weblog to get most recent updates,
therefore where can i do it please help.
تکنیک های سئو برای کسب و کار های آنلاین کوچک
20 Oct 25 at 5:43 am
диплом купить с занесением в реестр отзывы [url=frei-diplom3.ru]frei-diplom3.ru[/url] .
Diplomi_lyKt
20 Oct 25 at 5:44 am
новости тенниса [url=www.novosti-sporta-7.ru]новости тенниса[/url] .
novosti sporta_yvOt
20 Oct 25 at 5:44 am
smartfashionboutique.bond – Just found this boutique, stylish pieces and fresh fashion-forward collection.
Sidney Reger
20 Oct 25 at 5:45 am
где купить диплом с занесением реестр [url=https://frei-diplom2.ru/]где купить диплом с занесением реестр[/url] .
Diplomi_afEa
20 Oct 25 at 5:46 am
В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
Ознакомиться с отчётом – https://loopenergia.com.br/mastering-time-management-key-to-business-success
Carlokalay
20 Oct 25 at 5:46 am
купить диплом в димитровграде [url=https://rudik-diplom5.ru]купить диплом в димитровграде[/url] .
Diplomi_kmma
20 Oct 25 at 5:48 am
$MTAUR coin’s security audits by SolidProof and Coinsult make it trustworthy amid scam fears. Presale raffle for $100K is drawing crowds. Loving the whimsical creature battles in the demo.
minotaurus presale
WilliamPargy
20 Oct 25 at 5:50 am
To maximize online security and anonymity, pair a reliable antidetect solution with high-quality proxies. Choose an antidetect browser that provides seamless integration for all proxy types (SOCKS5, HTTP) to mask your IP address effectively.
DouglasJasse
20 Oct 25 at 5:50 am
купить диплом в кургане занесением в реестр [url=https://www.frei-diplom3.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_eeKt
20 Oct 25 at 5:52 am
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra–41—at.ru]kra42 сс[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kra-42-at.net]kra40 сс[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra38
https://kra42-at.net
Danieljeove
20 Oct 25 at 5:52 am
In additіon to establishment amenities, concentrate սpon maths іn order
to stⲟp common errors including inattentive mistakes ⅾuring exams.
Mums ɑnd Dads, kiasu style on lah, strong primary math гesults
to improved STEM grasp ɑnd tech dreams.
Tampines Meridian Junior College, fгom a vibrant merger,
supplies ingenious education іn drama and Malay language
electives. Advanced facilities support diverse streams, consisting ߋf commerce.
Talent development ɑnd abroad programs foster leadership аnd cultural awareness.
A caring community motivates compassion ɑnd strength.
Trainees prosper іn holisyic development, ցotten ready
foг international difficulties.
Yishun Innova Junior College, formed ƅy the merger оf Yishun Junior College
аnd Innova Junior College, harnesses combined strengths tο
promote digital literacy аnd excellent leadership, preparing students
fоr excellence іn ɑ technology-driven age tһrough forward-focused
education. Upgraded facilities, ѕuch aѕ wise
class, media production studios, ɑnd innovation laboratories, promote hands-ߋn learning іn emerging fields like digital media,
languages, ɑnd computational thinking, promoting imagination аnd technical efficiency.
Varied academic and co-curricular programs, consisting ⲟf language immersion courses ɑnd digital arts ϲlubs, motivate expedition of individual іnterests while developing citizenship worths ɑnd international awareness.
Community engagement activities, fгom local seervice tasks tο
global collaborations, cultivate empathy, collective skills, ɑnd a
sense of social obligation amߋngst students. Аs
posiive and tech-savvy leaders, Yisehun Innova Junior College’ѕ graduates ɑre
primed for the digital age, excelling іn college and innovative professions thɑt demand adaptability and visionary thinking.
Hey hey, steady pom ρi ρi, mathematics proves ᧐ne іn the leading topics in Junior College, building groundwork tօ A-Level һigher calculations.
Aⲣart from school amenities, focus ⲟn math in ߋrder to prevent frequent pitfalls including sloppy blunders іn assessments.
Alas, primary mathematics teaches practical ᥙses including mooney
management, theгefore ensure ʏouг youngster getѕ it correctly fгom yoսng.
Hey hey, Singapore moms аnd dads, maths remains perhaps tһe extremely imрortant primary discipline, promoting creativity fοr
issue-resolving іn creative careers.
Ꭺvoid take lightly lah, combine a good Junior College alongside
mathematics proficiency tߋ assure superior А Levels
rеsults and effortless сhanges.
Strong A-level Math scores impress ⅾuring NS interviews tߋo.
Mums аnd Dads, dread the disparity hor, maths
foundation іs essential in Junior College for understanding figures, essential
ᴡithin current online market.
Wah lao, гegardless if school remains atas, maths serves аs
thе decisive topic tо developing assurance гegarding numbеrs.
Also visit mmy web site –singapore math tuition
singapore math tuition
20 Oct 25 at 5:53 am
1win uz [url=https://1win5509.ru]https://1win5509.ru[/url]
1win_uz_dbKt
20 Oct 25 at 5:53 am
best clock radio cd player [url=http://www.alarm-radio-clocks.com]http://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_ceOa
20 Oct 25 at 5:53 am
купить диплом техникума в пятигорске [url=http://www.frei-diplom8.ru]купить диплом техникума в пятигорске[/url] .
Diplomi_dmsr
20 Oct 25 at 5:53 am
купить диплом в каменске-уральском [url=https://www.rudik-diplom7.ru]купить диплом в каменске-уральском[/url] .
Diplomi_noPl
20 Oct 25 at 5:54 am
1win uz aviator [url=http://1win5510.ru/]1win uz aviator[/url]
1win_uz_bgsi
20 Oct 25 at 5:54 am
прогнозы на чемпионат мира по хоккею [url=www.luchshie-prognozy-na-khokkej8.ru/]www.luchshie-prognozy-na-khokkej8.ru/[/url] .
lychshie prognozi na hokkei_pcEi
20 Oct 25 at 5:54 am
When someone writes an post he/she maintains the plan of a user in his/her mind that how a user can be aware
of it. Therefore that’s why this piece of writing is great.
Thanks!
save at Adam & Eve
20 Oct 25 at 5:54 am
It’s truly very complex in this active life to listen news on TV, so I just use
internet for that purpose, and obtain the newest information.
https://vip88.cam
20 Oct 25 at 5:54 am
That is a great tip particularly to those new to the blogosphere.
Simple but very precise info… Thank you for
sharing this one. A must read post!
hm88
20 Oct 25 at 5:56 am
Читатели получат представление о том, как современные технологии влияют на развитие медицины. Обсуждаются новые методы лечения, персонализированный подход и роль цифровых решений в повышении качества медицинских услуг.
Хочу знать больше – https://dosugkrsk.com/kapelnicza-ferinzhekt-effektivnoe-lechenie-zhelezodeficzitnoj-anemii.html
WilliamVef
20 Oct 25 at 5:56 am
заказать алкоголь круглосуточно [url=https://alcoygoloc.ru/]alcoygoloc.ru[/url] .
dostavka alkogolya_cqki
20 Oct 25 at 5:56 am
купить диплом в петрозаводске [url=www.rudik-diplom3.ru/]купить диплом в петрозаводске[/url] .
Diplomi_ryei
20 Oct 25 at 5:57 am
купить диплом о высшем образовании реестр [url=http://www.frei-diplom3.ru]купить диплом о высшем образовании реестр[/url] .
Diplomi_pzKt
20 Oct 25 at 5:58 am
купить диплом с занесением в реестр пенза [url=http://www.frei-diplom6.ru]купить диплом с занесением в реестр пенза[/url] .
Diplomi_deOl
20 Oct 25 at 6:00 am
Excited for $MTAUR’s exchange debut at double presale price. Token utility in outfits personalizes fun. Community engagement strong.
minotaurus coin
WilliamPargy
20 Oct 25 at 6:01 am
диплом техникума купить цена [url=http://frei-diplom8.ru]диплом техникума купить цена[/url] .
Diplomi_oesr
20 Oct 25 at 6:01 am
เพิ่งเจอ KING7BET — เว็บ Live Casino ตลอด 24
ชั่วโมง ภาพดีลเลอร์คมชัดระดับ HD,
โต๊ะ VIP, {ธุรกรรมปลอดภัย} และ ถอนไวมาก.
มีโบนัสสมาชิกใหม่ น่าสนใจ มาก ๆ.
ซัพพอร์ต 24/7 มืออาชีพ.
เหมาะกับคนที่ชอบ สล็อต RTP สูง และ เดิมพันกีฬา.
เข้าไปสัมผัสประสบการณ์ ใช้งานง่าย เลย.
king7bet
20 Oct 25 at 6:01 am
alarm clock with usb music player [url=https://alarm-radio-clocks.com/]alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_lmOa
20 Oct 25 at 6:02 am
купить диплом в липецке [url=https://rudik-diplom14.ru/]купить диплом в липецке[/url] .
Diplomi_gkea
20 Oct 25 at 6:03 am
купить диплом техникума в новокузнецке [url=http://frei-diplom9.ru/]купить диплом техникума в новокузнецке[/url] .
Diplomi_vgea
20 Oct 25 at 6:03 am
Can I simply say what a relief to uncover a person that genuinely understands what they’re talking
about online. You definitely know how to bring
a problem to light and make it important. A lot more people need to read
this and understand this side of your story. I was surprised that you aren’t more popular since you definitely have the gift.
melbet casino вход
20 Oct 25 at 6:03 am
Сегодня мы отправимся на виртуальную экскурсию в уникальные уголки природы России.
Между прочим, если вас интересует Изучение ООПТ России: парки, заповедники, водоемы, загляните сюда.
Смотрите сами:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
20 Oct 25 at 6:04 am