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!
В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
Все материалы собраны здесь – https://hidupsenang.com/cara-trade-saham
JamesTup
19 Aug 25 at 12:17 pm
купить водительские права
Darrenheets
19 Aug 25 at 12:20 pm
Awesome article.
UK88.COM
19 Aug 25 at 12:22 pm
https://linkin.bio/moore_sharont80834
WilliamTop
19 Aug 25 at 12:24 pm
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Получить полную информацию – https://taxipuntacanamacao.com/transfer/index.php/2024/02/19/hola-mundo
MatthewCof
19 Aug 25 at 12:25 pm
Safe access to generic ED medication: KamaMeds – Non-prescription ED tablets discreetly shipped
ElijahKic
19 Aug 25 at 12:26 pm
В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
Подробнее – https://freshforest.in/2013/12/30/just-a-cool-blog-post-with-images
EdwinWep
19 Aug 25 at 12:30 pm
купить аттестат 11 класс фото [url=www.arus-diplom25.ru/]купить аттестат 11 класс фото[/url] .
Diplomi_zbot
19 Aug 25 at 12:30 pm
https://www.med2.ru/story.php?id=147095
DennisseK
19 Aug 25 at 12:30 pm
Согласен с предыдущим оратором, и в дополнение хочу сказать:
Особенно понравился материал про cyq.ru.
Вот, делюсь ссылкой:
[url=https://cyq.ru]https://cyq.ru[/url]
Если есть вопросы, задавайте.
rusPoito
19 Aug 25 at 12:30 pm
Hi there! Do you know if they make any plugins to assist with SEO?
I’m trying to get my blog to rank for some targeted keywords but I’m not
seeing very good results. If you know of any please
share. Appreciate it!
호빠
19 Aug 25 at 12:31 pm
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Только факты! – https://www.solni.pl/2024/05/16/witaj-swiecie
JamesTup
19 Aug 25 at 12:34 pm
Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
Ознакомиться с полной информацией – https://oficinas.unsch.edu.pe/ocri/convocatoria-de-becas-de-maestria-en-la-universidad-rey-juan-carlos
EdwinWep
19 Aug 25 at 12:35 pm
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Что ещё нужно знать? – https://pueblaroja.mx/muere-nino-11-anos-jugando-futbol-escuela-puebla
MatthewCof
19 Aug 25 at 12:36 pm
Hello There. I found your blog the use of msn. That is a really smartly
written article. I will make sure to bookmark it and return to learn more of your useful info.
Thank you for the post. I will definitely return.
megaweb2.at
19 Aug 25 at 12:37 pm
viagra for sale in uk cheap: SildenaPeak – buy brand viagra
PeterTEEFS
19 Aug 25 at 12:38 pm
He has had more cordial, more productive, meetings with US President Donald Trump since that now-notorious encounter on February 28.
[url=https://kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7inst.com]kraken3yvbvzmhytnrnuhsy772i6dfobofu652e27f5hx6y5cpj7rgyd onion[/url]
But for Ukrainian President Volodymyr Zelensky, today’s meeting at the White House will surely trigger awkward memories of that very public clash with the US President almost six months ago. Navigating the treacherous waters in which he finds himself today will be no easier.
[url=https://kraken2trfqodidvlh4a37cpzfrhdlfldhve5nf7njhumwr7instad.com]kraken6gf6o4rxewycqwjgfchzgxyfeoj5xafqbfm4vgvyaig2vmxvyd onion[/url]
Increasingly, it appears likely he will be told to give up land in exchange for some sort of security guarantees.
The land side of that “deal” will be obvious. It can be drawn on a map. Crimea: gone, says Trump. Donetsk: give all of it up, says Putin, apparently with Trump’s blessing.
But the security guarantees? That’s where far more challenging ideas, like credibility, come into play. Could Zelensky rely on the US to deliver on some NATO Article 5-type promise, to defend Ukraine if Russia breaches any peace agreement?
Putin himself might even see an opportunity to further weaken the West, by testing any such guarantees, confident they are a bluff he could call. But all that would be for the future.
For now, it looks like Zelensky will have to weigh up whether he could bring his country with him if he were to cede territory to Russia – some of it still in Ukrainian hands – or whether he and his people could bear the costs of potentially defying Trump a Nobel Peace Prize, and say no.
If he chose the latter, would the US President immediately end all remaining American support for Ukraine, in terms of military aid and intelligence sharing, for instance?
If that happened, to what extent could Zelensky’s European allies really step in and fill in the gaps left by any full US retreat?
It is an almost impossibly hard choice before him.
kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33ad
https://kraken4qzqnoi7ogpzpzwrxk7mw53n5i56loydwiyonu4owxsh4g67yd0.com
ThomasNib
19 Aug 25 at 12:43 pm
https://tripscan01.win/
Robertwen
19 Aug 25 at 12:43 pm
доставка морем из Китая авиаперевозки из китая
Richardcep
19 Aug 25 at 12:44 pm
https://pixelfed.tokyo/ltmthr33Sanndnew
WilliamTop
19 Aug 25 at 12:45 pm
https://pxlmo.com/sandersonnlily12
Danielevemy
19 Aug 25 at 12:45 pm
Hello to every single one, it’s in fact a pleasant for me
to pay a quick visit this website, it includes helpful
Information.
99ok
19 Aug 25 at 12:46 pm
This is my first time visit at here and i am truly pleassant to read all at single place.
macauslot88 link alternatif
19 Aug 25 at 12:49 pm
Mitolyn is a natural supplement designed to support healthy
metabolism and energy production by targeting the mitochondria, often called the “powerhouses” of the cells.
Its formula focuses on improving fat-burning efficiency, reducing fatigue, and boosting overall
vitality. Many people see it as a helpful option for maintaining a healthy weight
and staying energized throughout the day.
Mitolyn
19 Aug 25 at 12:49 pm
He has had more cordial, more productive, meetings with US President Donald Trump since that now-notorious encounter on February 28.
[url=https://kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7instad7.com]kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7instad onion[/url]
But for Ukrainian President Volodymyr Zelensky, today’s meeting at the White House will surely trigger awkward memories of that very public clash with the US President almost six months ago. Navigating the treacherous waters in which he finds himself today will be no easier.
[url=https://kraken2trfqodidvlh4a37cpzfrhdlfldhve5nf7njhumwr7instad.com]kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7instad.onion[/url]
Increasingly, it appears likely he will be told to give up land in exchange for some sort of security guarantees.
The land side of that “deal” will be obvious. It can be drawn on a map. Crimea: gone, says Trump. Donetsk: give all of it up, says Putin, apparently with Trump’s blessing.
But the security guarantees? That’s where far more challenging ideas, like credibility, come into play. Could Zelensky rely on the US to deliver on some NATO Article 5-type promise, to defend Ukraine if Russia breaches any peace agreement?
Putin himself might even see an opportunity to further weaken the West, by testing any such guarantees, confident they are a bluff he could call. But all that would be for the future.
For now, it looks like Zelensky will have to weigh up whether he could bring his country with him if he were to cede territory to Russia – some of it still in Ukrainian hands – or whether he and his people could bear the costs of potentially defying Trump a Nobel Peace Prize, and say no.
If he chose the latter, would the US President immediately end all remaining American support for Ukraine, in terms of military aid and intelligence sharing, for instance?
If that happened, to what extent could Zelensky’s European allies really step in and fill in the gaps left by any full US retreat?
It is an almost impossibly hard choice before him.
kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33ad
https://kraken4qzqnoi7ogpzpzwrxk7mw53n5i56loydwiyonu4owxsh4g67ydonion.info
ScottWorse
19 Aug 25 at 12:49 pm
Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
Что ещё? Расскажи всё! – https://pharmacy.ishan.ac/news-and-events/celebration-of-world-pharmacist-day
DonaldRop
19 Aug 25 at 12:51 pm
My spouse and I stumbled over here coming from a different web
address and thought I might as well check things out.
I like what I see so now i am following you.
Look forward to looking at your web page repeatedly.
macauslot88
19 Aug 25 at 12:55 pm
Hi! Quick question that’s completely off topic. Do you know how to make your site mobile
friendly? My site looks weird when viewing from my iphone 4.
I’m trying to find a template or plugin that might be able
to fix this issue. If you have any recommendations, please share.
Many thanks!
بهترین رشته های دانشگاه فرهنگیان نی نی سایت
19 Aug 25 at 12:55 pm
Howdy I am so excited I found your weblog, I really found you
by accident, while I was searching on Digg for something else,
Anyhow I am here now and would just like to say thanks a lot
for a fantastic post and a all round entertaining
blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have book-marked it
and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic work.
Zeno Flow Engine
19 Aug 25 at 12:57 pm
https://wanderlog.com/view/nextwdggog/купить-кокаин-марихуану-мефедрон-люблин/shared
WilliamTop
19 Aug 25 at 1:06 pm
I simply couldn’t go away your site prior to suggesting that I really loved the standard information a person supply to
your guests? Is going to be again continuously in order to investigate cross-check new posts
https://promosimple.com/ps/3a955/pin
19 Aug 25 at 1:07 pm
I like the valuable info you provide in your articles.
I will bookmark your weblog and check again here frequently.
I’m quite sure I’ll learn lots of new stuff right
here! Good luck for the next!
با تراز ۵۰۰۰ انسانی چی قبول میشم ۱۴۰۴
19 Aug 25 at 1:10 pm
Excellent, what a website it is! This web site presents valuable information to us, keep it up.
phising
19 Aug 25 at 1:14 pm
Heya i am for the first time here. I found this board and I in finding It really useful &
it helped me out much. I’m hoping to provide something back and help others such as you helped me.
유흥알바
19 Aug 25 at 1:14 pm
курсы английского языка для взрослых Курсы английского для взрослых: Индивидуальный подход Мы понимаем, что у каждого студента свои уникальные потребности и цели. Поэтому наши курсы разработаны с учетом различных уровней владения языком и предлагают гибкий график занятий.
Dennisgaw
19 Aug 25 at 1:16 pm
Hi are using WordPress for your site platform? I’m new to
the blog world but I’m trying to get started and set up my own. Do you
need any coding knowledge to make your own blog?
Any help would be really appreciated!
آموزش مصاحبه فرهنگیان
19 Aug 25 at 1:18 pm
viagra soft tabs uk: SildenaPeak – SildenaPeak
PeterTEEFS
19 Aug 25 at 1:18 pm
As the admin of this web site is working, no question very quickly it will be famous, due to its quality contents.
https://smartbuildforum.com.ua/hermetyk-dlya-far-yakyj-vybraty-i-chomu.html
GichardMam
19 Aug 25 at 1:20 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Обратитесь за информацией – https://apee.bg/%D0%BA%D0%B0%D0%BA%D0%B2%D0%BE-%D0%B5-%D0%BA%D0%B8%D0%BB%D0%BE%D0%B2%D0%B0%D1%82%D1%87%D0%B0%D1%81
DonaldRop
19 Aug 25 at 1:26 pm
https://www.themeqx.com/forums/users/ifuceghoihy/
JustinTup
19 Aug 25 at 1:26 pm
https://www.montessorijobsuk.co.uk/author/sucxiagab/
Michaelmot
19 Aug 25 at 1:31 pm
It’s great that you are getting ideas from this paragraph as well as from
our argument made here.
تراز معدل ۱۴۰۴
19 Aug 25 at 1:35 pm
Thanks for the auspicious writeup. It if truth be told
was a leisure account it. Look complicated to far brought agreeable from you!
However, how can we keep in touch?
تا رتبه چند پزشکی قبول میشه ۱۴۰۴
19 Aug 25 at 1:38 pm
Pretty! This has been an incredibly wonderful post.
Thank you for providing this info.
prorn download
19 Aug 25 at 1:40 pm
I know this if off topic but I’m looking into starting my
own weblog and was wondering what all is needed to get set up?
I’m assuming having a blog like yours would cost a pretty
penny? I’m not very internet savvy so I’m not 100% sure.
Any suggestions or advice would be greatly appreciated.
Thanks
nohu 90
19 Aug 25 at 1:43 pm
Right away I am ready to do my breakfast, later than having my breakfast coming over
again to read further news.
gta 5 download for pc highly compressed
19 Aug 25 at 1:44 pm
В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
Переходите по ссылке ниже – https://www.dubaivibesmagazine.ae/coya-dubais-vibrant-friday-brunch-is-back
Kennethclorp
19 Aug 25 at 1:44 pm
2-комнатные квартиры от Унистрой Казань Новостройки у метро Проспект Победы Казань: Развитая инфраструктура и современные комплексы Новостройки у метро Проспект Победы в Казани предлагают жизнь в районе с развитой инфраструктурой и современными жилыми комплексами.
AllenLib
19 Aug 25 at 1:47 pm
https://www.themeqx.com/forums/users/adddoegyebid/
JustinTup
19 Aug 25 at 1:47 pm
An interesting discussion is worth comment. There’s no doubt that that you ought to publish more about this subject matter, it might not be a taboo subject but
typically people do not talk about these topics.
To the next! All the best!!
فرهنگیان چه رشته هایی دارد
19 Aug 25 at 1:48 pm