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!
buy cialis online: discreet ED pills delivery in the US – trusted online pharmacy for ED meds
AndrewPal
15 Oct 25 at 9:36 pm
Good blog you have here.. It’s difficult to find excellent writing like yours nowadays.
I really appreciate individuals like you! Take care!!
singapore 82200219
15 Oct 25 at 9:39 pm
These are really enormous ideas in regarding blogging.
You have touched some pleasant points here. Any way keep up wrinting.
BỌN RẺ RÁCH 69VN
15 Oct 25 at 9:39 pm
потолки натяжные в нижнем новгороде [url=https://natyazhnye-potolki-nizhniy-novgorod.ru/]https://natyazhnye-potolki-nizhniy-novgorod.ru/[/url] .
natyajnie potolki nijnii novgorod_kdOt
15 Oct 25 at 9:40 pm
студия для самостоятельной записи [url=https://studiya-podkastov-spb.ru]https://studiya-podkastov-spb.ru[/url] .
stydiya podkastov spb_bcka
15 Oct 25 at 9:40 pm
Greetings I am so glad I found your web site, I really found you by accident, while I
was searching on Askjeeve for something else, Regardless I am here now and would just
like to say thank you for a incredible post and a all round entertaining
blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb jo.
Opulatrix Legit Or Not
15 Oct 25 at 9:41 pm
все микрозаймы [url=https://zaimy-28.ru/]все микрозаймы[/url] .
zaimi_mlKa
15 Oct 25 at 9:42 pm
Thanks for the good writeup. It actually was once a enjoyment account it.
Look complex to far introduced agreeable from you!
By the way, how could we keep in touch?
Many thanks
15 Oct 25 at 9:42 pm
студия для съемки подкастов [url=studiya-podkastov-spb.ru]studiya-podkastov-spb.ru[/url] .
stydiya podkastov spb_qtka
15 Oct 25 at 9:44 pm
bs2web at Интересуешься, что происходит в тёмных уголках сети? Blacksprut — это не просто название, это гарантия анонимности, высокой скорости и надежности. Переходи на bs2best.at — там ты найдёшь то, о чём другие умалчивают. Тебе откроется доступ к информации, которую скрывают от большинства. Только для тех, кто понимает. Без компрометирующих следов. Без уступок. Только Blacksprut. Не упусти шанс узнать первым — bs2best.at уже готов открыть свои двери. Дерзнешь ли ты взглянуть правде в глаза?
HermanRhype
15 Oct 25 at 9:46 pm
организация онлайн трансляций мероприятий [url=https://www.zakazat-onlayn-translyaciyu.ru]организация онлайн трансляций мероприятий[/url] .
zakazat onlain translyaciu _xlka
15 Oct 25 at 9:47 pm
потолочки [url=https://natyazhnye-potolki-nizhniy-novgorod.ru/]https://natyazhnye-potolki-nizhniy-novgorod.ru/[/url] .
natyajnie potolki nijnii novgorod_rxOt
15 Oct 25 at 9:48 pm
Wow! In the end I got a web site from where I know how to
actually obtain helpful information regarding my study and
knowledge.
Måne Fundexis Anmeldelse
15 Oct 25 at 9:51 pm
https://tadalifepharmacy.com/# TadaLife Pharmacy
MervinWoorE
15 Oct 25 at 9:51 pm
организация прямой трансляции [url=https://zakazat-onlayn-translyaciyu1.ru/]организация прямой трансляции[/url] .
zakazat onlain translyaciu _simt
15 Oct 25 at 9:51 pm
кухни на заказ производство спб [url=https://kuhni-spb-1.ru/]kuhni-spb-1.ru[/url] .
kyhni spb_bemi
15 Oct 25 at 9:53 pm
1win az bonus 500 [url=https://1win5005.com]1win az bonus 500[/url]
1win_hdml
15 Oct 25 at 9:53 pm
взять +в аренду экскаватор [url=https://arenda-mini-ekskavatora-v-moskve.ru]https://arenda-mini-ekskavatora-v-moskve.ru[/url] .
arenda mini ekskavatora v moskve_xrEn
15 Oct 25 at 9:54 pm
потолочкин натяжные потолки отзывы клиентов нижний новгород [url=www.natyazhnye-potolki-nizhniy-novgorod.ru]www.natyazhnye-potolki-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_ajOt
15 Oct 25 at 9:55 pm
sportwetten tipps für heute
My web page – wettanbieter ohne einzahlung (Maxie)
Maxie
15 Oct 25 at 9:55 pm
wetten pferderennen tipps
Also visit my blog: wett vorhersage – Florence
–
Florence
15 Oct 25 at 9:57 pm
вывод из запоя омск
vivod-iz-zapoya-omsk012.ru
лечение запоя омск
vivodomskNeT
15 Oct 25 at 9:57 pm
стоимость онлайн трансляции на мероприятии [url=www.zakazat-onlayn-translyaciyu.ru/]www.zakazat-onlayn-translyaciyu.ru/[/url] .
zakazat onlain translyaciu _xcka
15 Oct 25 at 9:59 pm
community theater
MichaelSig
15 Oct 25 at 10:00 pm
потолочкин потолки натяжные отзывы [url=www.stretch-ceilings-nizhniy-novgorod.ru]www.stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_shPl
15 Oct 25 at 10:00 pm
потолок натяжной [url=http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]потолок натяжной[/url] .
natyajnie potolki nijnii novgorod_cnma
15 Oct 25 at 10:01 pm
A motivating discussion is definitely worth comment.
I do think that you should publish more on this subject, it may not be a taboo matter but generally people do
not talk about these issues. To the next! All the best!!
해운대호빠
15 Oct 25 at 10:02 pm
онлайн трансляция заказать [url=http://zakazat-onlayn-translyaciyu1.ru/]онлайн трансляция заказать[/url] .
zakazat onlain translyaciu _qkmt
15 Oct 25 at 10:03 pm
заказать кухню спб [url=kuhni-spb-1.ru]kuhni-spb-1.ru[/url] .
kyhni spb_shmi
15 Oct 25 at 10:04 pm
натяжные потолки сайт [url=http://www.stretch-ceilings-nizhniy-novgorod-1.ru]натяжные потолки сайт[/url] .
natyajnie potolki nijnii novgorod_faOn
15 Oct 25 at 10:06 pm
потолка [url=www.natyazhnye-potolki-nizhniy-novgorod.ru]www.natyazhnye-potolki-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_lpOt
15 Oct 25 at 10:07 pm
The $MTAUR token utility in unlocking special zones is what sets it apart from generic play-to-earn. Presale stage 1 savings are massive, up to 5x value. Team’s experience from top crypto projects adds credibility.
minotaurus ico
WilliamPargy
15 Oct 25 at 10:07 pm
https://t.me/rating_online/13
EverettGuemn
15 Oct 25 at 10:07 pm
With havin so much content and articles do you
ever run into any problems of plagorism or copyright infringement?
My blog has a lot of unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet without my
authorization. Do you know any solutions to help stop content from being
stolen? I’d certainly appreciate it.
facer.io
15 Oct 25 at 10:08 pm
все микрозаймы онлайн [url=http://www.zaimy-28.ru]все микрозаймы онлайн[/url] .
zaimi_fyKa
15 Oct 25 at 10:08 pm
https://t.me/s/rating_online/4
EverettGuemn
15 Oct 25 at 10:08 pm
Обязательно позвонить должны, как позвонят легче забрать самому чем ждать пока курьер доставит
https://telegra.ph/Kvadrokopter-dji-mavic-3t-kupit-10-13-3
то-же самое могу сказать!
MichaelViess
15 Oct 25 at 10:09 pm
В этой статье мы рассмотрим ключевые признаки эффективной наркологической помощи в Ярославле — от состава команды до подходов в работе с мотивацией пациента.
Детальнее – https://lechenie-narkomanii-yaroslavl0.ru/
RichardEsser
15 Oct 25 at 10:10 pm
Ich liebe die unbandige Kraft von Lowen Play Casino, es verstromt eine Spielstimmung, die wie eine Savanne tobt. Die Spielauswahl im Casino ist wie eine wilde Horde, mit Casino-Spielen, die fur Kryptowahrungen optimiert sind. Der Casino-Service ist zuverlassig und machtig, ist per Chat oder E-Mail erreichbar. Auszahlungen im Casino sind schnell wie ein Raubkatzen-Sprint, aber wurde ich mir mehr Casino-Promos wunschen, die wie ein Feuer lodern. Am Ende ist Lowen Play Casino ein Casino, das man nicht verpassen darf fur Fans moderner Casino-Slots! Zusatzlich die Casino-Navigation ist kinderleicht wie eine Fahrte, einen Hauch von Abenteuer ins Casino bringt.
lГ¶wen play uetersen|
zappysquirrel3zef
15 Oct 25 at 10:10 pm
http://tadalifepharmacy.com/# tadalafil tablets without prescription
MervinWoorE
15 Oct 25 at 10:11 pm
Adoro o clima explosivo de JabiBet Casino, oferece uma aventura de cassino que arrasta tudo. O catalogo de jogos do cassino e uma tempestade, incluindo jogos de mesa de cassino cheios de vibe. O suporte do cassino ta sempre na area 24/7, garantindo suporte de cassino direto e sem tempestade. As transacoes do cassino sao simples como uma brisa, as vezes mais bonus regulares no cassino seria top. No geral, JabiBet Casino e o point perfeito pros fas de cassino para os viciados em emocoes de cassino! Vale falar tambem o site do cassino e uma obra-prima de estilo, da um toque de classe aquatica ao cassino.
jabibet casino|
zippyoctopus4zef
15 Oct 25 at 10:11 pm
https://t.me/s/rating_online/5
EverettGuemn
15 Oct 25 at 10:13 pm
https://t.me/rating_online/5
EverettGuemn
15 Oct 25 at 10:14 pm
студия для самостоятельной записи [url=http://www.studiya-podkastov-spb.ru]http://www.studiya-podkastov-spb.ru[/url] .
stydiya podkastov spb_wwka
15 Oct 25 at 10:14 pm
Estou pirando com PagolBet Casino, tem uma vibe de jogo que e pura eletricidade. A gama do cassino e simplesmente uma faisca, com slots de cassino unicos e contagiantes. O servico do cassino e confiavel e brabo, dando solucoes na hora e com precisao. Os ganhos do cassino chegam voando como um meteoro, mesmo assim mais bonus regulares no cassino seria top. No fim das contas, PagolBet Casino e o point perfeito pros fas de cassino para os amantes de cassinos online! Alem disso a interface do cassino e fluida e cheia de energia eletrica, torna o cassino uma curticao total.
pagolbet cassino|
zanyflamingo2zef
15 Oct 25 at 10:14 pm
натяжные потолки сайт [url=natyazhnye-potolki-nizhniy-novgorod.ru]natyazhnye-potolki-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_ldOt
15 Oct 25 at 10:16 pm
Ich bin fasziniert von SpinBetter Casino, es bietet einen einzigartigen Kick. Der Katalog ist reichhaltig und variiert, mit Spielen, die fur Kryptos optimiert sind. Der Service ist von hoher Qualitat, verfugbar rund um die Uhr. Die Gewinne kommen prompt, ab und an mehr Rewards waren ein Plus. Alles in allem, SpinBetter Casino ist ein Muss fur alle Gamer fur Krypto-Enthusiasten ! Hinzu kommt die Navigation ist kinderleicht, erleichtert die gesamte Erfahrung. Hervorzuheben ist die schnellen Einzahlungen, die Vertrauen schaffen.
spinbettercasino.de|
ChillgerN4zef
15 Oct 25 at 10:16 pm
Сначала врач проводит экспресс-диагностику. Измеряются давление, пульс, сатурация, температура, оценивается неврологический статус и уровень обезвоживания. Уточняются аллергии, хронические заболевания, длительность и объём употребления, принимаемые препараты. При необходимости выполняется ЭКГ, чтобы исключить острые риски со стороны сердечно-сосудистой системы.
Получить дополнительные сведения – https://narkolog-na-dom-krasnogorsk6.ru/
JosephVem
15 Oct 25 at 10:20 pm
1win app qeydiyyat [url=1win5004.com]1win5004.com[/url]
1win_ocoi
15 Oct 25 at 10:21 pm
Thanks a bunch for sharing this with all of us you actually
realize what you’re speaking about! Bookmarked. Please also talk over with my web site =).
We can have a link exchange contract between us
lipödem therapie
15 Oct 25 at 10:21 pm