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!
It’s really a nice and useful piece of info. I’m satisfied that you shared this helpful info with
us. Please keep us informed like this. Thank you for sharing.
fence installation contractor Windsor
18 Sep 25 at 6:43 pm
Когда организм на пределе, важна срочная помощь в Краснодаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Получить больше информации – [url=https://vyvod-iz-zapoya-krasnodar15.ru/]нарколог на дом клиника город краснодар[/url]
BrandonAttet
18 Sep 25 at 6:43 pm
Ключевая задача первичного этапа — безопасно купировать абстинентный синдром и обеспечить постепенный метаболический «выход» без резких колебаний давления и частоты сердечных сокращений. Дополнительно оцениваются когнитивные и аффективные проявления, нарушения сна, уровень тревоги и наличие сопутствующих воспалительных процессов. По результатам обследования формируется индивидуальный план лечения с учетом предшествующего анамнеза, толерантности к препаратам и возможной полипрагмазии.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-doneczk0.ru/]вывод из запоя на дому недорого переулок панфилова, 36[/url]
Antoniotut
18 Sep 25 at 6:44 pm
Близкий человек в запое? Не ждите ухудшения. Обратитесь в клинику — здесь проведут профессиональный вывод из запоя с последующим восстановлением организма.
Разобраться лучше – [url=https://vyvod-iz-zapoya-krasnodar16.ru/]помощь вывод из запоя в городе[/url]
RichardRig
18 Sep 25 at 6:44 pm
Everything is very open with a clear description of the challenges.
It was really informative. Your website is useful. Thank you for sharing!
زمان اعلام نتایج امتحانات نهایی شهریور ۱۴۰۴
18 Sep 25 at 6:44 pm
You’re so awesome! I don’t think I have read a single thing like that before.
So wonderful to find another person with unique thoughts on this subject.
Seriously.. thanks for starting this up. This website
is one thing that is required on the web, someone with a bit of originality!
윈조이포커머니상
18 Sep 25 at 6:45 pm
Здравствуйте!
Хотите купить постоянный виртуальный номер? Мы предоставляем виртуальные номера для смс навсегда, которые подойдут для любых целей. Виртуальный номер обеспечивает удобство и надежность связи. Постоянный виртуальный номер – это выбор для тех, кто ищет простое и эффективное решение. Начните пользоваться нашими услугами уже сейчас.
Полная информация по ссылке – https://marcobkuc07519.dailyhitblog.com/32197077/alles-wat-je-moet-weten-over-mobiele-nummers-in-duitsland-een-diepgaande-verkenning
виртуальный номер, купить виртуальный номер, виртуальный номер
Виртуальный номер, купить виртуальный номер для смс навсегда, Виртуальный номер навсегда
Удачи и комфорта в общении!
Nomersulge
18 Sep 25 at 6:47 pm
купить щебень Асфальтовая крошка
pesko-144
18 Sep 25 at 6:47 pm
Hello there! I could have sworn I’ve been to this site
before but after checking through some of the post I realized it’s new to
me. Nonetheless, I’m definitely glad I found it
and I’ll be book-marking and checking back often!
roofing companies near me
18 Sep 25 at 6:47 pm
ПГС карьерный доставка купить песчано-гравийную смесь
pesko-47
18 Sep 25 at 6:50 pm
Hi mates, nice piece of writing and nice urging commented at
this place, I am Probate Law Firm in Utah fact enjoying by these.
Probate Law Firm in Utah
18 Sep 25 at 6:50 pm
гравий для бетона глина цена за куб
pesko-333
18 Sep 25 at 6:51 pm
plug in prague buy weed prague
prague-drugs-830
18 Sep 25 at 6:53 pm
https://autoreleases.ru
LarrySuish
18 Sep 25 at 6:55 pm
magnificent issues altogether, you simply received a new reader.
What might you suggest about your publish that you simply made a few days ago?
Any certain?
سامانه کارا آموزش و پرورش ثبت اعتراض
18 Sep 25 at 6:57 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 6:58 pm
Сайт lovespace.ua призывает купить услуги по телефонному скаму, проституции ,а также гомик клубам в Киеве и Украине. По ссылке ниже вы можешь забронировать шулерство, шлюху ,а также педика.
мошенничество на олх
skamlAlema
18 Sep 25 at 7:03 pm
На логотипах автоматов изображены
главные герои, потому выбрать тему
игры достаточно легко.
casino cat
18 Sep 25 at 7:04 pm
What’s up friends, its enormous piece of writing concerning tutoringand fully explained, keep it up all the time.
Also visit my site: Westwood Utah Probate Law
Westwood Utah Probate Law
18 Sep 25 at 7:10 pm
автоматический карниз для штор [url=www.razdvizhnoj-elektrokarniz.ru]www.razdvizhnoj-elektrokarniz.ru[/url] .
razdvijnoi elektrokarniz_mrei
18 Sep 25 at 7:11 pm
I used to be able to find good information from your blog posts.
AxiWert
18 Sep 25 at 7:11 pm
Пошаговая структура помогает удерживать стабильную динамику, своевременно оценивать прогресс и гибко корректировать тактику.
Изучить вопрос глубже – https://narkologicheskaya-klinika-lugansk0.ru/narkologicheskij-dispanser-lugansk/
Lemuelanism
18 Sep 25 at 7:14 pm
Whats up are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and set
up my own. Do you require any coding expertise to make your own blog?
Any help would be really appreciated!
mua bảo hiểm y tế
18 Sep 25 at 7:15 pm
https://evertrustmeds.com/# Ever Trust Meds
AntonioRaX
18 Sep 25 at 7:15 pm
I was wondering if you ever thought of changing the layout of your site?
Its very well written; I love what youve got
to say. But maybe you could a little more in the way of content so people could connect with it better.
Youve got an awful lot of text for only having 1 or two pictures.
Maybe you could space it out better?
Feel free to surf to my webpage: Novara Recovery Center Virginia
Novara Recovery Center Virginia
18 Sep 25 at 7:16 pm
Quality articles is the main to attract the viewers to visit the site,
that’s what this web page is providing.
IGP file application
18 Sep 25 at 7:16 pm
Hi mates, nice paragraph and fastidious urging commented at this place, I am genuinely enjoying by these.
АУФ казино зеркало
18 Sep 25 at 7:19 pm
https://xn--krken21-bn4c.com
Howardreomo
18 Sep 25 at 7:20 pm
https://arttex-salon.ru
LarrySuish
18 Sep 25 at 7:21 pm
I do believe all of the ideas you’ve presented to your post.
They’re very convincing and can certainly work.
Nonetheless, the posts are very short for beginners.
May just you please extend them a bit from
subsequent time? Thank you for the post.
BTC Income
18 Sep 25 at 7:23 pm
prague drugs prague drugstore
prague-drugs-144
18 Sep 25 at 7:26 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 7:27 pm
you’re really a excellent webmaster. The web site loading pace is amazing.
It seems that you’re doing any distinctive trick. Furthermore, The contents are masterwork.
you’ve performed a magnificent activity in this matter!
آدرس دانشگاه آزاد اسلامی واحد تهران شمال
18 Sep 25 at 7:28 pm
список займов онлайн на карту [url=https://www.zaimy-15.ru]https://www.zaimy-15.ru[/url] .
zaimi_inpn
18 Sep 25 at 7:29 pm
Этот краткий обзор предлагает сжатую информацию из области медицины, включая ключевые факты и последние новости. Мы стремимся сделать информацию доступной и понятной для широкой аудитории, что позволит читателям оставаться в курсе актуальных событий в здравоохранении.
Неизвестные факты о… – https://mobilenotebooks.ru/ispolzuya-silu-koda-borba-s-alkogolizmom-v-moskve
Philipboigo
18 Sep 25 at 7:29 pm
Big savings are possible when you synthroidvslevothyroxine.com from.
EcrFlulk
18 Sep 25 at 7:29 pm
After going over a number of the blog articles on your blog, I honestly appreciate your way of writing a
blog. I saved as a favorite it to my bookmark website list
and will be checking back in the near future.
Take a look at my website as well and tell me how you feel.
księgowy Stratford
18 Sep 25 at 7:30 pm
Ever Trust Meds: EverTrustMeds – Ever Trust Meds
DerekStops
18 Sep 25 at 7:32 pm
Откройте для себя удобство и стиль, используя [url=https://karniz-s-privodom.ru]карнизы с электроприводом|карнизы с электроприводом для штор|потолочные карнизы с электроприводом|карнизы с электроприводом и дистанционным управлением|карнизы с электроприводом цена|карнизы с электроприводом купить|карнизы с электроприводом с дистанционным управлением|карнизы с электроприводом и дистанционным|карнизы с электроприводом и пультом управления купить|Карнизы с электроприводом[/url] для вашего дома!
Установка карнизов с электроприводом часто является простой задачей.
Prokarniz
18 Sep 25 at 7:32 pm
CPL (Cost Per Lead) https://cost-per-lead1.ru ключевая метрика рекламы. Узнайте, что это, как правильно рассчитывать стоимость лида, где применяется и как помогает оценить эффективность кампаний.
Nathanvep
18 Sep 25 at 7:39 pm
Cialis without a doctor prescription [url=http://evertrustmeds.com/#]Buy Tadalafil 20mg[/url] EverTrustMeds
Michealstilm
18 Sep 25 at 7:39 pm
Военная ипотека 2025 с взносом 383 979 руб. — калькулятор показал, что накоплений хватит на первоначальный взнос в 20%. ипотека участникам СВО
Brentagila
18 Sep 25 at 7:39 pm
Доброго!
Купите виртуальный номер телефона навсегда и наслаждайтесь свободой общения. Постоянный виртуальный номер подходит для смс, мессенджеров и регистрации аккаунтов. Мы предлагаем удобные и надежные номера с возможностью долгосрочного использования. Виртуальный номер для смс навсегда – это стабильность и безопасность. Выбирайте проверенные решения для своих задач.
Полная информация по ссылке – https://best-rated-solar-heater-f71488.blogrenanda.com/30762746/virtueel-nummer
постоянный виртуальный номер, купить виртуальный номер, купить виртуальный номер для смс навсегда
купить номер телефона навсегда, виртуальный номер, купить виртуальный номер навсегда
Удачи и комфорта в общении!
Nomersulge
18 Sep 25 at 7:40 pm
накрутка подписчиков в тг канал
JohnnyPhido
18 Sep 25 at 7:43 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 7:44 pm
Kaizenaire.cߋm curates deals fгom Singapore’s
preferred business fߋr supreme cost savings.
Singapore’s allure аs a shopping paradise іs enhanced by Singaporeans wh᧐ transform promotions into
get-togethers and shared happiness.
Scuba diving trips tⲟ close-by islands adventure underwater explorers fгom Singapore, and қeep
in mind to stay updated ߋn Singapore’s most гecent promotions
ɑnd shopping deals.
The Social Foot offers stylish, comfortable footwear, loved ƅy
active Singaporeans for thеіr mix ߋf fashion ɑnd feature.
CapitaLand Investment establishes аnd manages residential properties ѕia, cherished by Singaporeans
fοr their iconic shopping malls аnd domestic rooms lah.
Suntory freshens wіth teas and waters, favored for costs Japanese drinks іn benefit stores.
Singaporeans, ԁo not kay kiang leh, rely upߋn Kaizenaire.com for аll your deal-hunting requires one.
Аlso visit my web site – singapore promotion
singapore promotion
18 Sep 25 at 7:44 pm
Great post.
Net Rowdex
18 Sep 25 at 7:46 pm
https://gigeya-med.ru
LarrySuish
18 Sep 25 at 7:47 pm
First off I would like to say excellent blog! I had a quick question that I’d like to ask if you
do not mind. I was curious to find out how you center yourself and
clear your head prior to writing. I have
had difficulty clearing my thoughts in getting my thoughts out there.
I do take pleasure in writing however it just seems like the first 10 to 15 minutes
are generally wasted just trying to figure out how
to begin. Any recommendations or tips? Appreciate it!
online slots for real money
18 Sep 25 at 7:51 pm
креативные горшки для цветов [url=http://www.dizaynerskie-kashpo-nsk.ru]креативные горшки для цветов[/url] .
dizainerskie kashpo_obSa
18 Sep 25 at 7:51 pm