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.elektro-karniz77.ru/]www.elektro-karniz77.ru/[/url] .
elektro karniz_zrSl
15 Sep 25 at 10:39 am
https://www.te-in.ru/
Rolandmow
15 Sep 25 at 10:39 am
карниз с электроприводом [url=http://avtomaticheskie-karnizy.ru]карниз с электроприводом[/url] .
avtomaticheskie karnizi_guSa
15 Sep 25 at 10:40 am
Remain ahead in shopping wіtһ Kaizenaire.com, Singapore’ѕ leading
promotions collector.
Singaporeans сonstantly claim уes tօ a great deal, enjoying thеir city’s fame аs a first-rate shopping paradise loaded ᴡith promotions.
Gathering vinyl documents is a retro intereѕt for music-collecting
Singaporeans, ɑnd keep in mind to remɑіn updated on Singapore’s most recent promotions and shopping deals.
Masion, ⅼikely a fashion label, offers classy apparel, cherished bу graceful Singaporeans fߋr their refined
designs.
Bigo оffers live streaming аnd social enjoyment applications lor,
appreciated ƅy Singaporeans for their interactive content
and area engagement leh.
Nestlé nurtures ѡith Milo ɑnd Nescafé, loved foг comforting
warm beverages аnd childhood favorites.
Singaporeans ⅼike vaⅼue leh, ѕo make Kaizenaire.com үοur
go-to for moѕt rеcent deals one.
My skte – Recruitment agency singapore
Recruitment agency singapore
15 Sep 25 at 10:40 am
электрокарниз недорого [url=https://avtomaticheskie-karnizy-dlya-shtor.ru]https://avtomaticheskie-karnizy-dlya-shtor.ru[/url] .
avtomaticheskie karnizi dlya shtor_oyOr
15 Sep 25 at 10:41 am
В обзоре об где продать скины кс автор отмечает индивидуальные особенности каждой платформы, включая применяемые комиссии, поддерживаемые валюты, доступные методы вывода и удобство интерфейса. Особое внимание уделяется безопасности транзакций и скорости выплат — большая часть сайтов обеспечивает моментальный вывод средств или перевод денег в течение нескольких часов после продажи.
RomanNam
15 Sep 25 at 10:42 am
быстрая регистрация на мостбет [url=http://mostbet12012.ru/]быстрая регистрация на мостбет[/url]
mostbet_mvSl
15 Sep 25 at 10:43 am
mostbet.com скачать [url=http://mostbet12012.ru/]http://mostbet12012.ru/[/url]
mostbet_qxSl
15 Sep 25 at 10:44 am
Статья (продать скины за реальные деньги) даёт читателям конкретные советы по выбору площадки для продажи скинов, рекомендует создавать аккаунты на нескольких сервисах ради наиболее выгодных условий и предупреждает о необходимости изучить комиссионную политику каждой платформы перед продажей. Информация структурирована так, чтобы облегчить выбор и сделать процесс безопасным и максимально удобным независимо от региона проживания пользователя.
RomanNam
15 Sep 25 at 10:44 am
купить диплом техникума Киев [url=https://educ-ua10.ru]купить диплом техникума Киев[/url] .
Diplomi_rkKl
15 Sep 25 at 10:45 am
coГ»t du prix d’flagyl gГ©nГ©rique
comment acheter de l'flagyl
15 Sep 25 at 10:46 am
карнизы для штор купить в москве [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]карнизы для штор купить в москве[/url] .
avtomaticheskie karnizi dlya shtor_teOr
15 Sep 25 at 10:46 am
Узнайте всё об владельцах авто — диалоги, советы и новости на автофоруме! Перейдите на [url=https://n-avtoshtorki.ru]https://n-avtoshtorki.ru[/url] и присоединяйтесь актуальные автотемы. Хотите обсудить ситуацию или получить совет — площадка предлагает инструкции и лайфхаки, личные истории и новинки автомобильной жизни. Нужна помощь от тех, кто ездит — здесь найдете интересные обсуждения и важные знания.
Spravkiplt
15 Sep 25 at 10:47 am
Lineage 2 Java форум разработчиков java для lineage 2 — настройка сервера
стала проще.
форум разработчиков java для lineage 2
15 Sep 25 at 10:48 am
карнизы с электроприводом купить [url=elektro-karniz77.ru]elektro-karniz77.ru[/url] .
elektro karniz_gwSl
15 Sep 25 at 10:50 am
карниз моторизованный [url=https://elektrokarniz-cena.ru/]https://elektrokarniz-cena.ru/[/url] .
elektrokarniz cena_lsPL
15 Sep 25 at 10:51 am
карнизы для штор с электроприводом [url=https://avtomaticheskie-karnizy.ru/]карнизы для штор с электроприводом[/url] .
avtomaticheskie karnizi_dgSa
15 Sep 25 at 10:51 am
buying cheap avapro without dr prescription
buying generic avapro without a prescription
15 Sep 25 at 10:53 am
электрокарнизы цена [url=https://avtomaticheskie-karnizy-dlya-shtor.ru]электрокарнизы цена[/url] .
avtomaticheskie karnizi dlya shtor_cwOr
15 Sep 25 at 10:54 am
автоматические карнизы [url=http://www.elektrokarniz-cena.ru]автоматические карнизы[/url] .
elektrokarniz cena_loPL
15 Sep 25 at 10:54 am
диплом автотранспортного техникума купить [url=http://educ-ua10.ru]диплом автотранспортного техникума купить[/url] .
Diplomi_peKl
15 Sep 25 at 10:56 am
карниз для штор электрический [url=http://avtomaticheskie-karnizy-dlya-shtor.ru/]карниз для штор электрический[/url] .
avtomaticheskie karnizi dlya shtor_ryOr
15 Sep 25 at 10:57 am
электрокарнизы для штор цена [url=www.elektrokarniz-cena.ru]электрокарнизы для штор цена[/url] .
elektrokarniz cena_ctPL
15 Sep 25 at 10:57 am
mostbet mobile [url=https://mostbet12013.ru]https://mostbet12013.ru[/url]
mostbet_kjka
15 Sep 25 at 10:57 am
An outstanding share! I’ve just forwarded this onto a coworker who had been conducting a little homework on this.
And he in fact bought me lunch simply because I found it for him…
lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending time to talk about this matter
here on your website.
Immediate Finansor
15 Sep 25 at 10:58 am
я купил диплом с проводкой [url=https://www.arus-diplom31.ru]я купил диплом с проводкой[/url] .
Vigodno zakazat diplom ob obrazovanii!_vmOl
15 Sep 25 at 10:58 am
карниз электро [url=https://www.elektro-karniz77.ru]https://www.elektro-karniz77.ru[/url] .
elektro karniz_zdSl
15 Sep 25 at 10:59 am
электрокарнизы купить в москве [url=https://avtomaticheskie-karnizy.ru]электрокарнизы купить в москве[/url] .
avtomaticheskie karnizi_dxSa
15 Sep 25 at 11:00 am
карниз для штор с электроприводом [url=http://karniz-s-elektroprivodom.ru]карниз для штор с электроприводом[/url] .
karniz s elektroprivodom_ksKt
15 Sep 25 at 11:01 am
Every weekend i used to pay a visit this web site, as i want enjoyment, since this this web page conations really
nice funny material too.
http://app.vellorepropertybazaar.in/profile/jeffrey1651190
15 Sep 25 at 11:01 am
Статья (продать скины кс2 с выводом) даёт читателям конкретные советы по выбору площадки для продажи скинов, рекомендует создавать аккаунты на нескольких сервисах ради наиболее выгодных условий и предупреждает о необходимости изучить комиссионную политику каждой платформы перед продажей. Информация структурирована так, чтобы облегчить выбор и сделать процесс безопасным и максимально удобным независимо от региона проживания пользователя.
RomanNam
15 Sep 25 at 11:02 am
электрокарниз [url=https://elektro-karniz77.ru]электрокарниз[/url] .
elektro karniz_paSl
15 Sep 25 at 11:03 am
карнизы для штор купить в москве [url=https://www.avtomaticheskie-karnizy.ru]карнизы для штор купить в москве[/url] .
avtomaticheskie karnizi_viSa
15 Sep 25 at 11:04 am
Kaizenaire.com iѕ the heart ⲟf Singapore’s promotions scene, curating deals foг each customer.
In Singapore’s heart, shopping heaven prospers
ⲟn deals thɑt delight itѕ individuals.
Τaking part in cosplay conventions excites anime followers
іn Singapore, and bear іn mind to stay upgraded οn Singapore’s latеst promotions аnd shopping deals.
DBS, a leading banking institution іn Singapore,
supplies a vast array ⲟf monetary solutions fгom electronic financial tօ
wide range management, whicһ Singaporeans adore fⲟr their smooth combination into everyday
life.
Rye ϲreates easy women’s clothes mah, appreciated Ьy informal fashion lovers іn Singapore for theiг loosened սp yet trendy styles siа.
Ananda Bhavan supplies vegan Indian fаre liкe idlis, valued Ƅy Singaporeans
fⲟr tidy, delicious South Indian classics.
Ꭰo not say bojio lor, Kaizenaire.сom ⲟn a regular basis features the
current promotions t᧐ assist yoᥙ extend your doⅼlar sia.
My homepɑցе Whatsapp AI Chatbot
Whatsapp AI Chatbot
15 Sep 25 at 11:05 am
карниз для штор электрический [url=https://elektro-karniz77.ru/]https://elektro-karniz77.ru/[/url] .
elektro karniz_chSl
15 Sep 25 at 11:05 am
купить диплом с реестром о высшем образовании [url=https://arus-diplom33.ru/]купить диплом с реестром о высшем образовании[/url] .
Diplomi_blSa
15 Sep 25 at 11:06 am
электрокарнизы для штор [url=www.avtomaticheskie-karnizy.ru/]электрокарнизы для штор[/url] .
avtomaticheskie karnizi_zdSa
15 Sep 25 at 11:06 am
автоматический карниз для штор [url=https://elektrokarniz-cena.ru/]автоматический карниз для штор[/url] .
elektrokarniz cena_ggPL
15 Sep 25 at 11:08 am
карниз для штор с электроприводом [url=www.karniz-s-elektroprivodom.ru]карниз для штор с электроприводом[/url] .
karniz s elektroprivodom_izKt
15 Sep 25 at 11:08 am
Kaizenaire.com aggregates promotions ⅼike nothing else, topping Singapore’ѕ
shopping sites.
Singapore’ѕ shopping centers are ⲣlaces
in this shopping heaven, where deals аnd promotions preponderate f᧐r residents.
Yoga exercise classes іn calm studios helр Singaporeans
maintain equilibrium іn their hectic lives, and remember tо stay updated on Singapore’ѕ m᧐ѕt current promotions and
shopping deals.
Guardian ցives pharmacy аnd individual care items,
appreciated Ƅy Singaporeans fоr their convenient health
and wellness solutions аnd promotions.
Centuries Hotels supplies deluxe holiday accommodations ɑnd friendliness services οne, cherished ƅy
Singaporeans fߋr theiг comfy remаіns and рrime
aгeas mah.
Umami Bioworks grows lab-grown fish аnd shellfish, enjoyed fоr lasting, honest choices tߋ traditional catches.
Aiyo, Ԁo not lag behind leh, Kaizenaire.сom hаs real-tіme promotions and deals for yօu one.
my pаge … best recruitment agency in singapore for locals
best recruitment agency in singapore for locals
15 Sep 25 at 11:10 am
https://ameblo.jp/eduardoofzj381/entry-12929573128.html
Pasar una prueba de orina puede ser arriesgado. Por eso, se desarrollo una solucion cientifica con respaldo internacional.
Su formula precisa combina minerales, lo que prepara tu organismo y enmascara temporalmente los metabolitos de sustancias. El resultado: un analisis equilibrado, lista para cumplir el objetivo.
Lo mas interesante es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete resultados permanentes, sino una solucion temporal que responde en el momento justo.
Miles de estudiantes ya han experimentado su rapidez. Testimonios reales mencionan paquetes 100% confidenciales.
Si necesitas asegurar tu resultado, esta alternativa te ofrece tranquilidad.
JuniorShido
15 Sep 25 at 11:11 am
I know this web page offers quality depending articles and other material, is there any other site which presents these kinds of things in quality?
Also visit my web-site; cheaper facelift alternative London
cheaper facelift alternative London
15 Sep 25 at 11:11 am
I think tis is one of the most significant information for me.
And i am glad reading your article. But want to remark on few
general things, The website style is ideal, tthe articles is really great : D.
Good job, cheers
My web page :: JetBlack
JetBlack
15 Sep 25 at 11:13 am
электрокарнизы для штор купить [url=http://www.avtomaticheskie-karnizy.ru]http://www.avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_saSa
15 Sep 25 at 11:15 am
электрокарнизы [url=http://www.elektro-karniz77.ru]электрокарнизы[/url] .
elektro karniz_bgSl
15 Sep 25 at 11:15 am
электрокарнизы москва [url=http://avtomaticheskie-karnizy-dlya-shtor.ru]электрокарнизы москва[/url] .
avtomaticheskie karnizi dlya shtor_kqOr
15 Sep 25 at 11:15 am
карнизы для штор купить в москве [url=www.elektrokarniz-cena.ru/]карнизы для штор купить в москве[/url] .
elektrokarniz cena_utPL
15 Sep 25 at 11:15 am
Medicine information leaflet. Cautions.
metronidazole 500 mg untuk ibu hamil
Actual information about drugs. Read now.
metronidazole 500 mg untuk ibu hamil
15 Sep 25 at 11:17 am
мостбет кж [url=http://mostbet12011.ru]мостбет кж[/url]
mostbet_vlOt
15 Sep 25 at 11:18 am
электрический карниз для штор купить [url=elektrokarniz-cena.ru]электрический карниз для штор купить[/url] .
elektrokarniz cena_buPL
15 Sep 25 at 11:19 am