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/bs_1xbet/29
https://t.me/bs_1xbet/10
24 Oct 25 at 12:18 pm
1xbet giri? g?ncel [url=http://www.1xbet-7.com]http://www.1xbet-7.com[/url] .
1xbet_wdol
24 Oct 25 at 12:19 pm
one x bet [url=https://1xbet-giris-3.com]https://1xbet-giris-3.com[/url] .
1xbet giris_mjMi
24 Oct 25 at 12:20 pm
https://rc.forum24.ru/?1-13-0-00004446-000-0-0-1757494574
RichardWet
24 Oct 25 at 12:24 pm
1 x bet [url=http://www.1xbet-giris-10.com]1 x bet[/url] .
1xbet giris_vwka
24 Oct 25 at 12:26 pm
1xbet g?ncel adres [url=www.1xbet-giris-8.com]1xbet g?ncel adres[/url] .
1xbet giris_kgPn
24 Oct 25 at 12:26 pm
кто нибудь работает медсестрой по купленному диплому [url=https://www.frei-diplom14.ru]https://www.frei-diplom14.ru[/url] .
Diplomi_jloi
24 Oct 25 at 12:27 pm
красноярск купить диплом техникума [url=frei-diplom11.ru]красноярск купить диплом техникума[/url] .
Diplomi_jjsa
24 Oct 25 at 12:28 pm
1xbet t?rkiye [url=www.1xbet-9.com]1xbet t?rkiye[/url] .
1xbet_xjSn
24 Oct 25 at 12:29 pm
https://rosslestnica.ru/
Victorcrype
24 Oct 25 at 12:29 pm
1xbet lite [url=https://1xbet-giris-9.com]1xbet lite[/url] .
1xbet giris_uoon
24 Oct 25 at 12:30 pm
1 xbet [url=http://www.1xbet-giris-10.com]1 xbet[/url] .
1xbet giris_faka
24 Oct 25 at 12:30 pm
быстрая доставка однако тут))) https://krasnyluchzo.ru Качество вышка, доставка до вашего города обговаривается индивидуально с ТС!
Louismes
24 Oct 25 at 12:30 pm
https://rosslestnica.ru/
Victorcrype
24 Oct 25 at 12:31 pm
Write more, thats all I have to say. Literally, it seems as though you relied on the video to
make your point. You clearly know what youre talking about, why throw away your
intelligence on just posting videos to your blog when you could be
giving us something informative to read?
lawsondozc510706.wikisona.com
24 Oct 25 at 12:31 pm
1x lite [url=https://1xbet-giris-7.com/]1xbet-giris-7.com[/url] .
1xbet giris_daKn
24 Oct 25 at 12:32 pm
Hello there! I could have sworn I’ve been to your blog before but after looking at some of the posts I realized it’s new to me.
Regardless, I’m definitely delighted I found it and I’ll be book-marking it and
checking back frequently!
toto togel online
24 Oct 25 at 12:33 pm
1xbet resmi giri? [url=http://1xbet-giris-3.com/]http://1xbet-giris-3.com/[/url] .
1xbet giris_clMi
24 Oct 25 at 12:34 pm
Мы не используем универсальную «капельницу». Схема собирается из модулей под ведущие жалобы. Медицинские шаги всегда сочетаются с нефраком опорами — свет, тишина, вода малыми глотками, дыхание, — потому что среда усиливает действие препаратов и позволяет держать дозы ниже.
Узнать больше – [url=https://narkolog-na-dom-saratov0.ru/]нарколог на дом цены[/url]
RolandAnatt
24 Oct 25 at 12:34 pm
https://лестницы-в-москве.рф
TravisGaf
24 Oct 25 at 12:34 pm
https://лестницы-в-москве.рф
TravisGaf
24 Oct 25 at 12:36 pm
1xbet mobil giri? [url=www.1xbet-9.com/]www.1xbet-9.com/[/url] .
1xbet_uySn
24 Oct 25 at 12:39 pm
При этом многие ученые, как пишет CNN,
говорят о вероятности нового глобального катаклизма,
который скажется на климате, экономике и
геополитической ситуации во всем мире.
вулкан казахстан
24 Oct 25 at 12:39 pm
https://rosslestnica.ru/
Victorcrype
24 Oct 25 at 12:41 pm
1xbet tr giri? [url=http://1xbet-giris-9.com]http://1xbet-giris-9.com[/url] .
1xbet giris_ieon
24 Oct 25 at 12:41 pm
https://t.me/s/bs_1xbet/19
https://t.me/s/bs_1xbet/35
24 Oct 25 at 12:42 pm
1xbet [url=http://1xbet-giris-10.com/]1xbet[/url] .
1xbet giris_enka
24 Oct 25 at 12:42 pm
Join the winning side today by activating your special https://vhearts.net/forums/thread/16527/. It’s your ticket to exciting sports bets and huge casino prizes.
Justincit
24 Oct 25 at 12:42 pm
The directives largely roll back efforts made over the last decade attempting to eradicate toxic culture in the military, both to decrease harmful behaviors like harassment, but also to meet practical needs of getting people in uniform and keeping them there longer as the military branches faced years of struggles filling the ranks.
[url=https://kra-44.ru/]kra44 cc[/url]
Many major reforms were described by the officials who implemented them as driven by that need; when former Defense Secretary Ash Carter opened up combat roles to women in 2015, he said the military “cannot afford to cut ourselves off from half the country’s talents and skills” if it wanted to succeed in national defense.
[url=https://kra–43-cc.ru/]kra40[/url]
And while the military had made changes in recent years in an attempt to lessen instances of harassment, discrimination or toxic leadership by creating reporting mechanisms so that troops would come forward, Hegseth said those efforts went too far and were undercutting commanders.
“The definition of ‘toxic’ has been turned upside down, and we’re correcting that,” Hegseth vowed on Tuesday, adding that the Defense Department would be undertaking a review of words like “hazing” and “bullying” which he said had been “weaponized.”
kra42 cc
https://apteka-lenina8.ru/kra42cc
ClydeBlomo
24 Oct 25 at 12:42 pm
https://www.floristic.ru/forum/groups/moskva-d1318-svetoprozrachnye-alyuminievye-konstrukcii.html#gmessage1870
RichardWet
24 Oct 25 at 12:42 pm
https://t.me/s/bs_1xbet/6
https://t.me/bs_1xbet/13
24 Oct 25 at 12:43 pm
http://devichnik.su/forum/39-26829-1
RichardWet
24 Oct 25 at 12:44 pm
1xbet turkey [url=www.1xbet-4.com/]www.1xbet-4.com/[/url] .
1xbet_hlol
24 Oct 25 at 12:44 pm
https://лестницы-в-москве.рф
TravisGaf
24 Oct 25 at 12:46 pm
1xbet guncel [url=http://1xbet-7.com]http://1xbet-7.com[/url] .
1xbet_xbol
24 Oct 25 at 12:47 pm
https://t.me/bs_1xbet/26
https://t.me/bs_1xbet/12
24 Oct 25 at 12:48 pm
https://t.me/bs_1xbet/17
https://t.me/s/bs_1xbet/29
24 Oct 25 at 12:49 pm
1xbet mobi [url=https://1xbet-giris-7.com/]1xbet-giris-7.com[/url] .
1xbet giris_leKn
24 Oct 25 at 12:51 pm
1xbet giri? linki [url=http://www.1xbet-giris-10.com]1xbet giri? linki[/url] .
1xbet giris_wkka
24 Oct 25 at 12:51 pm
Just wish to say your article is as astonishing. The clarity in your post is simply cool and i can assume you’re an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.
БК Париматч КЗ
Dichaelwaw
24 Oct 25 at 12:51 pm
Target is in trouble. And while it’s easy to get lost in the company’s recent (poor) handling of American culture war narratives that cast it as too “woke” or too willing to cave to online fascists, the root of Target’s problems runs deep.
[url=https://tripsca43.win]tripscan top[/url]
Don’t get me wrong – the massive consumer boycotts from Black organizers have done damage. And there are probably folks on the far right who think even Target’s toned-down, overwhelmingly beige Pride merch this year was still too loud.
https://tripsca43.win
трип скан
But its stock is in the gutter and sales have been falling for two years because of good ol’ business fundamentals. It overstocked. It lost the pulse of its customers. It went up against Amazon Prime with… actually, does anyone know what Target’s Amazon Prime competitor is called?
The brand we petite bourgeoisie once playfully referred to as Tar-zhay has lost its spark. The company reported a decline in sales for a third-straight quarter, part of a broader trend of falling or flat sales for two years. Employees have lost confidence in the company’s direction. And 2025 has been a particularly rough financially, as Black shoppers organized a boycott over Target’s decision to cave to right-wing pressure on diverse hiring goals.
Shares were down 10% Wednesday.
It’s not to say the new guy, Michael Fiddelke, is unqualified. He’s been at Target since he started as an intern more than 20 years ago, after all. But Wall Street is clearly concerned that Target’s leadership is underestimating the severity of the need for a significant change— just as President Donald Trump’s tariffs on imported goods threaten the entire retail industry.
Appointing a company lifer “does not necessarily remedy the problems of entrenched groupthink and the inward-looking mindset that have plagued Target for years,” Neil Saunders, an analyst at GlobalData Retail, said in a note to clients Wednesday.
Missing the mark
In its 2010s heyday, Target became a go-to for consumers who liked a bargain but didn’t necessarily like bargain-hunting. The shelves felt well-curated. You’d go to Target because it had one thing you needed and 12 things you didn’t know you needed. It was stocked with Millennial cringe long before Gen Z gave us the term Millennial cringe.
Target’s sales held strong through the pandemic as remote workers set up home offices and stocked up on essentials. Months of lockdown also benefited the store as people began refreshing their spaces because they didn’t really have much else to do and they were staring at the same walls all the time.
Michaelgidge
24 Oct 25 at 12:51 pm
The Oktoberfest beer festival in Munich will remain shut on Wednesday until at least 5 pm (1500 GMT) after police said they discovered explosives in a residential building in the north of the city that caught fire and left one person dead.
[url=https://at-kra39cc.ru]kra39 cc[/url]
As part of a major operation that police earlier said posed no danger to the public, special forces were investigating an area in the north of Munich where Bild newspaper and multiple other reports said shots and explosions had been heard.
[url=https://kra37сc-c.ru]kra39 at[/url]
Police said the residential building had been deliberately set on fire in a family dispute and one person who was found there had died and another was missing, but not believed to be in danger.
[url=https://kra37с-cc.ru]kra37 cc[/url]
Special forces had to be brought in to defuse booby traps found in the building, according to police.
“We are currently investigating all possibilities. Possible connections to other locations in Munich are being examined, including the Theresienwiese (where the Oktoberfest is located),” said Munich police on the WhatsApp messaging service.
“For this reason, the opening of the festival grounds has been delayed,” police added.
kra39 сс
https://kra37с-cc.ru
Rodneynen
24 Oct 25 at 12:53 pm
https://rosslestnica.ru/
Victorcrype
24 Oct 25 at 12:54 pm
https://assa0.myqip.ru/?1-1-0-00003606-000-0-0-1757494388
RichardWet
24 Oct 25 at 12:55 pm
1xbet [url=https://www.1xbet-giris-8.com]1xbet[/url] .
1xbet giris_rePn
24 Oct 25 at 12:56 pm
https://businessandfinance.com
ArnoldKam
24 Oct 25 at 12:58 pm
The scale of these recent attacks means Ukraine needs any help it can get to minimize the impacts – and volunteers are playing an increasingly important role in the defensive mix.
[url=https://kra49cc.com ]kra45 сс[/url]
Civilians are forming units tasked with shooting down smaller drones with machine guns or, most recently, specially developed interceptor drones.
[url=https://kra47.at-kra47.cc ]kra49 at[/url]
The chief of staff of one of Kyiv’s volunteer formation legions, Andriy, whose call-sign is Stolyar, said his unit is composed of people from all walks of life – from construction workers to businessmen to poets.
He told CNN the training for his legion lasts for about six weeks and includes basic knowledge, simulator practice and topography lessons. Andriy asked for his last name not to be published for security reasons.
“A person must understand how to operate an aircraft. Drones are becoming increasingly complex – this is aviation, and it requires constant attention, knowledge, and skills,” he said.
kra41
https://kra44.at-kra44.cc
Edwardheicy
24 Oct 25 at 12:58 pm
https://лестницы-в-москве.рф
TravisGaf
24 Oct 25 at 1:00 pm
где купить диплом колледжа в москве [url=https://www.frei-diplom11.ru]https://www.frei-diplom11.ru[/url] .
Diplomi_hisa
24 Oct 25 at 1:02 pm
1xbet giri? g?ncel [url=https://www.1xbet-giris-10.com]1xbet giri? g?ncel[/url] .
1xbet giris_hqka
24 Oct 25 at 1:02 pm