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!
1xbwt giri? [url=https://1xbet-13.com]https://1xbet-13.com[/url] .
1xbet_mbKa
26 Oct 25 at 9:04 am
Most summer season anthems earn their day within the sun for their sing-a-lengthy factor,
however “Wipe Out” won its claim to fame for a nearly 3-minute guitar instrumental that everybody could
surf-a-lengthy to.
viagra que contiene
26 Oct 25 at 9:05 am
1 x bet giri? [url=www.1xbet-12.com]www.1xbet-12.com[/url] .
1xbet_tbSr
26 Oct 25 at 9:07 am
birxbet [url=http://1xbet-17.com]birxbet[/url] .
1xbet_mbpl
26 Oct 25 at 9:08 am
mostbet skachat [url=mostbet12031.ru]mostbet12031.ru[/url]
mostbet_kg_bnMa
26 Oct 25 at 9:10 am
All Materials on the Topic: https://www.jec.qa
Jesseskevy
26 Oct 25 at 9:11 am
mostbet kg [url=http://mostbet12032.ru]http://mostbet12032.ru[/url]
mostbet_kg_fqmt
26 Oct 25 at 9:12 am
Tisel Technics — официальный дистрибьютор складской техники с одним из самых широких каталогов: от ручных и самоходных тележек до ричтраков, электрических и дизельных погрузчиков. 197 моделей, тест-драйв на вашем складе, аренда и лизинг, подбор запчастей и сервис в 53 сертифицированных центрах по России. Узнайте детали, акции и условия гарантии на https://tiseltechnics.ru/ Компания предлагает расширенную гарантию до 4 лет и демонстрации по видеосвязи со склада.
jiwojiAboge
26 Oct 25 at 9:13 am
медицинский наркологический центр [url=http://narkologicheskaya-klinika-23.ru]http://narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_ozet
26 Oct 25 at 9:15 am
кракен клиент
kraken онлайн
JamesDaync
26 Oct 25 at 9:15 am
Only the Important Details: https://www.wisla-plock.pl
Miltonlic
26 Oct 25 at 9:15 am
1xbet giri? g?ncel [url=www.1xbet-12.com/]1xbet giri? g?ncel[/url] .
1xbet_ptSr
26 Oct 25 at 9:16 am
Hi colleagues, its wonderful article on the topic of teachingand completely
defined, keep it up all the time.
buôn bán nội tạng
26 Oct 25 at 9:17 am
1xbet guncel [url=https://1xbet-14.com]1xbet guncel[/url] .
1xbet_fuet
26 Oct 25 at 9:17 am
поставщик медоборудования [url=www.medoborudovanie-postavka.ru/]www.medoborudovanie-postavka.ru/[/url] .
postavka medicinskogo oborydovaniya_hfsn
26 Oct 25 at 9:17 am
1xbet ?ye ol [url=http://1xbet-13.com]http://1xbet-13.com[/url] .
1xbet_kjKa
26 Oct 25 at 9:18 am
mostbet.com вход [url=www.mostbet12031.ru]www.mostbet12031.ru[/url]
mostbet_kg_xjMa
26 Oct 25 at 9:18 am
Кто делал дератизация цена холодным туманом? Эффективно ли?
обработка от педикулеза
KennethceM
26 Oct 25 at 9:18 am
https://herengezondheid.com/# erectiepillen discreet bestellen
Hermanereli
26 Oct 25 at 9:19 am
birxbet [url=http://1xbet-10.com]http://1xbet-10.com[/url] .
1xbet_wrea
26 Oct 25 at 9:19 am
wonderful put up, very informative. I ponder why the other experts of this sector do not understand this.
You must proceed your writing. I am sure,
you have a huge readers’ base already!
Nicely done
26 Oct 25 at 9:21 am
мед оборудование [url=medicinskoe–oborudovanie.ru]мед оборудование[/url] .
medicinskoe oborydovanie_spei
26 Oct 25 at 9:22 am
1xbet t?rkiye [url=https://1xbet-10.com]1xbet t?rkiye[/url] .
1xbet_xdea
26 Oct 25 at 9:22 am
1x bet [url=http://1xbet-16.com]1x bet[/url] .
1xbet_hpOn
26 Oct 25 at 9:25 am
помощь нарколога [url=https://narkologicheskaya-klinika-23.ru]https://narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_jiet
26 Oct 25 at 9:25 am
1xbet resmi giri? [url=https://www.1xbet-12.com]https://www.1xbet-12.com[/url] .
1xbet_pxSr
26 Oct 25 at 9:27 am
mostbet kg [url=https://www.mostbet12032.ru]https://www.mostbet12032.ru[/url]
mostbet_kg_hymt
26 Oct 25 at 9:28 am
поставщик медоборудования [url=http://medoborudovanie-postavka.ru/]http://medoborudovanie-postavka.ru/[/url] .
postavka medicinskogo oborydovaniya_kfsn
26 Oct 25 at 9:28 am
1xbet ?yelik [url=https://1xbet-16.com]1xbet ?yelik[/url] .
1xbet_hhOn
26 Oct 25 at 9:28 am
Undeniably believe that which you stated. Your favorite justification appeared to be on the net
thee easiest thing to be awae of. I say to you, I certainly
gget irked while people think about worries that they plainly
do not know about. You managed to hit the nail upon the top as well as defined out
the whole thing without having side ffect , people can take a signal.
Will probably be bsck to get more. Thanks
vapepremiumuk
26 Oct 25 at 9:29 am
mostbet kg [url=https://mostbet12032.ru]https://mostbet12032.ru[/url]
mostbet_kg_ylmt
26 Oct 25 at 9:31 am
kraken qr code
кракен vk3
JamesDaync
26 Oct 25 at 9:33 am
I believe what you published made a ton of sense. However, think about this, what if you wrote a catchier post title?
I mean, I don’t want to tell you how to run your website,
however suppose you added something that grabbed people’s attention? I mean PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is a little plain. You might peek at Yahoo’s home
page and see how they create news headlines to grab people to click.
You might add a video or a related picture or two to grab readers interested about what you’ve got to
say. In my opinion, it would make your posts
a little livelier.
water heater installation
26 Oct 25 at 9:33 am
1xbet g?ncel adres [url=www.1xbet-10.com/]1xbet g?ncel adres[/url] .
1xbet_fbea
26 Oct 25 at 9:34 am
мостбет андроид [url=https://www.mostbet12031.ru]https://www.mostbet12031.ru[/url]
mostbet_kg_zoMa
26 Oct 25 at 9:35 am
1xbet giri? yapam?yorum [url=http://1xbet-12.com]http://1xbet-12.com[/url] .
1xbet_vkSr
26 Oct 25 at 9:35 am
поставщик медоборудования [url=http://medoborudovanie-postavka.ru/]http://medoborudovanie-postavka.ru/[/url] .
postavka medicinskogo oborydovaniya_grsn
26 Oct 25 at 9:36 am
1 x bet [url=http://www.1xbet-16.com]1 x bet[/url] .
1xbet_piOn
26 Oct 25 at 9:37 am
После дезинфекция помещений от вирусов мыши пропали, рад!
обработка от педикулеза
KennethceM
26 Oct 25 at 9:37 am
Клопы вернулись после дезинфекция медицинских учреждений, что делать?
обработка от блох в доме
KennethceM
26 Oct 25 at 9:38 am
It’s truly very difficult in this full of activity life to listen news
on TV, thus I simply use web for that purpose, and obtain the most recent news.
extra boost supplements
26 Oct 25 at 9:42 am
1xbet tr giri? [url=http://1xbet-12.com/]http://1xbet-12.com/[/url] .
1xbet_ftSr
26 Oct 25 at 9:42 am
бк мостбет [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_dumt
26 Oct 25 at 9:43 am
https://mannensapotek.shop/# MannensApotek
Hermanereli
26 Oct 25 at 9:43 am
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 constant friction and lack of integration between fiat and crypto platforms
can severely hinder operational efficiency. This is precisely
why the Paybis fintech platform is worth a closer look.
They aren’t just another crypto exchange; they’ve built a remarkably
fluid gateway that effortlessly handles both fiat and cryptocurrency banking.
Imagine sourcing liquidity 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 offerings, especially their advanced tools for high-volume traders.
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. Don’t just take my word for it check out the piece to see if their
platform aligns with your operational requirements. It’s a fantastic deep-dive for anyone in our field looking
to optimize their financial stack. The link is in the main post—go give it a read.
c7448732676575115077
26 Oct 25 at 9:43 am
bahis siteler 1xbet [url=https://www.1xbet-12.com]bahis siteler 1xbet[/url] .
1xbet_kzSr
26 Oct 25 at 9:44 am
анонимная наркологическая помощь в москве [url=narkologicheskaya-klinika-23.ru]narkologicheskaya-klinika-23.ru[/url] .
narkologicheskaya klinika_czet
26 Oct 25 at 9:45 am
1xbet t?rkiye [url=https://1xbet-16.com]1xbet t?rkiye[/url] .
1xbet_odOn
26 Oct 25 at 9:46 am
кракен обмен
кракен актуальная ссылка
JamesDaync
26 Oct 25 at 9:46 am
1 xbet [url=https://www.1xbet-14.com]1 xbet[/url] .
1xbet_nzet
26 Oct 25 at 9:47 am