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!
https://t.me/s/Beefcasino_rus/27
HighRollerMage
28 Oct 25 at 2:21 pm
https://t.me/Official_mellstroy_casino/42
Calvindreli
28 Oct 25 at 2:22 pm
кракен маркетплейс
кракен сайт
Henryamerb
28 Oct 25 at 2:23 pm
https://t.me/s/Official_mellstroy_casino/59
Calvindreli
28 Oct 25 at 2:23 pm
Благо им! Биза на высоту https://tuningclass.ru какой выход с 1г ?
JasonBoomi
28 Oct 25 at 2:23 pm
интерактивные панели
Marvinreoky
28 Oct 25 at 2:24 pm
This is a topic which is near to my heart…
Best wishes! Where are your contact details though?
Leger Finvio
28 Oct 25 at 2:25 pm
https://t.me/Beefcasino_rus/36
LuckyBandit
28 Oct 25 at 2:25 pm
купить диплом в киселевске [url=https://www.rudik-diplom7.ru]купить диплом в киселевске[/url] .
Diplomi_kjPl
28 Oct 25 at 2:25 pm
оборудование конференц-зала
Bryanfloky
28 Oct 25 at 2:26 pm
Промокод позволяет улучшить предлагаемые условия и получить ещё большую выгоду. Вводить melbet промокод при регистрации 2026 аккаунта или непосредственно перед внесением депозита. При этом все данные в профиле игрока в личном кабинете должны быть заполнены достоверной информацией, иначе это может привести к трудностям при выводе средств. Компания оставляет за собой право проводить различные проверки с целью защититься от недобросовестных действий бетторов (мультиаккаунтинг, бонусхантинг, подложные документы и т.п.). Для получения бонуса в соответствующих полях регистрационной формы клиент сначала должен выбрать его вид (спортивный бонус 100% на первый депозит, казино-бонус, фрибет), а затем указать промокод (при наличии). Также следует подтвердить совершеннолетие и согласие с правилами БК. Если беттор не желает обременять себя отыгрышем бонусных денег, то в ходе регистрации в поле выбора бонуса можно выбрать отметку «Мне не нужен бонус».
Georgeduh
28 Oct 25 at 2:26 pm
kraken официальный
кракен тор
Henryamerb
28 Oct 25 at 2:29 pm
оборудование конференц-зала
Bryanfloky
28 Oct 25 at 2:30 pm
This game looks amazing! The way it blends that old-school chicken crossing concept with actual consequences is brilliant.
Count me in!
Okay, this sounds incredibly fun! Taking that nostalgic
chicken crossing gameplay and adding real risk?
I’m totally down to try it.
This is right up my alley! I’m loving the combo of classic
chicken crossing mechanics with genuine stakes involved.
Definitely want to check it out!
Whoa, this game seems awesome! The mix of that timeless chicken crossing feel with real consequences
has me hooked. I need to play this!
This sounds like a blast! Combining that iconic chicken crossing gameplay with actual stakes?
Sign me up!
I’m so into this concept! The way it takes that classic chicken crossing vibe and adds legitimate risk
is genius. Really want to give it a go!
This game sounds ridiculously fun! That fusion of nostalgic chicken crossing action with real-world stakes has me interested.
I’m ready to jump in!
Holy cow, this looks great! Merging that beloved chicken crossing style with tangible consequences?
I’ve gotta try this out!
chicken road game apk
28 Oct 25 at 2:32 pm
лед экран
Marvinreoky
28 Oct 25 at 2:32 pm
Presque toutes les robes des femmes arrivaient au niveau du genou ou au-dessus.
Georgia
28 Oct 25 at 2:33 pm
ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.
IsmaelStics
28 Oct 25 at 2:33 pm
блог о маркетинге [url=http://statyi-o-marketinge6.ru]блог о маркетинге[/url] .
stati o marketinge _ckkn
28 Oct 25 at 2:35 pm
Wah, in Singapore, a prestigious primary mеans admission to fօrmer students grⲟups, assisting yoսr kid land internships and jobs іn future.
Goodness, t᧐p primaries honor inventiveness, encouraging neᴡ ventures inn Singapore’s business scene.
Guardians, fear tһe disparity hor, math groundwork proves critical аt primary school tⲟ grasping figures,
essential fοr modern online economy.
Hey hey, Singapore folks, arithmetic гemains perһaps the extremely imⲣortant primary discipline, encouraging
imagination іn challenge-tackling for groundbreaking careers.
Ⅾο not mess around lah, combine a good primary school ρlus math excellence to
assure elevated PSLE reѕults as ԝell ɑs seamless ϲhanges.
Guardians, fearful ߋf losing style οn lah, solid
primary mathematics leads t᧐ improved scientific grasp ɑnd tech goals.
Guardians, dread tһе gap hor, math base гemains
critical іn primary school in comprehending informаtion, vital foг current tech-driven market.
Ѕi Ling Primary School оffers а positive setting for
detailed development.
Ꭲhe school motivates seⅼf-confidence througһ
quality guideline.
Methodist Girls’ School (Primary) empowers ladies ᴡith Methodist worths ɑnd rigor.
Тhe school promotes leadership ɑnd quality.
Іt’s a leading option for aⅼl-girls education.
mү website … Serangoon Garden Secondary School
Serangoon Garden Secondary School
28 Oct 25 at 2:36 pm
купить диплом фельдшера [url=rudik-diplom9.ru]купить диплом фельдшера[/url] .
Diplomi_giei
28 Oct 25 at 2:37 pm
душевые на заказ из стекла в спб перегородки [url=http://dzen.ru/a/aPaQV60E-3Bo4dfi/]http://dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .
steklyannie dyshevie na zakaz _rfol
28 Oct 25 at 2:37 pm
beste sportwetten Apps (educamosviajando.com) urteil
educamosviajando.com
28 Oct 25 at 2:37 pm
kraken vpn
kraken android
Henryamerb
28 Oct 25 at 2:37 pm
купить диплом в ноябрьске [url=www.rudik-diplom7.ru]купить диплом в ноябрьске[/url] .
Diplomi_oaPl
28 Oct 25 at 2:38 pm
оборудование конференц-зала
Bryanfloky
28 Oct 25 at 2:38 pm
кракен vk6
kraken market
Henryamerb
28 Oct 25 at 2:38 pm
l2dkp.com – Found practical insights today; sharing this article with colleagues later.
Elmira Stankiewicz
28 Oct 25 at 2:38 pm
Наши выездные и стационарные бригады работают по принципу «одна корректировка за раз». Меняем не всё и сразу, а ровно один параметр — темп инфузии, очередность модулей или поведенческий якорь (свет/тишина/питьевой режим). Затем в заранее оговорённый момент проверяем эффект по фактам: переносимость воды малыми глотками, вариабельность ЧСС к сумеркам, латентность сна, число ночных пробуждений, субъективная ясность утром. Такая дисциплина устраняет хаос и снижает потребность «усиливать» терапию «на всякий случай».
Выяснить больше – http://narkologicheskaya-klinika-saratov0.ru/klinika-narkologii-saratov/
Williamweith
28 Oct 25 at 2:40 pm
vqscvasavtzqpsj.shop – Bookmarked this immediately, planning to revisit for updates and inspiration.
Michale Mccraig
28 Oct 25 at 2:40 pm
Цифровая экономика формирует будущее сайт kraken darknet kraken онион kraken онион тор кракен онион
RichardPep
28 Oct 25 at 2:41 pm
spartanwebsolution.com – Content reads clearly, helpful examples made concepts easy to grasp.
Doug Dejarnette
28 Oct 25 at 2:41 pm
ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.
IsmaelStics
28 Oct 25 at 2:41 pm
Эта статья предлагает захватывающий и полезный контент, который привлечет внимание широкого круга читателей. Мы постараемся представить тебе идеи, которые вдохновят вас на изменения в жизни и предоставят практические решения для повседневных вопросов. Читайте и вдохновляйтесь!
Обратитесь за информацией – https://doodhghar.com/hello-world
Martinkem
28 Oct 25 at 2:42 pm
душевое ограждение матовое стекло [url=www.dzen.ru/a/aPaQV60E-3Bo4dfi/]www.dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .
steklyannie dyshevie na zakaz _dvol
28 Oct 25 at 2:42 pm
кракен Россия
кракен сайт
Henryamerb
28 Oct 25 at 2:43 pm
[url=https://mydiv.net/arts/view-TOP-5-luchshih-servisov-virtualnyh-nomerov-dlya-SMS-aktivaciy-v-2026-godu.html]аренда номера[/url]
Briantar
28 Oct 25 at 2:43 pm
Hey there, I think your site might be having browser compatibility issues.
When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it
has some overlapping. I just wanted to give you a quick heads up!
Other then that, superb blog!
dewa scatter
28 Oct 25 at 2:43 pm
pok01.live – Bookmarked this immediately, planning to revisit for updates and inspiration.
Jonah Presha
28 Oct 25 at 2:44 pm
ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.
IsmaelStics
28 Oct 25 at 2:44 pm
[url=https://umnye-shtory-s-elektroprivodom.ru/]шторы СЃ автоматическим управлением Прокарниз[/url] – управляемые шторы, которые позволят вам легко контролировать свет и атмосферу в вашем доме.
Раздел 2: Преимущества управляемых штор
управление шторами и жалюзи с электроприводом Прокарниз
28 Oct 25 at 2:44 pm
купить диплом в ухте [url=www.rudik-diplom13.ru]купить диплом в ухте[/url] .
Diplomi_khon
28 Oct 25 at 2:45 pm
продвижение сайтов интернет магазины в москве [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru/]продвижение сайтов интернет магазины в москве[/url] .
optimizaciya i seo prodvijenie saitov moskva_nzPi
28 Oct 25 at 2:46 pm
led экран
Marvinreoky
28 Oct 25 at 2:46 pm
[url=https://elektrokarnizy-dlya-shtor-moskva.ru/]электро карниз[/url] позволяют управлять шторами с помощью одного нажатия кнопки, обеспечивая удобство и комфорт в вашем доме.
Автоматические карнизы с электроприводом становятся всё более популярными в современных интерьере.
электрокарниз купить в москве Прокарниз
28 Oct 25 at 2:46 pm
Thankfulness to my father who informed me regarding this web site, this web site is in fact remarkable.
ankara kürtaj
28 Oct 25 at 2:47 pm
купить диплом для иностранцев [url=http://rudik-diplom7.ru/]купить диплом для иностранцев[/url] .
Diplomi_bzPl
28 Oct 25 at 2:49 pm
kraken 2025
кракен тор
Henryamerb
28 Oct 25 at 2:49 pm
ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.
IsmaelStics
28 Oct 25 at 2:50 pm
оснащение конференц залов
Bryanfloky
28 Oct 25 at 2:52 pm
интерактивные панели
Marvinreoky
28 Oct 25 at 2:52 pm