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=https://frei-diplom3.ru]купить проведенный диплом кого[/url] .
Diplomi_dmKt
25 Oct 25 at 11:46 pm
Плесень ушла после санитарная обработка, спасибо!
санобработка
KennethceM
25 Oct 25 at 11:46 pm
1 x bet [url=www.1xbet-13.com]1 x bet[/url] .
1xbet_laKa
25 Oct 25 at 11:49 pm
Hello, I enjoy reading through your article post.
I wanted to write a little comment to support you.
Yua Mikami
25 Oct 25 at 11:49 pm
1 x bet giri? [url=http://www.1xbet-15.com]http://www.1xbet-15.com[/url] .
1xbet_yopl
25 Oct 25 at 11:50 pm
купить дипломы о высшем образовании цена [url=www.rudik-diplom11.ru]купить дипломы о высшем образовании цена[/url] .
Diplomi_ysMi
25 Oct 25 at 11:50 pm
купить диплом техникума в кирове [url=www.frei-diplom8.ru]купить диплом техникума в кирове[/url] .
Diplomi_lbsr
25 Oct 25 at 11:50 pm
Hey! Someone in my Myspace group shared this website with us so I came
to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
Superb blog and wonderful style and design.
material
25 Oct 25 at 11:51 pm
1 xbet giri? [url=www.1xbet-15.com/]www.1xbet-15.com/[/url] .
1xbet_jtpl
25 Oct 25 at 11:51 pm
What a stuff of un-ambiguity and preserveness of precious experience regarding unpredicted emotions.
visit them
25 Oct 25 at 11:51 pm
What’s Taking place i’m new to this, I stumbled upon this I’ve found It
positively useful and it has aided me out loads.
I hope to contribute & assist other users like its helped
me. Good job.
igtoto
25 Oct 25 at 11:51 pm
купить диплом колледжа с занесением в реестр [url=frei-diplom3.ru]купить диплом колледжа с занесением в реестр[/url] .
Diplomi_jlKt
25 Oct 25 at 11:52 pm
kraken marketplace
кракен маркет
JamesDaync
25 Oct 25 at 11:52 pm
купить диплом слесаря [url=https://www.rudik-diplom3.ru]купить диплом слесаря[/url] .
Diplomi_qfei
25 Oct 25 at 11:53 pm
Heya are using WordPress for your site platform? I’m new to
the blog world but I’m trying to get started and set up my own. Do you require any html coding expertise to make your
own blog? Any help would be really appreciated!
Optima Fundrelix Legit Or Not
25 Oct 25 at 11:53 pm
Вызывали уничтожение тараканов в мебели ночью, приехали быстро!
дезинфекция после ремонта
KennethceM
25 Oct 25 at 11:55 pm
1xbet giri? adresi [url=https://1xbet-12.com]1xbet giri? adresi[/url] .
1xbet_gaSr
25 Oct 25 at 11:55 pm
купить диплом регистрацией [url=frei-diplom3.ru]купить диплом регистрацией[/url] .
Diplomi_csKt
25 Oct 25 at 11:56 pm
I’m not that much of a online reader to be honest but your sites really
nice, keep it up! I’ll go ahead and bookmark your
site to come back later. All the best
Mandee Store Lowest
25 Oct 25 at 11:58 pm
Вызвать обработка квартиры от клопов дешево, где?
уничтожение клопов холодным туманом
KennethceM
25 Oct 25 at 11:58 pm
1xbet com giri? [url=https://1xbet-15.com]https://1xbet-15.com[/url] .
1xbet_qhpl
25 Oct 25 at 11:58 pm
1x bet [url=1xbet-16.com]1x bet[/url] .
1xbet_tuOn
25 Oct 25 at 11:59 pm
где купить диплом техникума тебя [url=https://frei-diplom8.ru/]где купить диплом техникума тебя[/url] .
Diplomi_hwsr
26 Oct 25 at 12:00 am
купить диплом в крыму [url=https://rudik-diplom8.ru]купить диплом в крыму[/url] .
Diplomi_qsMt
26 Oct 25 at 12:00 am
globalmarketplacehub – Easy to navigate, found exactly what I was looking for.
Tammara Riveroll
26 Oct 25 at 12:02 am
birxbet [url=http://1xbet-14.com/]birxbet[/url] .
1xbet_gaet
26 Oct 25 at 12:02 am
xbet giri? [url=https://1xbet-12.com/]https://1xbet-12.com/[/url] .
1xbet_rlSr
26 Oct 25 at 12:05 am
Ready Wallet is a powerful crypto tool to manage multiple wallets
easily. The Argent X Wallet now called Ready Wallet App offers secure access through Ready Wallet Login for smooth and safe crypto management.
argent x wallet
26 Oct 25 at 12:06 am
https://herengezondheid.com/# goedkope Viagra tabletten online
Hermanereli
26 Oct 25 at 12:06 am
купить диплом продавца [url=www.rudik-diplom3.ru]купить диплом продавца[/url] .
Diplomi_lqei
26 Oct 25 at 12:07 am
Playamo digital venue offers an outstanding game library with over 3,000+ high-end slot games, casino tables, and live gaming experiences from premier game developers. From the current slots to tactical card games and realistic live gaming, the site suits every gaming style. With its refined, straightforward platform, the platform enables easy movement on any device, permitting you to access selections whenever you choose.
Playamo
AlfredLog
26 Oct 25 at 12:07 am
1xbet guncel [url=www.1xbet-16.com/]1xbet guncel[/url] .
1xbet_ldOn
26 Oct 25 at 12:08 am
I am extremely impressed with your writing skills and also with the layout
on your weblog. Is this a paid theme or did you modify it yourself?
Either way keep up the nice quality writing, it is rare to see
a great blog like this one today.
fastest payout online casinos
26 Oct 25 at 12:09 am
кракен сайт
кракен обмен
JamesDaync
26 Oct 25 at 12:10 am
купить диплом внесенный в реестр [url=https://frei-diplom3.ru]купить диплом внесенный в реестр[/url] .
Diplomi_iiKt
26 Oct 25 at 12:11 am
I’m extremely pleased to discover this website.
I want to to thank you for your time due to this fantastic read!!
I definitely loved every part of it and i also have you bookmarked to check out new stuff on your blog.
onewave
26 Oct 25 at 12:11 am
купить диплом менеджера по туризму [url=http://www.rudik-diplom10.ru]купить диплом менеджера по туризму[/url] .
Diplomi_rfSa
26 Oct 25 at 12:11 am
kraken vk5
kraken зеркало
JamesDaync
26 Oct 25 at 12:12 am
Отличная обработка от блох в доме , мастера приехали вовремя.
уничтожение тараканов с гарантией
KennethceM
26 Oct 25 at 12:13 am
скачать мостбет кг [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_anmt
26 Oct 25 at 12:14 am
discoverendlessideas – Always find fresh perspectives and practical tips to explore.
Marty Calegari
26 Oct 25 at 12:14 am
1 x bet giri? [url=http://1xbet-15.com]http://1xbet-15.com[/url] .
1xbet_zspl
26 Oct 25 at 12:14 am
This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I have shared your website in my social networks!
kra42 at
ShaneDrync
26 Oct 25 at 12:14 am
купить диплом в королёве [url=www.rudik-diplom3.ru]купить диплом в королёве[/url] .
Diplomi_dsei
26 Oct 25 at 12:14 am
1xbet giri? linki [url=1xbet-15.com]1xbet giri? linki[/url] .
1xbet_wdpl
26 Oct 25 at 12:16 am
1x bet giri? [url=https://1xbet-16.com/]1x bet giri?[/url] .
1xbet_bbOn
26 Oct 25 at 12:17 am
купить диплом медсестры [url=www.rudik-diplom8.ru]купить диплом медсестры[/url] .
Diplomi_raMt
26 Oct 25 at 12:18 am
купить диплом в ессентуках [url=http://www.rudik-diplom10.ru]купить диплом в ессентуках[/url] .
Diplomi_grSa
26 Oct 25 at 12:18 am
I’m now not sure where you’re getting your info, however
great topic. I must spend some time finding out more or working out
more. Thank you for great info I was on the lookout for this information for my
mission.
adam and eve coupon codes
26 Oct 25 at 12:19 am
купить диплом в белгороде [url=https://rudik-diplom3.ru]купить диплом в белгороде[/url] .
Diplomi_ecei
26 Oct 25 at 12:19 am