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!
1 win казино скачать [url=http://1win12012.ru]http://1win12012.ru[/url]
1win_mbmr
14 Sep 25 at 8:59 am
Купить диплом колледжа в Донецк [url=educ-ua7.ru]Купить диплом колледжа в Донецк[/url] .
Diplomi_ihEr
14 Sep 25 at 9:02 am
1win программа [url=https://www.1win12011.ru]1win программа[/url]
1win_imOl
14 Sep 25 at 9:05 am
Thanks for some other informative web site. Where else could I get that type of info written in such an ideal means? I have a challenge that I’m simply now running on, and I have been on the look out for such info.
Cleobetra Casino Online
EarnestAbent
14 Sep 25 at 9:05 am
I have read so many articles on the topic of the blogger lovers except
this piece of writing is truly a nice article,
keep it up.
link livebet303
14 Sep 25 at 9:08 am
Важная деталь — отсутствие полипрагмазии. Мы используем «минимально достаточную фармакотерапию»: каждый препарат имеет цель, окно эффективности и критерии отмены. Это снижает побочные эффекты, убирает «тяжесть» днём и делает восстановление более естественным.
Детальнее – [url=https://narkologicheskaya-klinika-v-spb14.ru/]платная наркологическая клиника санкт-петербург[/url]
Anthonygom
14 Sep 25 at 9:10 am
Вызов нарколога на дом сочетает медицинскую эффективность с удобством. Пациент получает квалифицированную помощь в привычной обстановке, что снижает уровень тревожности и способствует более быстрому восстановлению.
Получить больше информации – http://narkolog-na-dom-sankt-peterburg14.ru
Robertfloum
14 Sep 25 at 9:15 am
The steps to do so are the same for both YouTube
Premium and non-Premium users.
youtube shorts download mp4
14 Sep 25 at 9:17 am
Je suis fou de Roobet Casino, ca vibre avec une energie de casino totalement electro. L’assortiment de jeux du casino est un kaleidoscope de sensations, incluant des jeux de table de casino d’une elegance electrisante. Les agents du casino sont rapides comme un flash de neon, joignable par chat ou email. Les transactions du casino sont simples comme un rythme electro, quand meme des recompenses de casino supplementaires feraient danser. Au final, Roobet Casino est une pepite pour les fans de casino pour les passionnes de casinos en ligne ! De surcroit la plateforme du casino brille par son style dejante, ajoute une touche de frenesie au casino.
roobet promo|
zippyglowworm5zef
14 Sep 25 at 9:19 am
вывод 1win [url=1win12011.ru]вывод 1win[/url]
1win_crOl
14 Sep 25 at 9:19 am
This is a really good tip particularly to those new to the blogosphere.
Simple but very accurate info… Thanks for sharing
this one. A must read article!
88clb.app
14 Sep 25 at 9:19 am
Yesterday, while I was at work, my sister stole my iPad and tested to see if it
can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views.
I know this is totally off topic but I had to share it
with someone!
my site: 대밤
대밤
14 Sep 25 at 9:21 am
бк 1win скачать на андроид [url=1win12007.ru]бк 1win скачать на андроид[/url]
1win_pjpn
14 Sep 25 at 9:22 am
mostbet официальный сайт скачать [url=mostbet12011.ru]mostbet12011.ru[/url]
mostbet_vcOt
14 Sep 25 at 9:23 am
I read this article completely concerning the resemblance of
hottest and preceding technologies, it’s awesome article.
77ball
14 Sep 25 at 9:26 am
Индивидуальная программа у нас — это модульный конструктор. В одних случаях критичен блок сна, в других — профилактика вечерних «волн» тревоги, в третьих — семейная медиированная встреча. Мы гибко переставляем модули, учитывая сопутствующие заболевания, приём базовых лекарств (антигипертензивные, антиаритмические, сахароснижающие), возраст и расписание пациента. Цель проста: чтобы терапия вписалась в жизнь, а не наоборот.
Подробнее можно узнать тут – https://narkologicheskaya-klinika-ryazan14.ru/narkolog-ryazan-telefon/
AnthonyRah
14 Sep 25 at 9:27 am
I am really glad to read this website posts which contains plenty of valuable facts, thanks for providing these information.
Stream Fertinex Cap
14 Sep 25 at 9:32 am
Hello! I recently came across this fantastic article
on virtual gambling and couldn’t resist the chance to share it.
If you’re someone who’s looking to explore more about the industry of online casinos, this is definitely.
I’ve always been interested in casino games, and after reading this, I
gained so much about how online casinos work.
This post does a great job of explaining everything from tips for betting.
If you’re new to the whole scene, or even if
you’ve been gambling for years, this guide is an essential read.
I highly recommend it for anyone who needs to get more familiar with online gambling options.
Not only, the article covers some great advice about finding a
trusted online casino, which I think is extremely important.
So many people overlook this aspect, but this post really shows you the best ways to
stay safe.
What I liked most was the section on rewards and free spins, which I think is
crucial when choosing a site to play on. The insights here are priceless for anyone looking to maximize their winnings.
Furthermore, the tips about budgeting your gambling were very
helpful. The advice is clear and actionable, making it easy for gamblers to take control of their gambling
habits and stay within their limits.
The advantages and disadvantages of online gambling were
also thoroughly discussed. If you’re thinking about trying your luck at an online casino,
this article is a great starting point to understand both the
excitement and the risks involved.
If you’re into poker, you’ll find tons of valuable tips here.
The article really covers all the popular games in detail, giving you the
tools you need to improve your chances. Whether you’re
into competitive games like poker or just enjoy a casual
round of slots, this article has plenty for
everyone.
I personally appreciated the discussion about transaction methods.
It’s crucial to know that you’re gambling on a site
that’s safe and protected. It’s really helps you
make sure your personal information is in good hands when you play online.
In case you’re wondering where to start, I highly recommend reading this guide.
It’s clear, informative, and packed with valuable insights.
Without a doubt, one of the best articles I’ve come across in a
while on this topic.
So, I strongly suggest checking it out and giving
it a read. You won’t regret it! Trust me, you’ll walk away feeling like a better prepared player in the
online casino world.
Whether you’re a beginner, this post is an excellent resource.
It helps you avoid common mistakes and teaches you how
to have a fun and safe gambling experience. Definitely worth checking out!
I really liked how well-researched and thorough this article
is. I’ll definitely be coming back to it whenever I
need a refresher on casino games.
Has anyone else read it yet? What do you think? Feel free
to share!
page
14 Sep 25 at 9:33 am
диплом кулинарного техникума купить [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_ehEr
14 Sep 25 at 9:34 am
Medicament prescribing information. Brand names.
buying cheap zyban without dr prescription
Some what you want to know about medicines. Get information here.
buying cheap zyban without dr prescription
14 Sep 25 at 9:34 am
Hurrah, that’s what I was exploring for, what a information! present here at this blog, thanks admin of this web site.
turkey visa for australian
14 Sep 25 at 9:35 am
мостеб [url=https://www.mostbet12013.ru]https://www.mostbet12013.ru[/url]
mostbet_wmka
14 Sep 25 at 9:38 am
https://blogfreely.net/meghadldhn/mitos-sobre-limpiezas-rpidas-del-cuerpo-que-debes-conocer
Enfrentar un test antidoping puede ser un momento critico. Por eso, ahora tienes una alternativa confiable probada en laboratorios.
Su mezcla eficaz combina creatina, lo que estimula tu organismo y neutraliza temporalmente los metabolitos de THC. El resultado: una muestra limpia, lista para cumplir el objetivo.
Lo mas valioso es su capacidad inmediata de respuesta. A diferencia de metodos caseros, no promete limpiezas magicas, sino una estrategia de emergencia que funciona cuando lo necesitas.
Miles de postulantes ya han validado su seguridad. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si no deseas dejar nada al azar, esta solucion te ofrece seguridad.
JuniorShido
14 Sep 25 at 9:42 am
my canadian pharmacy: canadianpharmacymeds com – TrueNorth Pharm
Teddyroowl
14 Sep 25 at 9:43 am
Drugs information leaflet. What side effects can this medication cause?
naltrexone information
Some trends of medication. Read now.
naltrexone information
14 Sep 25 at 9:45 am
kraken онион kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
14 Sep 25 at 9:46 am
зеркало 1вин [url=https://www.1win12012.ru]https://www.1win12012.ru[/url]
1win_yimr
14 Sep 25 at 9:53 am
диплом занесен в реестр купить [url=https://www.arus-diplom33.ru]диплом занесен в реестр купить[/url] .
Diplomi_qySa
14 Sep 25 at 9:56 am
Если на осмотре выявляются спутанность сознания, подозрение на делирий, неукротимая рвота с примесью крови, выраженная боль в груди, тяжёлая одышка, судороги — врач немедленно предложит стационар. Безопасность важнее удобства.
Углубиться в тему – http://kapelnica-ot-zapoya-vidnoe7.ru
EugeneSoype
14 Sep 25 at 9:59 am
купить диплом об окончании [url=educ-ua7.ru]купить диплом об окончании[/url] .
Diplomi_anEr
14 Sep 25 at 10:05 am
войти в 1вин [url=http://1win12007.ru/]войти в 1вин[/url]
1win_yypn
14 Sep 25 at 10:05 am
Hi colleagues, fastidious piece of writing and nice urging commented here, I
am genuinely enjoying by these.
Fundspire Axivon Review
14 Sep 25 at 10:08 am
TrueNorth Pharm: TrueNorth Pharm – best canadian pharmacy online
Charlesdyelm
14 Sep 25 at 10:12 am
These are truly wonderful ideas in about blogging.
You have touched some nice factors here. Any way keep up wrinting.
My website :: Residential locksmith
Residential locksmith
14 Sep 25 at 10:14 am
мостбет скачать [url=https://mostbet12010.ru]https://mostbet12010.ru[/url]
mostbet_vgPt
14 Sep 25 at 10:15 am
mexican rx pharm [url=https://saludfrontera.com/#]mail order pharmacy mexico[/url] SaludFrontera
Michaelphype
14 Sep 25 at 10:15 am
mostbet [url=http://mostbet12013.ru/]http://mostbet12013.ru/[/url]
mostbet_azka
14 Sep 25 at 10:16 am
http://truenorthpharm.com/# precription drugs from canada
CarlosPreom
14 Sep 25 at 10:17 am
I have been surfing online more than 2 hours today, yet I never found any interesting article like yours.
It is pretty worth enough for me. In my opinion, if all
webmasters and bloggers made good content as you
did, the net will be much more useful than ever before.
Luce Corex
14 Sep 25 at 10:17 am
kraken ссылка на сайт kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
14 Sep 25 at 10:19 am
The electronic advertising world has evolved rapidly over the previous couple of years,
and companies now face a serious obstacle: just how to streamline
operations, handle client relationships, and supply quantifiable
results without juggling dozens of different devices. In this
write-up, we’ll take a deep dive into GoHighLevel Testimonial
(or GHL Evaluation), discovering its attributes, usability, prices, login procedure, trial alternatives, and why it has become
a go-to CRM for agencies worldwide.
Best PBN sites for backlinks
14 Sep 25 at 10:20 am
kraken зеркало kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
14 Sep 25 at 10:21 am
Узнайте все подробности о дилере Автомикс — партнёре бренда Honda, фирменный сервис, ремонт кузова и детали от производителя! Посетите [url=https://avtomiks-smolensk.ru/]https://avtomiks-smolensk.ru/[/url] и изучите версии авто. Хотите комфорт и качество — дилер предлагает пробную поездку, лицензированный сервис, оригинальные аксессуары, а также гарантийное ТО, сервис без ограничений и выгодные условия. Ищете Honda — здесь найдёте комфортный внедорожник и персональный подход.
Spravkitno
14 Sep 25 at 10:22 am
Helpful information. Fortunate me I discovered your site by chance, and I’m surprised why this twist of fate did
not happened earlier! I bookmarked it.
Visit my web page Swift locksmith Minnesota
Swift locksmith Minnesota
14 Sep 25 at 10:26 am
where to buy lamictal without prescription
order generic lamictal without insurance
14 Sep 25 at 10:30 am
best nuru massage
best nuru in thailand
nuru bangkok
nuru massage
best nuru
best massage
soapy massage
nuru bangkok
nuru sukhumvit 31
nuru sukhumvit
best nuru in thailand
14 Sep 25 at 10:30 am
I always spent my half an hour to read this website’s articles every day along with a mug of coffee.
Mountain Roofers Roof repair Phoenix
14 Sep 25 at 10:33 am
It’s awesome to visit this web page and reading
the views of all mates concerning this piece of writing, while
I am also keen of getting knowledge.
WhatsApp網頁版
14 Sep 25 at 10:38 am
kraken onion ссылка kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
14 Sep 25 at 10:38 am
купить диплом с занесением в реестр отзывы [url=http://arus-diplom33.ru/]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_nzSa
14 Sep 25 at 10:39 am