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!
the minimum withdrawal amount is 50 euro at that time as the maximum withdrawal amount varies: 5,000 eur per day, [url=http://hasly-photo.cz/2017/09/15/stay-with-me/]http://hasly-photo.cz/2017/09/15/stay-with-me/[/url] per week and 20 thousand eur per month.
JenniferSwece
25 Oct 25 at 5:37 pm
ставки кыргызстан [url=www.mostbet12032.ru]ставки кыргызстан[/url]
mostbet_kg_simt
25 Oct 25 at 5:37 pm
1 xbet giri? [url=https://1xbet-15.com]https://1xbet-15.com[/url] .
1xbet_icpl
25 Oct 25 at 5:37 pm
Howdy! I’m at work browsing your blog from
my new iphone 3gs! Just wanted to say I love reading
your blog and look forward to all your posts!
Carry on the outstanding work!
Sigil Finthora Reseña
25 Oct 25 at 5:40 pm
I read this piece of writing completely concerning the resemblance
of hottest and earlier technologies, it’s remarkable article.
Immediate Fastx TEST
25 Oct 25 at 5:40 pm
Hello my friend! I wish to say that this article is amazing, nice
written and come with approximately all important infos.
I’d like to peer more posts like this .
Syair Sdy
25 Oct 25 at 5:40 pm
http://lenotoplenie.ru лучшие предложения для новых игроков и постоянных пользователей
CollinDwets
25 Oct 25 at 5:41 pm
one x bet [url=http://1xbet-12.com/]http://1xbet-12.com/[/url] .
1xbet_zdSr
25 Oct 25 at 5:42 pm
Good post. I learn something new and challenging on sites I stumbleupon everyday.
It’s always helpful to read through content from other authors and
use a little something from other websites.
Cách lật đổ chính quyền
25 Oct 25 at 5:46 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://sefy.ru/kra40-cc.html]kra40 сс[/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://ckmosstroy.ru/kra41-cc]kra47 cc[/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.”
kra48 cc
https://kra-42.ru/kra42cc
ClydeBlomo
25 Oct 25 at 5:49 pm
кракен Россия
kraken android
JamesDaync
25 Oct 25 at 5:51 pm
как купить диплом техникума в красноярске [url=http://www.frei-diplom8.ru]как купить диплом техникума в красноярске[/url] .
Diplomi_dzsr
25 Oct 25 at 5:51 pm
купить диплом о высшем образовании с занесением в реестр владивосток [url=http://frei-diplom2.ru/]http://frei-diplom2.ru/[/url] .
Diplomi_lkEa
25 Oct 25 at 5:52 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://at-kra47.cc ]kra40[/url]
Civilians are forming units tasked with shooting down smaller drones with machine guns or, most recently, specially developed interceptor drones.
[url=https://kra41.net ]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.
kra48 at
https://kra41cc.net
Edwardheicy
25 Oct 25 at 5:52 pm
Срочно нужна санобработка, тараканы достали!
вывести тараканов
KennethceM
25 Oct 25 at 5:52 pm
Fastidious replies in return of this query with solid arguments and telling all concerning that.
Paito Warna Carolina Day Tahun 2025
25 Oct 25 at 5:52 pm
kraken 2025
кракен вход
JamesDaync
25 Oct 25 at 5:53 pm
1xbet giri? 2025 [url=http://1xbet-12.com/]1xbet giri? 2025[/url] .
1xbet_blSr
25 Oct 25 at 5:53 pm
Вызов обработка от клопов стоимость на выходные возможен?
уничтожение рыжих тараканов
KennethceM
25 Oct 25 at 5:54 pm
Discover Riyo Gems, a trusted 925 sterling silver jewelry
manufacturer in Jaipur, India. We create eco-friendly handmade gemstone jewelry, custom designs, and wholesale gemstone supply.
Work with our trusted factory for finest silver,
semi-precious, and loose gemstone jewelry production.
Silver Gemstones Jewelry
25 Oct 25 at 5:54 pm
купить диплом в ставрополе [url=http://rudik-diplom4.ru]купить диплом в ставрополе[/url] .
Diplomi_kuOr
25 Oct 25 at 5:54 pm
Цена на дезинфекция помещений от вирусов адекватная, результат супер.
уничтожение блох
KennethceM
25 Oct 25 at 5:56 pm
J’adore l’atmosphere dynamique de Spinit Casino, ca offre un plaisir veloce. Le catalogue est riche et varie, avec des slots aux designs veloces. Amplifiant le plaisir de jeu. Le service est disponible 24/7, offrant des reponses claires. Les paiements sont securises et rapides, bien que des offres plus genereuses seraient veloces. Dans l’ensemble, Spinit Casino est un incontournable pour les joueurs pour les joueurs en quete d’excitation ! Par ailleurs le site est rapide et attractif, ajoute une touche de vitesse. A souligner les evenements communautaires engageants, assure des transactions fiables.
casinospinitfr.com|
WheelWhisperB3zef
25 Oct 25 at 5:56 pm
1xbet resmi sitesi [url=https://www.1xbet-16.com]https://www.1xbet-16.com[/url] .
1xbet_jjOn
25 Oct 25 at 5:56 pm
At Playamo gaming site, players enjoy an outstanding gaming experience with over 3,000 superior slots, casino classics, and real dealer options from top gaming companies. Playing advanced video slots, planning at card games, or savoring real live casino entertainment—the platform features something for all participant. The portal boasts an polished, simple design that delivers fluid browsing on mobile and desktop, providing you play enjoyment whenever and wherever.
Playamo casino
AlfredLog
25 Oct 25 at 5:57 pm
купить диплом московского торгово экономического техникума [url=www.frei-diplom8.ru/]купить диплом московского торгово экономического техникума[/url] .
Diplomi_zzsr
25 Oct 25 at 5:58 pm
Отзывы о уничтожение клопов цена положительные, попробуем.
санэпидемстанция
KennethceM
25 Oct 25 at 5:58 pm
Je suis completement transporte par BassBet Casino, il cree une ambiance de concert. Les titres sont d’une richesse envoutante, comprenant des jeux adaptes aux cryptos. Boostant votre mise de depart. Le support client est au top, toujours pret a chanter. Les transactions sont fiables, parfois quelques tours gratuits en plus seraient top. En resume, BassBet Casino garantit un fun non-stop pour les passionnes de jeux modernes ! En plus le site est rapide et captivant, booste le plaisir de jouer. A souligner les evenements communautaires dynamiques, offre des recompenses continues.
https://bassbetcasinopromocodefr.com/|
SoulSpinnerJ2zef
25 Oct 25 at 5:58 pm
купить диплом пту с занесением в реестр [url=https://www.frei-diplom2.ru]купить диплом пту с занесением в реестр[/url] .
Diplomi_lcEa
25 Oct 25 at 5:58 pm
birxbet giri? [url=https://1xbet-15.com/]1xbet-15.com[/url] .
1xbet_tupl
25 Oct 25 at 5:58 pm
1xbet giri? adresi [url=https://1xbet-14.com/]1xbet giri? adresi[/url] .
1xbet_peet
25 Oct 25 at 5:59 pm
J’ai une passion rythmique pour BassBet Casino, il procure une experience harmonieuse. Le catalogue est riche et varie, avec des slots aux designs rythmiques. Amplifiant le plaisir de jeu. Les agents repondent comme un solo, toujours pret a jammer. Les gains arrivent sans delai, cependant des bonus plus varies seraient un riff. Dans l’ensemble, BassBet Casino vaut une jam session pour les passionnes de jeux modernes ! En bonus la navigation est simple et rythmee, donne envie de prolonger l’aventure. Egalement appreciable les paiements securises en crypto, qui booste l’engagement.
https://bassbetcasinobonusfr.com/|
RiverRiffE7zef
25 Oct 25 at 6:00 pm
купить проведенный диплом [url=http://frei-diplom2.ru/]купить проведенный диплом[/url] .
Diplomi_zhEa
25 Oct 25 at 6:02 pm
Je suis absolument captive par Monte Cryptos Casino, c’est une plateforme qui pulse comme un reseau blockchain. Les options sont vastes comme un ledger, offrant des sessions en direct immersives. Boostant votre capital initial. Le suivi est d’une efficacite absolue, offrant des solutions claires. Les retraits sont rapides comme une transaction, cependant des recompenses supplementaires seraient ideales. Dans l’ensemble, Monte Cryptos Casino est un must pour les fans de blockchain pour les joueurs en quete d’innovation ! Ajoutons que le design est moderne et captivant, ajoute une touche de sophistication. Egalement cool les paiements securises en BTC/ETH, garantit des transactions fiables.
Aller plus loin|
QuantumByteS5zef
25 Oct 25 at 6:02 pm
Je suis accro a Spinit Casino, ca plonge dans un monde de legendes. Les options sont vastes comme un grimoire, avec des slots aux designs enchantes. Avec des depots instantanes. Les agents repondent comme par magie, toujours pret a transformer. Les gains arrivent sans delai, cependant des offres plus genereuses seraient enchantees. En bref, Spinit Casino vaut une lecture magique pour les joueurs en quete d’excitation ! De plus la plateforme est visuellement envoutante, facilite une immersion totale. A souligner le programme VIP avec des niveaux exclusifs, propose des avantages personnalises.
https://spinitcasinobonusfr.com/|
FairyWhirlG8zef
25 Oct 25 at 6:03 pm
J’ai une passion ardente pour Monte Cryptos Casino, c’est une plateforme qui pulse comme un reseau blockchain. Les options sont vastes comme un ledger, comprenant des jeux optimises pour les cryptos. Avec des depots crypto rapides. Les agents repondent avec une vitesse fulgurante, toujours pret a decoder. Les retraits sont rapides comme une transaction, neanmoins plus de promos regulieres dynamiseraient l’experience. Pour conclure, Monte Cryptos Casino offre une experience inoubliable pour les joueurs en quete d’innovation ! A noter le design est moderne et captivant, donne envie de prolonger l’aventure. Un avantage notable les evenements communautaires decentralises, propose des avantages uniques.
Regarder de prГЁs|
GlitchWaveR2zef
25 Oct 25 at 6:06 pm
1x bet giri? [url=http://1xbet-16.com/]1x bet giri?[/url] .
1xbet_vwOn
25 Oct 25 at 6:06 pm
Excellent article! We are linking to this great content on our website.
Keep up the good writing.
paito sdy lotto
25 Oct 25 at 6:07 pm
kraken darknet
kraken онлайн
JamesDaync
25 Oct 25 at 6:08 pm
Excellent post. I was checking continuously this blog and I am impressed!
Very useful info specifically the last part 🙂 I care for
such information a lot. I was seeking this certain information for
a very long time. Thank you and best of luck.
LarevixInvest
25 Oct 25 at 6:09 pm
https://mediuomo.shop/# trattamento ED online Italia
JamesSlilk
25 Oct 25 at 6:09 pm
Цены на санитарная обработка разумные, качество на высоте.
уничтожение клопов с гарантией
KennethceM
25 Oct 25 at 6:10 pm
Je suis absolument seduit par Monte Cryptos Casino, c’est une plateforme qui vibre comme un reseau blockchain. Les options sont vastes comme un reseau, incluant des paris en direct dynamiques. Le bonus d’accueil est eclatant. L’assistance est efficace et professionnelle, garantissant un service de pointe. Les paiements sont securises et fluides, parfois des recompenses supplementaires seraient ideales. En bref, Monte Cryptos Casino vaut une exploration virtuelle pour les adeptes de jeux modernes ! A noter le design est moderne et captivant, amplifie le plaisir de jouer. Particulierement captivant les paiements securises en BTC/ETH, garantit des transactions fiables.
Apprendre la mГ©thode|
DigitalDriftZ3zef
25 Oct 25 at 6:10 pm
Привет старичок https://denovar.ru сделал заказ ,оплатил 🙂 теперь жду трека и посыля с нетерпением 🙂 по общению продаван понравился все ровно обьяснил че да как . как придет опробую оставлю отзыв окончательный ,пока что все ровно )
LeonardHOX
25 Oct 25 at 6:11 pm
These are really impressive ideas in about blogging.
You have touched some pleasant points here. Any way
keep up wrinting.
universitas di bandung
25 Oct 25 at 6:11 pm
The best click here: https://www.gagolga.de
AlfonsoMycle
25 Oct 25 at 6:15 pm
Top recommendations: https://possible11.com
Thomasviday
25 Oct 25 at 6:15 pm
Поделитесь отзывами о дезинфекция после потопа! Как качество и цена?
дезинфекция автомобилей
KennethceM
25 Oct 25 at 6:15 pm
1xbetgiri? [url=https://www.1xbet-12.com]https://www.1xbet-12.com[/url] .
1xbet_fcSr
25 Oct 25 at 6:16 pm
All on this topic – here: https://03ekb.ru
Trentpeedo
25 Oct 25 at 6:16 pm