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!
My brother suggested I might like this web site. He was totally right.
This post truly made my day. You can not imagine simply how
much time I had spent for this information! Thanks!
Ám sát tổng thống
13 Sep 25 at 11:28 am
«Как отмечает врач-нарколог Иван Петрович Смирнов, «вывод из запоя должен проводиться исключительно под наблюдением специалистов, поскольку риски для организма при резком прекращении употребления алкоголя чрезвычайно высоки».»
Выяснить больше – [url=https://vyvod-iz-zapoya-rostov-na-donu14.ru/]нарколог вывод из запоя в ростове-на-дону[/url]
RafaelMum
13 Sep 25 at 11:31 am
Ik ben dol op sweet bonanza, ga vooral door – de content is top!
winst verhogen
winst verhogen
13 Sep 25 at 11:31 am
сайт mostbet [url=https://www.mostbet12009.ru]сайт mostbet[/url]
mostbet_hhsl
13 Sep 25 at 11:34 am
Мы готовы предложить документы любых учебных заведений, расположенных на территории всей Российской Федерации. Приобрести диплом университета:
[url=http://empleo.infosernt.com/employer/diplomiki/]купить аттестаты за 11 класс в школе[/url]
Diplomi_etPn
13 Sep 25 at 11:42 am
Друууууг, РЅСѓ РіРґРµ Р¶Рµ трееек……
https://linkin.bio/hollypughhol
Плюсы: качество супер, цена отличная, вес по госту
Harryunsag
13 Sep 25 at 11:43 am
В «РостовМедЦентре» лечение начинается с подробной оценки факторов риска и мотивации. Клиническая команда анализирует стаж употребления, тип вещества, эпизоды срывов, соматический фон, лекарства, которые пациент принимает постоянно, и уровень социальной поддержки. Уже на первой встрече составляется «дорожная карта» на ближайшие 72 часа: диагностический минимум, объём медицинских вмешательств, пространство для психологической работы и точки контроля. Безопасность — не абстракция: скорости инфузий рассчитываются в инфузомате, седацию подбирают по шкалам тревоги и с обязательным контролем сатурации, а лекарственные взаимодействия сверяет клинический фармаколог. Пациент получает прозрачные цели на день, на неделю и на месяц — без обещаний мгновенных чудес и без стигмы.
Узнать больше – https://narkologicheskaya-klinika-rostov-na-donu14.ru/chastnaya-narkologicheskaya-klinika
Jackiemoips
13 Sep 25 at 11:44 am
мостбет вход официальный сайт [url=mostbet12003.ru]mostbet12003.ru[/url]
mostbet_qget
13 Sep 25 at 11:47 am
canadianpharmacyworld com [url=https://truenorthpharm.shop/#]TrueNorth Pharm[/url] TrueNorth Pharm
Michaelphype
13 Sep 25 at 11:48 am
Hello There. I found your blog using msn. This is an extremely well written article.
I’ll make sure to bookmark it and come back to read more
of your useful information. Thanks for the post.
I’ll certainly comeback.
bandar slot
13 Sep 25 at 11:48 am
Наркологический выезд включает несколько последовательных шагов, каждый из которых направлен на стабилизацию состояния пациента.
Исследовать вопрос подробнее – [url=https://narkolog-na-dom-v-krasnodare14.ru/]вызвать врача нарколога на дом[/url]
PetermEn
13 Sep 25 at 11:49 am
Wow that was strange. I just wrote an incredibly long
comment but after I clicked submit my comment didn’t show up.
Grrrr… well I’m not writing all that over again. Regardless, just wanted to say great blog!
Amazing
13 Sep 25 at 11:49 am
https://www.haikudeck.com/presentations/EnHYStIxIf
ChrisBooff
13 Sep 25 at 11:52 am
Мы практикуем минимально достаточную фармакотерапию и предсказуемые алгоритмы. Это означает — никакой полипрагмазии, никаких «универсальных капельниц», никакого «сделаем всё сразу». Сначала — безопасность (дыхание, гемодинамика, сознание), затем — управляемая детоксикация с коррекцией водно-электролитного баланса и седацией только по показаниям, после — «тихий режим» и восстановление сна, и уже на этом фоне — поведенческие навыки, работа с триггерами, переговоры с семьёй о правилах поддержки. Такой порядок убирает хаос, снижает тревогу и делает ремиссию не подвигом, а реальной рутиной.
Разобраться лучше – [url=https://narkologicheskaya-klinika-ryazan14.ru/]платная наркологическая клиника[/url]
AnthonyRah
13 Sep 25 at 11:54 am
vjcn,tn [url=http://mostbet12009.ru/]http://mostbet12009.ru/[/url]
mostbet_vxsl
13 Sep 25 at 11:56 am
Hi, I do think this is an excellent blog. I stumbledupon it 😉 I may return once again since i have bookmarked it.
Money and freedom is the best way to change, may you be rich and continue
to guide other people.
Yupoo Gucci
13 Sep 25 at 11:58 am
1win casino зеркало
1win casino зеркало
13 Sep 25 at 11:58 am
Восстановление после запоя: шаги к нормальной жизни в Туле Проблема алкоголизма затрагивает множество людей, и реабилитация после запоя, ключевой момент на пути к здоровой жизни. В Туле доступны различные наркологические услуги, включая консультации у наркологов и выездные медицинские услуги. Нарколог на дом клиника Клиники предлагают программы восстановления, которые включают психотерапию при алкоголизме и эмоциональную поддержку. Поддержка семьи также является важной составляющей в процессе реабилитации. Кризисные центры и группы поддержки в Туле помогают зависимым справиться с трудностями, обеспечивая социальную адаптацию. Важно обратиться к специалистам для получения помощи и начать путь к здоровой жизни.
lechenietulaNeT
13 Sep 25 at 12:03 pm
1win casino зеркало
1win casino зеркало
13 Sep 25 at 12:06 pm
Мы предлагаем документы институтов, которые находятся на территории всей РФ. Купить диплом о высшем образовании:
[url=http://art-gsm.ru/forum/?PAGE_NAME=profile_view&UID=107176/]аттестат купить 11 классов 2013[/url]
Diplomi_mpPn
13 Sep 25 at 12:06 pm
I think the admin of this website is in fact working hard
in favor of his web page, because here every information is quality based information.
Feel free to visit my web page – hunting boots waterproof
hunting boots waterproof
13 Sep 25 at 12:07 pm
В общем, хотелось бы вас оповестить и другим может пригодится.
https://baskadia.com/user/fzuf
Кто Сѓ Чемикала РІ последнее время брал РћРџРў ( РѕС‚ 1 РљР“ Рё более) !!! Р’СЃРµ РћРљ?????? РћРџРў давно кто получал???? Задержки были…..?????
Harryunsag
13 Sep 25 at 12:07 pm
https://saludfrontera.shop/# farmacia pharmacy mexico
JeremyBip
13 Sep 25 at 12:10 pm
1wun [url=http://1win12006.ru]http://1win12006.ru[/url]
1win_xgkn
13 Sep 25 at 12:10 pm
При выводе из запоя в Ростове-на-Дону используются разные терапевтические подходы. Основной задачей является устранение токсинов и восстановление работы систем организма. Врач подбирает терапию индивидуально в зависимости от состояния пациента и длительности запоя.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-rostov-na-donu14.ru/]анонимный вывод из запоя ростов-на-дону[/url]
RafaelMum
13 Sep 25 at 12:10 pm
Такая схема позволяет комплексно воздействовать на организм и уменьшить риски осложнений.
Ознакомиться с деталями – [url=https://narkolog-na-dom-v-krasnodare14.ru/]нарколог на дом вывод краснодар[/url]
PetermEn
13 Sep 25 at 12:11 pm
I’m not sure why but this site is loading incredibly
slow for me. Is anyone else having this problem or is it a issue on my end?
I’ll check back later and see if the problem still exists.
Also visit my homepage; jagdschuhe
jagdschuhe
13 Sep 25 at 12:14 pm
бк мост бет [url=www.mostbet12003.ru]www.mostbet12003.ru[/url]
mostbet_yvet
13 Sep 25 at 12:16 pm
mostbet ckachat [url=www.mostbet12003.ru]mostbet ckachat[/url]
mostbet_cpet
13 Sep 25 at 12:17 pm
В «РостовМедЦентре» лечение начинается с подробной оценки факторов риска и мотивации. Клиническая команда анализирует стаж употребления, тип вещества, эпизоды срывов, соматический фон, лекарства, которые пациент принимает постоянно, и уровень социальной поддержки. Уже на первой встрече составляется «дорожная карта» на ближайшие 72 часа: диагностический минимум, объём медицинских вмешательств, пространство для психологической работы и точки контроля. Безопасность — не абстракция: скорости инфузий рассчитываются в инфузомате, седацию подбирают по шкалам тревоги и с обязательным контролем сатурации, а лекарственные взаимодействия сверяет клинический фармаколог. Пациент получает прозрачные цели на день, на неделю и на месяц — без обещаний мгновенных чудес и без стигмы.
Детальнее – [url=https://narkologicheskaya-klinika-rostov-na-donu14.ru/]наркологическая клиника цены в ростове-на-дону[/url]
Jackiemoips
13 Sep 25 at 12:20 pm
We are a bunch of volunteers and opening a brand new scheme in our community.
Your site offered us with helpful information to work on. You’ve done a formidable process and
our entire neighborhood will likely be thankful to you.
Posología y administración
13 Sep 25 at 12:21 pm
диплом с занесением в реестр купить [url=https://www.educ-ua13.ru]диплом с занесением в реестр купить[/url] .
Diplomi_hmpn
13 Sep 25 at 12:21 pm
такая же хрень пропал продаван ((( уже неделю обещает выслать трек дать и нет не чего *((((
https://yamap.com/users/4808467
Оставляйте свои отзывы! Мы ценим каждого клиента нам важны ваши отзывы и мнения!
Harryunsag
13 Sep 25 at 12:32 pm
Je suis accro a Stake Casino, ca degage une ambiance de jeu aussi brulante qu’une lave en fusion. La selection du casino est un torrent de plaisirs, avec des machines a sous de casino modernes et enflammees. Le support du casino est disponible 24/7, offrant des solutions claires et instantanees. Les gains du casino arrivent a une vitesse explosive, quand meme des recompenses de casino supplementaires feraient tout peter. En somme, Stake Casino est une pepite pour les fans de casino pour les joueurs qui aiment parier avec panache au casino ! En plus l’interface du casino est fluide et eclatante comme un volcan, donne envie de replonger dans le casino sans fin.
jouer sur stake en france|
zanyglowtoad4zef
13 Sep 25 at 12:35 pm
Als nieuwe speler heb je namelijk de mogelijkheid om gebruik te maken van onze casino welkomstbonus.
Dit heeft onder andere te maken met de voorkeur van jij,
de speler. Elke gokkast heeft weer zijn eigen voor- en nadelen en zal daarom
ook een ander type speler aanspreken. Elke bedrijf heeft weer
specialismen en unieke features die je op deze manier kan leren kennen. Probeer dus gewoon rustig uit met onze demo gokkasten en kies op die manier een spel uit dat
je leuk vindt. Online gokkasten bedien je met een klik op je muis, terwijl je bij fysieke
gokkasten aan een hendel moet trekken. Wellicht
ben je al bekend met een aantal van deze ontwikkelaars, bijvoorbeeld
omdat je hun slot gokkasten bij ons hebt gespeeld.
Wellicht dat je deze slots gokkast al wel eens gespeeld hebt bij ons.
De kans is groot dat je wel eens een slots gokkast van NetEnt gespeeld
hebt. Dit zijn gokautomaten waar je naast het winnen van geld via de reguliere combinaties
ook nog kans maakt op een jackpot. Hierbij gaat het specifiek om klassiekers
uit fysieke casino’s waar ze online varianten van hebben ontwikkeld.
roulette spelen gratis
13 Sep 25 at 12:35 pm
Такая схема позволяет комплексно воздействовать на организм и уменьшить риски осложнений.
Получить дополнительные сведения – [url=https://narkolog-na-dom-v-krasnodare14.ru/]помощь нарколога на дому[/url]
Robertosaids
13 Sep 25 at 12:36 pm
Мы готовы предложить документы институтов, расположенных на территории всей РФ. Заказать диплом любого университета:
[url=http://pakalljob.pk/companies/diplomiki/]купить аттестат за 11 класс украине[/url]
Diplomi_fmPn
13 Sep 25 at 12:37 pm
Woah! I’m really digging the template/theme of this website.
It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between superb usability and appearance.
I must say that you’ve done a awesome job with this.
Additionally, the blog loads super fast for me on Safari.
Superb Blog!
WertalmPro
13 Sep 25 at 12:39 pm
best online pharmacy in india: order medicine without prescription – medicine online india
Charlesdyelm
13 Sep 25 at 12:42 pm
скачать казино 1win [url=www.1win12006.ru]www.1win12006.ru[/url]
1win_gqkn
13 Sep 25 at 12:54 pm
Задержка усиливает риск судорог, делирия, аритмий и травм. Эти маркеры не требуют медицинского образования — их легко распознать. Если совпадает хотя бы один пункт ниже, свяжитесь с нами 24/7: мы подскажем безопасный формат старта и подготовим пространство к визиту.
Разобраться лучше – https://narkologicheskaya-klinika-ryazan14.ru/narkologiya-v-ryazani/
AnthonyRah
13 Sep 25 at 12:54 pm
сколько стоит купить диплом в киеве [url=www.educ-ua4.ru]сколько стоит купить диплом в киеве[/url] .
Diplomi_qlPl
13 Sep 25 at 12:54 pm
It’s perfect time to make some plans for the future and it is time to be happy.
I’ve read this post and if I could I desire to suggest
you some interesting things or suggestions. Perhaps you can write next
articles referring to this article. I want to read even more things about it!
buôn bán nội tạng
13 Sep 25 at 12:55 pm
Наконец-то пришёл товар. Упакован отлично, РєСѓСЂРёРє РІСЃРµ передал, РІ этом проблем нет. Пришли РґРѕРјРѕР№, распечатали РїРѕ РІРёРґСѓ РїРѕС…РѕР¶Рµ РЅР° регу, РЅРѕ РІ РІРѕРґРµ разболталось. РњСѓР¶ поставился внутривенно, СЏ отписала chemical, РѕРЅ РіРѕРІРѕСЂРёС‚ РјРѕР» для РІРІ нет инструкции. РџРѕС…СѓР№, растворили РІ РІРѕРґРµ, выпили,Р РќРРҐРЈРЇ! НОЛЬ! РќРµ РїСЂРёС…РѕРґР° РЅРё тяги, РЅРё С…СѓСЏРіРё. Пусто. Р’ аське пишу, молчит. РҐР·.
https://www.impactio.com/researcher/leramoseeing
Получил трек 4 февраля, трек РЅРµ бьется РЅР° сайте РїРѕ сей день…
Harryunsag
13 Sep 25 at 12:56 pm
Medicament information for patients. Generic Name.
can i order valtrex pill
Some about medicines. Get now.
can i order valtrex pill
13 Sep 25 at 12:57 pm
SaludFrontera: SaludFrontera – los algodones pharmacy online
Charlesdyelm
13 Sep 25 at 12:58 pm
«Как отмечает врач-нарколог Алексей Николаевич Прудников, «выезд нарколога на дом — это возможность стабилизировать состояние пациента в привычной обстановке, снизив стресс и риски осложнений».»
Подробнее можно узнать тут – https://narkolog-na-dom-v-krasnodare14.ru/krasnodar-narkologicheskaya-klinika
Robertosaids
13 Sep 25 at 12:59 pm
Hi, I check your blog on a regular basis. Your humoristic style is
awesome, keep doing what you’re doing!
bandar toto macau
13 Sep 25 at 12:59 pm
купить свидетельство о заключении брака [url=www.educ-ua5.ru]www.educ-ua5.ru[/url] .
Diplomi_oqKl
13 Sep 25 at 1:03 pm
This is very interesting, You’re a very
skilled blogger. I have joined your rss feed and look forward to seeking
more of your great post. Also, I have shared your
website in my social networks!
Soulmate Sketch reviews
13 Sep 25 at 1:04 pm