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!
1xbet guncel [url=https://www.1xbet-10.com]https://www.1xbet-10.com[/url] .
1xbet_vmea
26 Oct 25 at 11:16 am
Je suis captive par Olympe Casino, il procure une experience harmonieuse. Le catalogue est riche en melodies, proposant des jeux de table glorieux. Avec des depots rapides. Le support client est olympien, avec une aide precise. Les gains arrivent sans delai, parfois des recompenses supplementaires seraient eternelles. En bref, Olympe Casino garantit un plaisir divin pour les amateurs de sensations mythiques ! En bonus la navigation est simple comme un oracle, ce qui rend chaque session plus celeste. Particulierement captivant les tournois reguliers pour la competition, renforce le sentiment de communaute.
https://olympefr.com/|
ApolloLyraC6zef
26 Oct 25 at 11:18 am
Кто делал дератизация цена холодным туманом? Эффективно ли?
дезинфекция цена
KennethceM
26 Oct 25 at 11:18 am
1xbet tr giri? [url=https://www.1xbet-13.com]https://www.1xbet-13.com[/url] .
1xbet_apKa
26 Oct 25 at 11:18 am
клиника наркологии [url=www.narkologicheskaya-klinika-24.ru]клиника наркологии[/url] .
narkologicheskaya klinika_dtSr
26 Oct 25 at 11:19 am
1xbet mobil giri? [url=www.1xbet-16.com/]1xbet mobil giri?[/url] .
1xbet_taOn
26 Oct 25 at 11:19 am
1xbetgiri? [url=www.1xbet-12.com/]www.1xbet-12.com/[/url] .
1xbet_jhSr
26 Oct 25 at 11:22 am
We’re a group of volunteers and opening a brand
new scheme in our community. Your website offered us with helpful info
to work on. You’ve done an impressive task and our entire neighborhood might be grateful to you.
My webpage; zinnat02
zinnat02
26 Oct 25 at 11:23 am
https://www.edufex.com/forums/discussion/introductions/play-smarter-with-code-promo-1xbet-cote-divoireq
sdlebdq
26 Oct 25 at 11:24 am
kraken vpn
kraken ссылка
JamesDaync
26 Oct 25 at 11:27 am
mostbet kg [url=http://mostbet12031.ru]http://mostbet12031.ru[/url]
mostbet_kg_lfMa
26 Oct 25 at 11:31 am
Где дешево уничтожение рыжих тараканов? Бюджет ограничен.
санэпидемстанция
KennethceM
26 Oct 25 at 11:32 am
1xbet lite [url=www.1xbet-16.com/]1xbet lite[/url] .
1xbet_xhOn
26 Oct 25 at 11:32 am
1xbet yeni adresi [url=https://1xbet-13.com/]1xbet yeni adresi[/url] .
1xbet_xrKa
26 Oct 25 at 11:32 am
Товар тоже на 5/5 (только с концетрацией мало 1 к 5 или 1 к 7 дальше держит не долго) купить Мефедрон, Бошки, Марихуану Удачных закупок
ManuelBrege
26 Oct 25 at 11:34 am
Где купить Лсд в Гусиноозёрске?Нашел на https://mentaragua.ru
– адекватные отзывы и цены. Есть курьерская доставка. Кто-то пробовал их товаром? Интересует качество?
Stevenref
26 Oct 25 at 11:34 am
bahis sitesi 1xbet [url=http://www.1xbet-14.com]bahis sitesi 1xbet[/url] .
1xbet_fyet
26 Oct 25 at 11:35 am
1 xbet giri? [url=https://1xbet-12.com]https://1xbet-12.com[/url] .
1xbet_gmSr
26 Oct 25 at 11:37 am
медтехника [url=medicinskaya-tehnika.ru]medicinskaya-tehnika.ru[/url] .
medicinskaya tehnika_maEi
26 Oct 25 at 11:37 am
1x bet giri? [url=https://1xbet-10.com/]1xbet-10.com[/url] .
1xbet_rnea
26 Oct 25 at 11:38 am
поставщик медицинского оборудования [url=www.medoborudovanie-postavka.ru]поставщик медицинского оборудования[/url] .
postavka medicinskogo oborydovaniya_hwsn
26 Oct 25 at 11:38 am
The most important is here: https://primorskival.si
MichaelBoype
26 Oct 25 at 11:39 am
Top content here: https://www.wisla-plock.pl
Stanleyecoma
26 Oct 25 at 11:39 am
Hi! I just wanted to ask if you ever have any trouble with hackers?
My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no data backup.
Do you have any methods to stop hackers?
88aas.com
26 Oct 25 at 11:40 am
Thank you for sharing your info. I really appreciate your
efforts and I will be waiting for your next write ups thank you once
again.
custom dog meal plans
26 Oct 25 at 11:41 am
The best collected for you: https://www.panamericano.us
MartinCoF
26 Oct 25 at 11:42 am
It’s in reality a nice and helpful piece of information. I am happy
that you shared this helpful info with us. Please stay us informed like this.
Thank you for sharing.
Ev99
26 Oct 25 at 11:43 am
birxbet [url=http://www.1xbet-16.com]birxbet[/url] .
1xbet_nrOn
26 Oct 25 at 11:43 am
кракен сайт
кракен vk2
JamesDaync
26 Oct 25 at 11:43 am
xbet giri? [url=www.1xbet-14.com/]www.1xbet-14.com/[/url] .
1xbet_poet
26 Oct 25 at 11:44 am
Interesting blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple tweeks would really make my blog
shine. Please let me know where you got your theme.
Thank you
trang chủ 88vv
26 Oct 25 at 11:46 am
1xbet [url=https://www.1xbet-13.com]1xbet[/url] .
1xbet_ypKa
26 Oct 25 at 11:46 am
1xbet t?rkiye giri? [url=http://1xbet-12.com]1xbet t?rkiye giri?[/url] .
1xbet_wqSr
26 Oct 25 at 11:46 am
https://e-bookmarks.com/story6161061/meilleur-code-promo-1xbet-s%C3%A9n%C3%A9gal
zvsfrul
26 Oct 25 at 11:48 am
Клопы в мебели? дезинфекция после умерших поможет.
вывести тараканов
KennethceM
26 Oct 25 at 11:49 am
Great post. I will be experiencing many of these issues as well..
nhà cái 88aa
26 Oct 25 at 11:50 am
больница наркологическая [url=http://narkologicheskaya-klinika-23.ru]http://narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_kvet
26 Oct 25 at 11:50 am
После обработка от тараканов стоимость дом безопасный для детей.
уничтожение клопов в мебели
KennethceM
26 Oct 25 at 11:51 am
Since the admin of this site is working, no uncertainty very quickly it will be well-known, due to its feature contents.
вход через зеркало kra42 at
OLaneDrync
26 Oct 25 at 11:51 am
Navigating the bridge between traditional finance and the digital asset world has always
been a logistical nightmare for many in the GSA community.
The exorbitant fees and clunky user interfaces 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 remarkably fluid gateway that effortlessly
handles both fiat and cryptocurrency banking. Imagine managing treasury
across USD, EUR, and a vast selection of major digital assets—all from
a streamlined platform. Their focus on regulatory compliance means
you can meet compliance standards. A brief comment can’t possibly do justice to the full scope of their
capabilities, especially their advanced tools for corporate accounts.
To get a complete picture of how Paybis is building the future of finance, 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.
Make sure to check out the piece to see if their platform aligns
with your specific use-case. It’s a comprehensive overview for anyone in our field looking to leverage modern fintech.
The link is in the main post—go give it a read.
article
26 Oct 25 at 11:51 am
1x lite [url=www.1xbet-10.com]www.1xbet-10.com[/url] .
1xbet_wqea
26 Oct 25 at 11:55 am
kraken vk4
кракен официальный сайт
JamesDaync
26 Oct 25 at 11:55 am
1xbet yeni giri? [url=https://1xbet-16.com/]1xbet yeni giri?[/url] .
1xbet_zkOn
26 Oct 25 at 11:58 am
You don’t need to wait on a long period to obtain fresh verified URLs though.
Here is my web site … Merri
Merri
26 Oct 25 at 12:01 pm
Ищу уничтожение тараканов холодным туманом с выездом в область.
уничтожение моли в шкафу
KennethceM
26 Oct 25 at 12:02 pm
bloemhill – I’ll keep an eye out for promotions, might pick up something for a gift.
Eleni Garwood
26 Oct 25 at 12:04 pm
mostbet kg [url=mostbet12032.ru]mostbet12032.ru[/url]
mostbet_kg_nkmt
26 Oct 25 at 12:04 pm
I got this web page from my buddy who told me regarding this web site and now this time I am visiting this web page and reading very informative posts at this place.
Ependraxa Review
26 Oct 25 at 12:05 pm
Hello everybody, here every one is sharing these kinds of familiarity, so it’s fastidious to read this blog, and I used
to go to see this weblog all the time.
My web site :: zinnat02
zinnat02
26 Oct 25 at 12:05 pm
Terrific article! This is the kind of info that should be shared across the net.
Shame on the seek engines for no longer positioning this submit upper!
Come on over and discuss with my website . Thanks =)
cfd-brand
26 Oct 25 at 12:06 pm