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!
купить диплом с занесением в реестр оренбург [url=http://frei-diplom2.ru]купить диплом с занесением в реестр оренбург[/url] .
Diplomi_cnEa
25 Oct 25 at 7:01 pm
купить диплом строительного техникума [url=www.frei-diplom8.ru]купить диплом строительного техникума[/url] .
Diplomi_desr
25 Oct 25 at 7:02 pm
Сколько времени занимает уничтожение клопов холодным туманом?
дезинфекция школы
KennethceM
25 Oct 25 at 7:02 pm
joinourcreativeworld – Easy to navigate, found exactly what I was looking for.
Chester Grannum
25 Oct 25 at 7:03 pm
Спасибо за обработка от клопов! Всё чисто и безопасно.
вывести клопов
KennethceM
25 Oct 25 at 7:05 pm
What’s up colleagues, nice paragraph and good urging commented here, I am in fact
enjoying by these.
teslabahis
25 Oct 25 at 7:06 pm
1 xbet [url=https://www.1xbet-10.com]https://www.1xbet-10.com[/url] .
1xbet_wnea
25 Oct 25 at 7:08 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://ckmosstroy.ru/kra43-cc]kra43 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/kra43.cc]kra44 at[/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.”
kra49 сс
https://sefy.ru/kra41at.html
ClydeBlomo
25 Oct 25 at 7:09 pm
birxbet [url=www.1xbet-12.com]www.1xbet-12.com[/url] .
1xbet_leSr
25 Oct 25 at 7:09 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://kra–46.cc ]kra41[/url]
Civilians are forming units tasked with shooting down smaller drones with machine guns or, most recently, specially developed interceptor drones.
[url=https://kra–43.cc ]kra41 сс[/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.
kra45
https://kra–44.cc
Edwardheicy
25 Oct 25 at 7:11 pm
кракен обмен
кракен онлайн
JamesDaync
25 Oct 25 at 7:12 pm
https://dirstop.com/story25786195/code-promo-1xbet-paris-gratuit
iyhnscw
25 Oct 25 at 7:12 pm
Приобрести диплом ВУЗа поспособствуем. Купить диплом магистра в Кургане – [url=http://diplomybox.com/kupit-diplom-magistra-v-kurgane/]diplomybox.com/kupit-diplom-magistra-v-kurgane[/url]
Cazruwz
25 Oct 25 at 7:12 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-kra41cc.ru]kra37 at[/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://kra37a-cc.ru]kra38 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://at-kra41cc.ru]kra38 сс[/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.
kra37 сс
https://kra37a-cc.ru
Rodneynen
25 Oct 25 at 7:12 pm
Купить диплом техникума в Луганск [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_ueea
25 Oct 25 at 7:12 pm
https://www.hockeynhlforum.com/read-blog/1663
xoqiuas
25 Oct 25 at 7:12 pm
pillole per disfunzione erettile [url=http://mediuomo.com/#]farmaci per potenza maschile[/url] Viagra generico online Italia
Davidduese
25 Oct 25 at 7:13 pm
кракен тор
kraken зеркало
JamesDaync
25 Oct 25 at 7:14 pm
купить диплом зубного техника [url=www.rudik-diplom11.ru]купить диплом зубного техника[/url] .
Diplomi_xpMi
25 Oct 25 at 7:15 pm
Обработка дезинфекция цена частного дома.
обработка от клещей
KennethceM
25 Oct 25 at 7:15 pm
диплом купить с внесением в реестр [url=www.frei-diplom3.ru/]диплом купить с внесением в реестр[/url] .
Diplomi_asKt
25 Oct 25 at 7:15 pm
inspireeverydaylife – Highly recommend this shop, never disappointed with my purchases.
Louetta Hilado
25 Oct 25 at 7:17 pm
купить диплом с занесением в реестр вуза [url=http://www.frei-diplom2.ru]купить диплом с занесением в реестр вуза[/url] .
Diplomi_ouEa
25 Oct 25 at 7:18 pm
Playamo gaming site features an elite entertainment portfolio with over three thousand superior slots, table games, and real dealer games powered by premier development companies. From rotating new slot machine reels to applying your game plan at card games or experiencing real live dealer games, the platform accommodates every user needs. The casino’s elegant, easy-to-navigate design ensures effortless browsing on any device, letting game pleasure anytime, anywhere.
Playamo casino
AlfredLog
25 Oct 25 at 7:18 pm
1xbet [url=http://www.1xbet-16.com]1xbet[/url] .
1xbet_clOn
25 Oct 25 at 7:19 pm
1xbet yeni giri? [url=http://1xbet-15.com/]1xbet yeni giri?[/url] .
1xbet_jjpl
25 Oct 25 at 7:19 pm
Клопы в мебели? уничтожение тараканов в общежитии поможет.
уничтожение клопов
KennethceM
25 Oct 25 at 7:19 pm
Here is my web site – Play Pragmatic Play slots online – demo + cash
Play Pragmatic Play slots online – demo + cash
25 Oct 25 at 7:19 pm
smartchoiceoutlet – Always a pleasure shopping here, never disappoints with selections.
Coral Dopf
25 Oct 25 at 7:21 pm
neuer wettanbieter
Feel free to surf to my webpage – deutsche wettseiten
deutsche wettseiten
25 Oct 25 at 7:22 pm
купить проведенный диплом кого [url=http://frei-diplom2.ru]купить проведенный диплом кого[/url] .
Diplomi_ltEa
25 Oct 25 at 7:24 pm
Viа real-life study, OMT ѕhows math’s еffect, aiding
Singapore pupils develop ɑ profound love and exam motivation.
Established іn 2013 Ƅү Mr. Justin Tan, OMT Math Tuition һas actually helped mɑny students ace examinations ⅼike PSLE, O-Levels,ɑnd A-Levels ԝith proven probⅼem-solving strategies.
Ꮃith math incorporated seamlessly іnto Singapore’s class settings to benefit botһ teachers and trainees, devoted math tuition magnifies tһese gains by providing tailored support fοr sustained achievement.
Ԝith PSLE mathematics concerns frequently including real-ѡorld
applications, tuition supplies targeted practice tо develop crucial thinking skills
necеssary fߋr hіgh ratings.
Alternative development tһrough math tuition not ϳust increases
O Level ratings уet likewise cultivates logical thinking abilities іmportant for long-lasting knowing.
Preparing fⲟr the changability оf A Level concerns, tuition establishes flexible
ⲣroblem-solving strategies fⲟr real-time exam
situations.
OMTestablishes іtself aρart with аn exclusive educational program thаt extends MOE cօntent Ьу consisting ߋf enrichment activities focused оn creating mathematical intuition.
Ꮤith 24/7 accessibility to video lessons, үou can catch up on difficult subjects anytime leh, assisting үou score bеtter in exams with᧐ut stress.
Singapore’ѕ meritocratic ѕystem awards
hiցh up-ɑnd-comers, making math tuition a strategic financial iinvestment fߋr exam supremacy.
mу web page – secondary 3 Math tuition Singapore
secondary 3 Math tuition Singapore
25 Oct 25 at 7:25 pm
birxbet [url=http://1xbet-10.com/]http://1xbet-10.com/[/url] .
1xbet_tlea
25 Oct 25 at 7:25 pm
mostbet kg [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_ehmt
25 Oct 25 at 7:25 pm
купить диплом с занесением в реестр москва [url=https://frei-diplom3.ru]купить диплом с занесением в реестр москва[/url] .
Diplomi_snKt
25 Oct 25 at 7:26 pm
кракен маркетплейс
кракен вход
JamesDaync
25 Oct 25 at 7:27 pm
купить диплом занесением в реестр [url=www.frei-diplom6.ru]купить диплом занесением в реестр[/url] .
Diplomi_uiOl
25 Oct 25 at 7:29 pm
1xbet tr [url=https://www.1xbet-13.com]1xbet tr[/url] .
1xbet_uaKa
25 Oct 25 at 7:30 pm
Ресторан чистый после дезинсекция предприятий.
обработка от плесени в ванной
KennethceM
25 Oct 25 at 7:30 pm
купить диплом в запорожье [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_bxea
25 Oct 25 at 7:30 pm
Hello to all, since I am in fact keen of reading this blog’s post to be updated regularly.
It includes nice information.
Finozanetix
25 Oct 25 at 7:34 pm
Благодарю за дезинфекция после умерших! Проблема решена быстро.
уничтожение мышей
KennethceM
25 Oct 25 at 7:34 pm
I think what you said was actually very reasonable.
However, what about this? suppose you added a little content?
I ain’t saying your content isn’t good., however what if
you added a post title that grabbed people’s attention? I mean PHP hook,
building hooks in your application – Sjoerd
Maessen blog at Sjoerd Maessen blog is a little boring.
You should peek at Yahoo’s home page and see how they write
article titles to grab people to open the links. You might try adding a video or a pic or two to get readers interested about everything’ve got to say.
In my opinion, it would make your posts a little livelier.
bokep memek
25 Oct 25 at 7:34 pm
диплом техникума купить в украине [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_riea
25 Oct 25 at 7:37 pm
мостбеь [url=mostbet12032.ru]мостбеь[/url]
mostbet_kg_knmt
25 Oct 25 at 7:37 pm
1xbwt giri? [url=www.1xbet-12.com]www.1xbet-12.com[/url] .
1xbet_liSr
25 Oct 25 at 7:38 pm
lifestyleinspirationhub – User-friendly website, easy to navigate and find desired items.
Gary Arcuri
25 Oct 25 at 7:39 pm
farmacia confiable en España: Viagra genérico online España – pastillas de potencia masculinas
RandySkync
25 Oct 25 at 7:40 pm
My spouse and I stumbled over here by a different website and thought I might as well check things out.
I like what I see so now i’m following you. Look forward to finding out about your web page for a second
time.
Lune Finwex
25 Oct 25 at 7:40 pm
купить диплом с занесением в реестр в украине [url=www.frei-diplom6.ru]www.frei-diplom6.ru[/url] .
Diplomi_byOl
25 Oct 25 at 7:41 pm