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.pereplanirovka-nezhilogo-pomeshcheniya10.ru]www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_guSr
13 Oct 25 at 11:34 pm
It’s perfect time to make some plans for the future and it’s time
to be happy. I’ve read this post and if I could I
wish to suggest you few interesting things or tips.
Perhaps you can write next articles referring to this article.
I desire to read even more things about it!
homepage
13 Oct 25 at 11:35 pm
Suchen Sie Immobilien? Montenegro immobilien von privat kaufen wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.
Carminenus
13 Oct 25 at 11:36 pm
перепланировка в нежилом помещении [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка в нежилом помещении[/url] .
pereplanirovka nejilogo pomesheniya_qper
13 Oct 25 at 11:38 pm
rumalaya online
rumalaya online
13 Oct 25 at 11:42 pm
аренда гусеничного мини экскаватора [url=http://www.arenda-mini-ekskavatora-v-moskve-2.ru]аренда гусеничного мини экскаватора[/url] .
arenda mini ekskavatora v moskve_idKt
13 Oct 25 at 11:44 pm
разрешение на перепланировку нежилого помещения не требуется [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_vder
13 Oct 25 at 11:46 pm
brightideaweb – Content feels fresh, helpful, and not overloaded.
Damien Heist
13 Oct 25 at 11:48 pm
azulfidine for sale
azulfidine for sale
13 Oct 25 at 11:49 pm
проект перепланировки нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya9.ru]http://pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_jgKl
13 Oct 25 at 11:51 pm
согласование перепланировок нежилых помещений [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/[/url] .
pereplanirovka nejilogo pomesheniya_fher
13 Oct 25 at 11:51 pm
Website backlinks SEO
Our services are accessible by the following keywords: website backlinks, search engine optimization links, Google-focused backlinks, link building service, link developer, obtain backlinks, backlinking service, web backlinks, purchase backlinks, Kwork-based backlinks, website backlinks, SEO-focused backlinks.
Website backlinks SEO
13 Oct 25 at 11:52 pm
Получить диплом любого университета мы поможем. Купить аттестат в Тюмени – [url=http://diplomybox.com/kupit-attestat-v-tyumeni/]diplomybox.com/kupit-attestat-v-tyumeni[/url]
Cazrbeg
13 Oct 25 at 11:53 pm
натяжные потолки дешево самара [url=http://www.stretch-ceilings-samara.ru]http://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_nakl
13 Oct 25 at 11:54 pm
generic Amoxicillin pharmacy UK: amoxicillin uk – buy penicillin alternative online
JamesDes
13 Oct 25 at 11:57 pm
электрокарнизы для штор купить [url=elektrokarnizy797.ru]электрокарнизы для штор купить[/url] .
elektrokarnizi_qyMl
13 Oct 25 at 11:57 pm
Для максимальной эффективности мы предлагаем несколько сценариев — от разового экстренного вмешательства до длительного сопровождения ремиссии. Выбор формата определяется состоянием, анамнезом и целями пациента. Возможен гибридный маршрут: старт на дому, затем — дневной стационар или госпитализация, а после стабилизации — амбулаторное сопровождение.
Детальнее – [url=https://narkologicheskaya-pomoshch-ramenskoe7.ru/]chastnaya-skoraya-narkologicheskaya-pomoshch[/url]
AntonioMit
13 Oct 25 at 11:59 pm
DAGA 88 대한민국에 오신 것을 환영합니다 –
당신의 승리, 전액 지급. 지금 바로 매력적인 보너스를 받고,
최고의 게임을 즐기며, 믿을 수 있고 편리한 온라인 베팅 경험을 시작하세요!
DAGA 88 대한민국 – 당신의 승리
14 Oct 25 at 12:02 am
Sou viciado no fluxo de Brazino Casino, explode com uma vibe aquatica eletrizante. A selecao de titulos e uma correnteza de emocoes. com caca-niqueis que reluzem como perolas. O time do cassino e digno de um capitao de navio. garantindo suporte direto e sem correntezas. Os pagamentos sao seguros e fluidos. em alguns momentos as ofertas podiam ser mais generosas. Em resumo, Brazino Casino e um recife de emocoes para os mergulhadores do cassino! E mais o site e uma obra-prima de estilo subaquatico. dando vontade de voltar como uma onda.
brazino777 apuestas|
whimsybubblecrab6zef
14 Oct 25 at 12:02 am
узаконивание перепланировки нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]узаконивание перепланировки нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_yqer
14 Oct 25 at 12:02 am
Greɑt post. Ι was checking constantly this blog and I am impressed!
Extremely usefuⅼ informаtion рarticularly the lasst part 🙂 Ι care for such informatiοn a lⲟt.
I wаs loօking for this paгticular information foг
a very long time. Thank you аnd good luck.
My blog :: jc math tuition serangoon
jc math tuition serangoon
14 Oct 25 at 12:03 am
согласование перепланировки в нежилом здании [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_bzKl
14 Oct 25 at 12:03 am
потолки в самаре [url=https://www.stretch-ceilings-samara-1.ru]потолки в самаре[/url] .
natyajnie potolki samara_wdsl
14 Oct 25 at 12:06 am
If some one needs expert view regarding running a blog then i propose him/her to
pay a visit this blog, Keep up the nice work.
Hobicode
14 Oct 25 at 12:06 am
I’m gone to convey my little brother, that he should also visit
this web site on regular basis to take updated from hottest
gossip.
K88
14 Oct 25 at 12:07 am
Wow, mega Plattform! Sehr professionell, Glückwunsch ans Team!
linneasky onlyfans leak
linneasky onlyfans leak
14 Oct 25 at 12:08 am
перепланировка нежилого помещения в москве [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка нежилого помещения в москве[/url] .
pereplanirovka nejilogo pomesheniya_pier
14 Oct 25 at 12:10 am
best games
Brentsek
14 Oct 25 at 12:11 am
Backlinks for your site
Effective in every area of the resource.
I build backlinks to your site.
These backlinks draw in indexing bots to the resource, something that significantly impacts for ranking, thus it is essential to promote a resource that does not have errors that obstruct ranking.
Posting is secure for your domain!
I avoid filling in contact forms, (contact forms are harmful the domain because of reports from the owners).
Placement is performed in allowed areas.
Links are posted to their latest continuously refreshed list. Several portals in the list.
Backlinks for your site
14 Oct 25 at 12:11 am
Greetings, There’s no doubt that your website could possibly be having web
browser compatibility problems. Whenever I take a look at your site in Safari, it looks fine however, when opening in Internet
Explorer, it has some overlapping issues. I just wanted
to give you a quick heads up! Apart from that, excellent
site!
Puro Tradelux
14 Oct 25 at 12:12 am
компания потолочник [url=http://natyazhnye-potolki-samara-1.ru]http://natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_dfor
14 Oct 25 at 12:13 am
согласование перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/]согласование перепланировки нежилого помещения[/url] .
pereplanirovka nejilogo pomesheniya_foSr
14 Oct 25 at 12:14 am
жалюзи для пластиковых окон с электроприводом [url=http://www.zhalyuzi-s-elektroprivodom77.ru]http://www.zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_rkpa
14 Oct 25 at 12:14 am
готовые рулонные шторы купить в москве [url=rulonnaya-shtora-s-elektroprivodom.ru]готовые рулонные шторы купить в москве[/url] .
rylonnaya shtora s elektroprivodom_hjKt
14 Oct 25 at 12:15 am
Sou viciado no codigo de PlayPix Casino, tem uma energia de jogo tao vibrante quanto um codigo binario em furia. A selecao de titulos e um buffer de prazeres. incluindo mesas com charme de algoritmo. Os agentes sao rapidos como um download. assegurando apoio sem erros. Os pagamentos sao lisos como um buffer. porem mais giros gratis seriam vibrantes. Em sintese, PlayPix Casino vale explorar esse cassino ja para os viciados em emocoes de cassino! De lambuja o design e um espetaculo visual de matriz. amplificando o jogo com vibracao digital.
saque diГЎrio playpix|
zapwhirlwindostrich3zef
14 Oct 25 at 12:15 am
If you want to learn everything about online platforms in the United States, then this is definitely worth checking out. Discover the full details via the link at the bottom of the page:
best online casino
FrancisCrymn
14 Oct 25 at 12:18 am
перепланировка нежилого помещения в нежилом здании законодательство [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]перепланировка нежилого помещения в нежилом здании законодательство[/url] .
pereplanirovka nejilogo pomesheniya_vser
14 Oct 25 at 12:18 am
Estou completamente incendiado por Fogo777 Casino, oferece uma aventura que reluz como brasas vivas. O leque do cassino e um fogo de delicias. com caca-niqueis modernos que hipnotizam como fogos. Os agentes sao rapidos como uma faisca. com solucoes precisas e instantaneas. Os pagamentos sao lisos como uma pira. de vez em quando mais giros gratis seriam uma loucura de fogo. Ao final, Fogo777 Casino e o point perfeito pros fas de cassino para quem curte apostar com estilo flamejante! Adicionalmente o visual e uma explosao de chamas. transformando cada aposta em uma aventura flamejante.
plataforma fogo777 Г© confiГЎvel|
flamewhirlwindemu2zef
14 Oct 25 at 12:18 am
Suchen Sie Immobilien? http://www.montenegro-immobilien-kaufen.com wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.
Carminenus
14 Oct 25 at 12:19 am
купить диплом в симферополе [url=http://rudik-diplom13.ru/]http://rudik-diplom13.ru/[/url] .
Diplomi_laon
14 Oct 25 at 12:19 am
Программы терапии строятся так, чтобы одновременно воздействовать на биологические, психологические и социальные факторы зависимости. Это повышает результативность и уменьшает риск повторного употребления.
Подробнее – [url=https://narkologicheskaya-klinika-lugansk0.ru/]www.domen.ru[/url]
Lowellseery
14 Oct 25 at 12:20 am
можно купить диплом медсестры [url=http://frei-diplom15.ru/]можно купить диплом медсестры[/url] .
Diplomi_gxoi
14 Oct 25 at 12:21 am
перепланировка нежилого помещения в москве [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]перепланировка нежилого помещения в москве[/url] .
pereplanirovka nejilogo pomesheniya_gyer
14 Oct 25 at 12:21 am
Suchen Sie Immobilien? Montenegro immobilie kaufen erfahrungen wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.
Carminenus
14 Oct 25 at 12:22 am
Hi, i think that i noticed you visited my web site thus i came to return the favor?.I’m trying to
to find things to enhance my web site!I guess its adequate to
use some of your concepts!!
kra42 cc
14 Oct 25 at 12:23 am
перепланировка здания [url=pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка здания[/url] .
pereplanirovka nejilogo pomesheniya_qlKl
14 Oct 25 at 12:25 am
Hi! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Lumineux Invexus
14 Oct 25 at 12:26 am
It is perfect time to make some plans for the long run and it’s time to be happy.
I’ve learn this publish and if I could I want to counsel you few interesting things or advice.
Perhaps you can write subsequent articles regarding this article.
I want to read even more things about it!
Westrise Corebit
14 Oct 25 at 12:27 am
Выделяется ряд преимуществ, которые делают терапию в клинике оптимальным решением для борьбы с зависимостью.
Выяснить больше – [url=https://lechenie-alkogolizma-perm0.ru/]здоровье лечение алкоголизма в перми[/url]
Francisaxogy
14 Oct 25 at 12:27 am
Saved as a favorite, I like your site!
Thanks
14 Oct 25 at 12:28 am