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://tamozhenniiy-broker-moskva.ru/
NathanDax
23 Oct 25 at 5:32 pm
bahis sitesi 1xbet [url=https://1xbet-giris-9.com/]bahis sitesi 1xbet[/url] .
1xbet giris_fson
23 Oct 25 at 5:32 pm
можно ли купить диплом медсестры [url=https://www.frei-diplom14.ru]можно ли купить диплом медсестры[/url] .
Diplomi_vyoi
23 Oct 25 at 5:34 pm
It’s genuinely very difficult in this busy life to listen news on TV,
thus I simply use world wide web for that purpose,
and obtain the newest news.
Nationwide Contracting
23 Oct 25 at 5:34 pm
Je suis accro a Spinit Casino, on ressent une ambiance de piste. Les options sont vastes comme une course, proposant des jeux de table rapides. Avec des depots instantanes. Le service est disponible 24/7, toujours pret a accelerer. Les paiements sont securises et rapides, parfois des bonus plus varies seraient un sprint. Dans l’ensemble, Spinit Casino est un incontournable pour les joueurs pour les joueurs en quete d’excitation ! Ajoutons que le site est rapide et attractif, facilitate une immersion totale. Particulierement interessant les paiements securises en crypto, propose des avantages personnalises.
https://casinospinitfr.com/|
WheelWhisperB3zef
23 Oct 25 at 5:36 pm
Navigating the bridge between traditional finance and the digital
asset world has always been a major pain point for many in the GSA community.
The exorbitant fees and opaque processes between fiat and crypto platforms can severely compromise financial agility.
This is precisely why the Paybis fintech platform
is so compelling. They aren’t just another crypto exchange; they’ve
built a seamlessly integrated gateway that effortlessly handles both fiat and cryptocurrency banking.
Imagine executing trades across USD, EUR, and a vast selection of major digital
assets—all from a streamlined platform. Their focus on user-friendly onboarding means you can transact with confidence.
A brief comment can’t possibly do justice to the full scope of their feature set, especially their advanced tools for institutional
clients. To get a complete picture of how Paybis is solving the fiat-crypto problem, you absolutely need to read the detailed analysis in the full article.
It breaks down their payment methods, fee structure, and
security protocols in a way that is incredibly insightful.
Don’t just take my word for it check out the piece to see
if their platform aligns with your strategic financial goals.
It’s a comprehensive overview for anyone in our field looking to optimize their financial stack.
The link is in the main post—you won’t regret it.
website
23 Oct 25 at 5:37 pm
exploreamazingideas – The tone is friendly and approachable, doesn’t feel overly formal or salesy.
Jamey Deering
23 Oct 25 at 5:40 pm
https://t.me/s/ofitsialniy_1win/33/Kix
https://t.me/s/ofitsialniy_1win/33/Kix
23 Oct 25 at 5:41 pm
lucky jet игра скачать [url=https://www.1win5518.ru]https://www.1win5518.ru[/url]
1win_kg_drkl
23 Oct 25 at 5:41 pm
1 xbet giri? [url=https://1xbet-giris-2.com/]1xbet-giris-2.com[/url] .
1xbet giris_rwPt
23 Oct 25 at 5:42 pm
1xbet guncel [url=1xbet-giris-9.com]1xbet guncel[/url] .
1xbet giris_cuon
23 Oct 25 at 5:43 pm
активные ваучеры 1win [url=http://1win5518.ru/]http://1win5518.ru/[/url]
1win_kg_ylkl
23 Oct 25 at 5:44 pm
1xbet resmi sitesi [url=www.1xbet-giris-6.com]www.1xbet-giris-6.com[/url] .
1xbet giris_kdsl
23 Oct 25 at 5:45 pm
лучшие агентства seo продвижения [url=https://reiting-seo-kompaniy.ru]https://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_nson
23 Oct 25 at 5:46 pm
With havin so much written content do you ever run into
any problems of plagorism or copyright infringement? My site has
a lot of unique content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the internet without my agreement.
Do you know any methods to help reduce content from being ripped off?
I’d certainly appreciate it.
dewascatter slot
23 Oct 25 at 5:47 pm
1xbet turkey [url=www.1xbet-giris-8.com]1xbet turkey[/url] .
1xbet giris_kzPn
23 Oct 25 at 5:47 pm
Please let me know if you’re looking for a author for your weblog.
You have some really good articles and I believe I would be a good asset.
If you ever want to take some of the load off, I’d love to write some content
for your blog in exchange for a link back to mine. Please send
me an e-mail if interested. Cheers!
kitchen exhaust singapore
23 Oct 25 at 5:48 pm
hyrdaruzxpnev4of.online – Found several helpful guides, will return later for more details.
Rashad Mathony
23 Oct 25 at 5:50 pm
Realmente has desarrollado este tema de forma excelente!|
Vaya, muchos tips de tragamonedas!|
Buen trabajo, Gracias por compartir!|
El artículo fue adecuadamente escrito!|
Interesante análisis, Se aprecia.|
Con agradecimiento. Aprecié este contenido de bonos|Interesante contenido sobre iGaming!|
Muchas gracias, Amplia guía sobre bonos aquí!
https://performanceart.lucillelehr.com/gmedia/10250203_808415419186143_8116802616751320096_n-jpg
23 Oct 25 at 5:50 pm
1xbet mobil giri? [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .
1xbet giris_zjSa
23 Oct 25 at 5:51 pm
J’adore l’aura divine d’ Olympe Casino, il procure une experience legendaire. La selection de jeux est olympienne, comprenant des jeux optimises pour les cryptos. Avec des depots rapides. Les agents repondent comme des dieux, offrant des reponses claires. Les gains arrivent sans delai, de temps a autre des bonus plus varies seraient un nectar. Au final, Olympe Casino garantit un plaisir divin pour les fans de casino en ligne ! De plus l’interface est fluide comme un nectar, ce qui rend chaque session plus celeste. A souligner le programme VIP avec des niveaux exclusifs, assure des transactions fiables.
olympefr.com|
AthenaWisdomB2zef
23 Oct 25 at 5:51 pm
1win kg [url=https://1win5518.ru/]1win kg[/url]
1win_kg_rkkl
23 Oct 25 at 5:52 pm
1xbet t?rkiye [url=https://www.1xbet-giris-5.com]1xbet t?rkiye[/url] .
1xbet giris_rySa
23 Oct 25 at 5:53 pm
1 xbet giri? [url=www.1xbet-giris-2.com/]www.1xbet-giris-2.com/[/url] .
1xbet giris_yxPt
23 Oct 25 at 5:55 pm
kbdesignlab.com – Found practical insights today; sharing this article with colleagues later.
Douglas Neverman
23 Oct 25 at 5:56 pm
onewin зеркало [url=https://1win5519.ru]https://1win5519.ru[/url]
1win_kg_xaEr
23 Oct 25 at 5:57 pm
Goodness, prestigious institutions incorporate dance, improving coordination fօr performing theater professions.
Oi, ԁon’t disregard hor, excellent primary emphasizes location,
f᧐r transport and commerce jobs.
Oi oi, Singapore folks, mathematics іs ⲣerhaps tһe extremely esdential primary discipline, fostering imagination іn ⲣroblem-solving
to innovative professions.
Guardians, dread tһe disparity hor, mathematics groundwork гemains vital at primary school in grasping informаtion, vital ԝithin modern digital market.
Ᏼesides from institution facilities, emphasize ߋn math in orɗer
tߋ prevent frequent pitfalls ⅼike inattentive errors іn tests.
Wah lao, even іf establishment remains fancy, arithmetic is tһe critical discipline tⲟ building poise ԝith
figures.
Оh dear, lacking strong math аt primary school, no matter prestigious institution kids сould stumble wіth
higһ school equations, therefore cultivate іt now leh.
Qihua Primary School supplies ɑn іnteresting environment motivating development and self-confidence.
Devoted instructors support ԝell-rounded people.
St Stephen’s School рrovides Christian education ᴡith strong values.
Тhe school nurtures holistic advancement.
Ӏt’ѕ ideal for faith-based families.
Hеre is my web blog Yishun Secondary School, Sheldon,
Sheldon
23 Oct 25 at 5:57 pm
1xbet g?ncel giri? [url=1xbet-giris-4.com]1xbet g?ncel giri?[/url] .
1xbet giris_gdSa
23 Oct 25 at 6:00 pm
рейтинг digital seo агентств [url=https://reiting-seo-kompaniy.ru]рейтинг digital seo агентств[/url] .
reiting seo kompanii_tlon
23 Oct 25 at 6:00 pm
купить диплом в шахтах [url=https://rudik-diplom2.ru/]https://rudik-diplom2.ru/[/url] .
Diplomi_tcpi
23 Oct 25 at 6:01 pm
можно купить диплом медсестры [url=https://frei-diplom14.ru]можно купить диплом медсестры[/url] .
Diplomi_mqoi
23 Oct 25 at 6:02 pm
куда вводить промокод 1win [url=https://1win5519.ru]https://1win5519.ru[/url]
1win_kg_ulEr
23 Oct 25 at 6:03 pm
lenotoplenie.ru инструкции, как активировать бонусные программы и акции
CollinDwets
23 Oct 25 at 6:03 pm
J’adore l’atmosphere blues de BassBet Casino, il procure une experience rythmee. Il y a une profusion de jeux excitants, offrant des sessions live immersives. Le bonus de bienvenue est rythme. Les agents repondent comme un riff, joignable a toute heure. Le processus est simple et elegant, bien que quelques tours gratuits supplementaires seraient bien venus. En bref, BassBet Casino est un incontournable pour les joueurs pour ceux qui aiment parier en crypto ! De plus le site est rapide et attractif, ajoute une touche de rythme. Un autre atout les tournois reguliers pour la competition, propose des avantages personnalises.
bassbetcasinologinfr.com|
DeltaBassC6zef
23 Oct 25 at 6:03 pm
https://mediuomo.com/# trattamento ED online Italia
Hermanereli
23 Oct 25 at 6:04 pm
https://www.beirutnews.net/newsr/15861
iwebjjl
23 Oct 25 at 6:06 pm
1xbet giri? yapam?yorum [url=http://www.1xbet-giris-4.com]http://www.1xbet-giris-4.com[/url] .
1xbet giris_eeSa
23 Oct 25 at 6:06 pm
Такая карта делает лечение обозримым и дисциплинирует решения: пациент видит цель и порог перехода, семья понимает, зачем нужно соблюдать «тихие» часы, команда сохраняет управляемость и не «крутит ручки» ночью.
Подробнее можно узнать тут – https://narkologicheskaya-klinika-v-petrozavodske15.ru/narkolog-petrozavodsk-otzyvy
WilliamRep
23 Oct 25 at 6:07 pm
1xbet tr giri? [url=https://1xbet-giris-5.com/]1xbet-giris-5.com[/url] .
1xbet giris_ioSa
23 Oct 25 at 6:08 pm
1 x bet [url=https://www.1xbet-giris-9.com]1 x bet[/url] .
1xbet giris_zion
23 Oct 25 at 6:10 pm
http://lenotoplenie.ru актуальные инструкции по активации бонусов
CollinDwets
23 Oct 25 at 6:11 pm
1xbet giri? linki [url=https://www.1xbet-giris-6.com]1xbet giri? linki[/url] .
1xbet giris_snsl
23 Oct 25 at 6:12 pm
tuzidh.pw – Typography and spacing are comfortable, reading experience feels pleasant.
Rolf Zotti
23 Oct 25 at 6:14 pm
1xbet guncel [url=http://www.1xbet-giris-2.com]http://www.1xbet-giris-2.com[/url] .
1xbet giris_afPt
23 Oct 25 at 6:14 pm
1xbet turkiye [url=www.1xbet-giris-6.com]www.1xbet-giris-6.com[/url] .
1xbet giris_uqsl
23 Oct 25 at 6:14 pm
Домашний формат наркологической помощи особенно востребован в курортном регионе: плотный график, сезонная работа, круглосуточная индустрия гостеприимства и нежелание афишировать проблему заставляют искать решение «тихо и быстро». В «ЮгМедЦентре» (Сочи) выезд врача доступен 24/7 без праздников и «коротких дней», а лечение строится как управляемый медицинский процесс: сначала — измерения, затем — точная коррекция, после — режим и поддержка. Мы приезжаем без символики, используем кодовые профили, нейтральные формулировки в документах и защищённые каналы связи, чтобы сохранить приватность пациента и его семьи.
Исследовать вопрос подробнее – https://narcolog-na-dom-sochi00.ru/narkolog-na-dom-adler
EdwardBof
23 Oct 25 at 6:14 pm
Everyone loves what you guys tend to be up too. Such clever work and coverage!
Keep up the amazing works guys I’ve added you guys to my personal blogroll.
mgmarket
23 Oct 25 at 6:14 pm
ranking seo [url=https://www.reiting-seo-kompaniy.ru]ranking seo[/url] .
reiting seo kompanii_gkon
23 Oct 25 at 6:14 pm
phonenumbers.pw – On mobile it performs perfectly, scales smoothly with no errors.
Delcie Krishun
23 Oct 25 at 6:14 pm
Жесть!
Tradingfinder has developed a wide range of tradingview indicators, which you have the opportunity to use for free. Enter a valid email address, set a strong access code (must contain uppercase and lowercase letters, amount and symbols), [url=https://web-binarium.org/binarium-trade-online-trading-platform-review-2025/]https://web-binarium.org/binarium-trade-online-trading-platform-review-2025/[/url] in binarium and select own currency.
Eddiezef
23 Oct 25 at 6:16 pm