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=www.rudik-diplom2.ru]купить диплом в челябинске[/url] .
Diplomi_jwpi
3 Oct 25 at 7:29 pm
футбол сегодня прогнозы [url=http://prognozy-na-futbol-10.ru]http://prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_euOi
3 Oct 25 at 7:32 pm
купить диплом вуза с реестром [url=http://frei-diplom4.ru/]купить диплом вуза с реестром[/url] .
Diplomi_luOl
3 Oct 25 at 7:32 pm
Нужен надежный акб? где купить аккумулятор для авто AKB STORE — ведущий интернет-магазин автомобильных аккумуляторов в Санкт-Петербурге! Мы специализируемся на продаже качественных аккумуляторных батарей для самой разнообразной техники. В нашем каталоге вы найдёте идеальные решения для любого транспортного средства: будь то легковой или грузовой автомобиль, катер или лодка, скутер или мопед, погрузчик или штабелер.
akb-store-313
3 Oct 25 at 7:32 pm
купить диплом в октябрьском [url=rudik-diplom3.ru]купить диплом в октябрьском[/url] .
Diplomi_wlei
3 Oct 25 at 7:32 pm
Hello there! This post couldn’t be written any better!
Reading through this article reminds me of my previous roommate!
He continually kept preaching about this. I will send this post to him.
Pretty sure he will have a great read. Many thanks for sharing!
신용카드 현금화
3 Oct 25 at 7:32 pm
Nіce slot bro!
slot tanpa deposit
3 Oct 25 at 7:33 pm
где купить диплом с занесением реестр [url=http://www.frei-diplom1.ru]где купить диплом с занесением реестр[/url] .
Diplomi_leOi
3 Oct 25 at 7:33 pm
диплом торгового техникума купить [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_qpea
3 Oct 25 at 7:33 pm
купить диплом медсестры [url=www.rudik-diplom8.ru/]купить диплом медсестры[/url] .
Diplomi_ggMt
3 Oct 25 at 7:33 pm
https://www.designspiration.com/promocode1xbet/saves/
izeacqg
3 Oct 25 at 7:33 pm
точный прогнозы на футбол [url=www.prognozy-na-futbol-10.ru]www.prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_twOi
3 Oct 25 at 7:34 pm
Клиника «Альтернатива» предлагает фиксированные цены на выезд нарколога с оплатой после оказания услуги. Тарифы действуют по всему городу и пригороду.
Получить дополнительные сведения – [url=https://narkologicheskaya-pomoshh-ufa9.ru/]платная наркологическая помощь[/url]
LionelBok
3 Oct 25 at 7:34 pm
купить диплом судоводителя [url=http://rudik-diplom4.ru/]купить диплом судоводителя[/url] .
Diplomi_kfOr
3 Oct 25 at 7:34 pm
Лазерные уровни – это высокоточные инструменты, используемые для определения горизонтальных и вертикальных линий на строительных площадках, при ремонте и в других сферах, где необходима ровная разметка. Они значительно упрощают и ускоряют процесс, по сравнению с традиционными методами, такими как водяной уровень или отвес.
Существует несколько типов лазерных уровней, каждый из которых предназначен для определенных задач. Линейные лазерные уровни проецируют одну или несколько прямых линий, что удобно для выравнивания плитки, установки подвесных потолков или оклейки обоев. Ротационные лазерные уровни вращаются и проецируют линию на 360 градусов, охватывая всю комнату.
Это особенно полезно при заливке полов, установке перегородок или выравнивании ландшафта. Точечные лазерные уровни проецируют точки, которые служат ориентирами для переноса отметок с одной стены на другую. Помогите выбрать [url=https://forum.sportmashina.com/index.php?threads/otlichnoe-reshenie-dlja-tochnogo-skanirovanija.24215/]сканер slam.[/url]
RobertCleag
3 Oct 25 at 7:35 pm
I couldn’t resist commenting. Well written!
antigua barbuda citizenship by investment
3 Oct 25 at 7:36 pm
купить диплом занесенный в реестр [url=www.frei-diplom5.ru]купить диплом занесенный в реестр[/url] .
Diplomi_hyPa
3 Oct 25 at 7:37 pm
где купить диплом среднем [url=http://rudik-diplom15.ru/]где купить диплом среднем[/url] .
Diplomi_thPi
3 Oct 25 at 7:37 pm
онлайн-казино с лицензией Curacao. Предлагает щедрые бонусы, топовые игры от ведущих провайдеров, быстрые выплаты и круглосуточную поддержку
dragon money официальный сайт
BrittGor
3 Oct 25 at 7:37 pm
купить диплом с занесением в реестр цена [url=http://frei-diplom1.ru/]купить диплом с занесением в реестр цена[/url] .
Diplomi_mjOi
3 Oct 25 at 7:38 pm
как купить диплом с занесением в реестр [url=https://www.frei-diplom6.ru]как купить диплом с занесением в реестр[/url] .
Diplomi_uzOl
3 Oct 25 at 7:38 pm
https://albummarket.ru
PatrickGop
3 Oct 25 at 7:38 pm
где купить диплом техникума [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_anea
3 Oct 25 at 7:38 pm
https://www.tripadvisor.com/Profile/promocodeforp
https://www.tripadvisor.com/Profile/promocodeforp
3 Oct 25 at 7:39 pm
купить диплом в анжеро-судженске [url=rudik-diplom10.ru]rudik-diplom10.ru[/url] .
Diplomi_peSa
3 Oct 25 at 7:40 pm
купить диплом программиста [url=www.rudik-diplom2.ru]купить диплом программиста[/url] .
Diplomi_cxpi
3 Oct 25 at 7:41 pm
Запросы [url=www.prognozy-na-khokkej4.ru]Запросы[/url] .
prognozi na hokkei_skOl
3 Oct 25 at 7:41 pm
купить диплом в саранске [url=https://rudik-diplom1.ru]купить диплом в саранске[/url] .
Diplomi_rzer
3 Oct 25 at 7:42 pm
экспресс на футбол сегодня [url=www.prognozy-na-futbol-10.ru]www.prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_ypOi
3 Oct 25 at 7:43 pm
купить диплом юриста [url=https://rudik-diplom3.ru/]купить диплом юриста[/url] .
Diplomi_eyei
3 Oct 25 at 7:43 pm
Great post. I used to be checking constantly this weblog and I’m inspired!
Very helpful information specifically the
last part 🙂 I handle such info much. I used to be
seeking this particular information for a very lengthy time.
Thank you and good luck.
gay
3 Oct 25 at 7:44 pm
купить диплом в екатеринбург реестр [url=http://frei-diplom3.ru/]купить диплом в екатеринбург реестр[/url] .
Diplomi_wpKt
3 Oct 25 at 7:44 pm
MedicExpress MX: Best online Mexican pharmacy – Best online Mexican pharmacy
MartinJaive
3 Oct 25 at 7:45 pm
Hi! This is my first visit to your blog!
We are a group of volunteers and starting a new initiative in a community in the same niche.
Your blog provided us useful information to
work on. You have done a marvellous job!
AeveniroxAi
3 Oct 25 at 7:46 pm
купить диплом техникума учебное [url=frei-diplom9.ru]купить диплом техникума учебное[/url] .
Diplomi_efea
3 Oct 25 at 7:47 pm
купить диплом в волгодонске [url=http://rudik-diplom7.ru]купить диплом в волгодонске[/url] .
Diplomi_tePl
3 Oct 25 at 7:47 pm
купить диплом в петропавловске-камчатском [url=https://rudik-diplom14.ru/]купить диплом в петропавловске-камчатском[/url] .
Diplomi_bmea
3 Oct 25 at 7:48 pm
купить диплом в новоалтайске [url=https://rudik-diplom1.ru/]купить диплом в новоалтайске[/url] .
Diplomi_bper
3 Oct 25 at 7:48 pm
Howdy I am so delighted I found your website, I really found you by accident, while
I was searching on Google for something else, Anyhow I am here now and
would just like to say kudos for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time
to read through it all at the moment but I have book-marked it
and also added in your RSS feeds, so when I have time I will be back
to read a lot more, Please do keep up the great job.
canadian pharmaceuticals online
3 Oct 25 at 7:49 pm
360view – Navigation is simple, no confusion moving between different sections today.
Jim Slotemaker
3 Oct 25 at 7:51 pm
купить легальный диплом техникума [url=https://frei-diplom3.ru]купить легальный диплом техникума[/url] .
Diplomi_mcKt
3 Oct 25 at 7:51 pm
прогнозы на сегодня футбол [url=prognozy-na-futbol-10.ru]прогнозы на сегодня футбол[/url] .
prognozi na fytbol_aaOi
3 Oct 25 at 7:52 pm
xxfh – Navigation is smooth, every click takes you where you expect.
Rex Long
3 Oct 25 at 7:53 pm
https://tadalmedspharmacy.com/# Buy Tadalafil online
Williamjib
3 Oct 25 at 7:53 pm
купить диплом о среднем [url=http://rudik-diplom7.ru/]купить диплом о среднем[/url] .
Diplomi_jzPl
3 Oct 25 at 7:55 pm
диплом о высшем образовании купить с занесением в реестр [url=https://www.frei-diplom1.ru]диплом о высшем образовании купить с занесением в реестр[/url] .
Diplomi_kmOi
3 Oct 25 at 7:55 pm
диплом купить проведенный [url=www.frei-diplom3.ru/]диплом купить проведенный[/url] .
Diplomi_knKt
3 Oct 25 at 7:55 pm
диплом техникум колледж купить [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_ioea
3 Oct 25 at 7:56 pm
прогноз футбол на сегодня [url=https://prognozy-na-futbol-10.ru/]прогноз футбол на сегодня[/url] .
prognozi na fytbol_bwOi
3 Oct 25 at 7:56 pm
купить диплом в когалыме [url=http://rudik-diplom5.ru/]http://rudik-diplom5.ru/[/url] .
Diplomi_kdma
3 Oct 25 at 7:56 pm