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!
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 5:44 am
Наркологическая клиника в Твери предлагает широкий спектр услуг, охватывающих все этапы лечения и восстановления.
Подробнее тут – http://narkologicheskaya-klinika-v-tveri0.ru/
KevinWer
18 Sep 25 at 5:45 am
оператор чпу вакансия Вахта – это форма организации труда, при которой работники выполняют свои трудовые обязанности на значительном удалении от места постоянного проживания. При этом, создаются специальные условия для проживания, отдыха и питания в вахтовых поселках. Работа вахтой позволяет привлекать специалистов для выполнения работ в удаленных регионах, где не хватает местных трудовых ресурсов.
Jameswendy
18 Sep 25 at 5:46 am
Good web site you have got here.. It’s difficult to find high-quality writing like
yours nowadays. I really appreciate people like you!
Take care!!
onbola
18 Sep 25 at 5:46 am
Такая комплексность обеспечивает воздействие на физические, психологические и социальные факторы зависимости.
Разобраться лучше – http://lechenie-alkogolizma-omsk0.ru
Michaeltuh
18 Sep 25 at 5:47 am
https://mp-digital.ru/
ThomasSOB
18 Sep 25 at 5:47 am
OpelGaming adalah situs slot online dan togel terpercaya dengan RTP tertinggi di Indonesia.
Hadir dengan berbagai pilihan game slot gacor, jackpot
terbesar, dan sistem transaksi cepat serta aman. Bergabunglah sekarang dan nikmati pengalaman bermain yang menguntungkan!!!
opelgaming
18 Sep 25 at 5:49 am
раздвижные карнизы [url=razdvizhnoj-elektrokarniz.ru]razdvizhnoj-elektrokarniz.ru[/url] .
razdvijnoi elektrokarniz_mfei
18 Sep 25 at 5:49 am
займ все [url=www.zaimy-14.ru/]www.zaimy-14.ru/[/url] .
zaimi_fpSr
18 Sep 25 at 5:50 am
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Ознакомиться с отчётом – https://turkishbeadart.com/choose-your-right-candle-for-each-room
TimothyAcura
18 Sep 25 at 5:52 am
Онлайн сервис военнослужащих: подал рапорт на отпуск, одобрили за день. расчёт довольствия росгвардия
Brentagila
18 Sep 25 at 5:54 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
А что дальше? – https://verenafranke.com/ernahrungstrends-2022
DavidCen
18 Sep 25 at 5:54 am
Hey just wanted to give you a brief heads up
and let you know a few of the images aren’t loading properly.
I’m not sure why but I think its a linking issue.
I’ve tried it in two different internet browsers and both show the same outcome.
ثبت نام کتاب درسی ابتدایی
18 Sep 25 at 5:54 am
https://xn--krken21-bn4c.com
Howardreomo
18 Sep 25 at 5:55 am
[url=https://1deposit.net/]1 dollar deposit casinos canada[/url]
CliftonPilky
18 Sep 25 at 5:55 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2web at
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 5:56 am
все займы на карту [url=http://www.zaimy-15.ru]все займы на карту[/url] .
zaimi_vdpn
18 Sep 25 at 5:57 am
мфо займ [url=www.zaimy-14.ru]www.zaimy-14.ru[/url] .
zaimi_qvSr
18 Sep 25 at 5:57 am
The speed of transactions makes it easy to check the http://www.metoprololvslopressor.com on the Internet is always the lowest.
NcrrFlulk
18 Sep 25 at 5:57 am
You have made some decent points there. I checked on the web to learn more about the issue and found most individuals will go along with your views on this
site.
آدرس دانشگاه زنجان
18 Sep 25 at 5:58 am
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 5:59 am
https://blaukraftde.shop/# online apotheke deutschland
Williamves
18 Sep 25 at 5:59 am
Вывод из запоя в Перми включает использование комплекса медикаментозных и психотерапевтических методик. Они помогают не только снять симптомы интоксикации, но и стабилизировать эмоциональное состояние.
Разобраться лучше – http://vyvod-iz-zapoya-perm0.ru/vyvod-iz-zapoya-na-domu-perm/
WilliamUNDEK
18 Sep 25 at 5:59 am
Такая структура позволяет обеспечить эффективность и безопасность лечения на каждом этапе.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-perm0.ru/]нарколог вывод из запоя[/url]
WilliamUNDEK
18 Sep 25 at 6:00 am
Hey there, You have done a great job. I’ll definitely digg it and personally suggest to my friends.
I am confident they will be benefited from this web site.
Mariana
18 Sep 25 at 6:00 am
https://wirtube.de/a/andrewsmithuuuc/video-channels
Timothyces
18 Sep 25 at 6:01 am
Undeniably believe that that you said. Your favorite justification seemed to be on the net the easiest thing to consider of.
I say to you, I definitely get irked even as people think about
issues that they plainly don’t recognize about. You managed to hit the nail upon the highest
as smartly as defined out the entire thing with no need side-effects , folks can take a signal.
Will probably be again to get more. Thanks
Brinveldor
18 Sep 25 at 6:01 am
I don’t even know how I ended up here, but I
thought this post was great. I do not know
who you are but definitely you’re going to a famous blogger if you are not already 😉 Cheers!
رشته های شرط معدل دانشگاه دولتی
18 Sep 25 at 6:02 am
Some don’t ask a sales clerk for the https://metoprololvslopressor.com/ pills using this comparative listing
NcrrFlulk
18 Sep 25 at 6:02 am
все онлайн займы [url=http://zaimy-15.ru/]все онлайн займы[/url] .
zaimi_xwpn
18 Sep 25 at 6:03 am
исторические фильмы [url=http://www.kinogo-14.top]исторические фильмы[/url] .
kinogo_cmEl
18 Sep 25 at 6:04 am
микро займы онлайн [url=https://www.zaimy-11.ru]https://www.zaimy-11.ru[/url] .
zaimi_tsPt
18 Sep 25 at 6:04 am
Estou completamente ressonado por JonBet Casino, tem um ritmo de jogo que ecoa como um coral. As escolhas sao vibrantes como um sino. com slots tematicos de aventuras sonoras. Os agentes sao rapidos como uma onda sonora. disponivel por chat ou e-mail. Os pagamentos sao lisos como uma corda. de vez em quando mais bonus seriam um diferencial ressonante. No geral, JonBet Casino promete uma diversao que e uma onda sonora para quem curte apostar com estilo harmonico! Vale dizer a plataforma vibra com um visual ressonante. tornando cada sessao ainda mais ressonante.
jogo jonbet|
twistycosmicllama3zef
18 Sep 25 at 6:05 am
фильмы ужасов смотреть онлайн [url=https://www.kinogo-15.top]фильмы ужасов смотреть онлайн[/url] .
kinogo_jdsa
18 Sep 25 at 6:05 am
легально купить диплом о высшем образовании [url=http://educ-ua11.ru/]http://educ-ua11.ru/[/url] .
Diplomi_jzPi
18 Sep 25 at 6:07 am
It’s truly very complex in this busy life
to listen news on Television, therefore I only use internet for
that purpose, and get the latest news.
1 omgprice6.cc
18 Sep 25 at 6:07 am
все займы онлайн на карту [url=http://www.zaimy-14.ru]все займы онлайн на карту[/url] .
zaimi_xgSr
18 Sep 25 at 6:07 am
kraken darknet 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
18 Sep 25 at 6:08 am
микрозайм всем [url=https://zaimy-15.ru/]https://zaimy-15.ru/[/url] .
zaimi_skpn
18 Sep 25 at 6:08 am
Tourists fined and banned from Venice for swimming in canal
[url=https://trip-scan.co]трипскан сайт[/url]
A couple from the United Kingdom had to cut their vacation in Venice short after being caught swimming in the Grand Canal.
The 35-year-old British man and his 25-year-old Romanian girlfriend were forced to return to their home in the UK on Thursday, the same day they arrived in the city, after gondoliers reported them to local police for taking a dip in the canal.
The pair were fined €450 ($529) each and expelled from Venice for 48 hours, marking the 1,136th such sanction to be handed down to badly behaved tourists in the city so far this year, according to the Venice City Police.
The unnamed couple took the plunge near the Accademia bridge near St. Mark’s Square and gondoliers at the Rio San Vidal kiosk immediately called authorities, who removed them from the water.
“I thank the gondoliers for their cooperation and timely reporting,” said Venice Security Councillor Elisabetta Pesce in a statement published by city authorities on Friday.
https://trip-scan.co
трип скан
“Venice must be defended from those who disrespect it: protecting the city means ensuring decorum for residents and visitors who experience it with civility.”
Swimming in the Venice canals is prohibited for a variety of reasons, including the intense boat traffic and the cleanliness — or lack thereof — of the water, according to the city’s tourism ministry.
Of the 1,136 orders of expulsion from the city so far this year, about 10 were for swimming.
Related article
Tourists take photographs on the Rialto Bridge in Venice, Italy, on Saturday, April 8, 2023. Italy’s upcoming budget outlook will probably incorporate a higher growth forecast for 2023 followed by a worsened outlook for subsequent years, according to people familiar with the matter. Photographer: Andrea Merola/Bloomberg via Getty Images
Rising waters and overtourism are killing Venice. Now the fight is on to save its soul
“Since the beginning of the year, we have issued a total of 1,136 orders of expulsion for incidents of degradation and uncivilized behavior,” Venice local police deputy commander Gianni Franzoi said in a statement shared with CNN.
Poor visitor behavior is one of the worst byproducts of overtourism, Franzoi said, and incidents are on the rise.
In July 2024, an Australian man was fined and expelled for diving off the Rialto Bridge after his friends posted about it on social media.
The year before, two French tourists were fined and expelled for skinny dipping in the canal under the moonlight. In August 2022, a German man was fined and expelled for surfing in the canal.
Related article
Aerial view of the plagued ghost island of Poveglia in the Venetian lagoon
‘Haunted’ Venice island to become a locals-only haven where tourists are banned
Venice’s authorities have been trying to balance the need for visitor income with residents’ demands for a city that works for them.
Day trippers now pay a €10 entrance fee on summer weekends and during busy periods throughout the year.
The city has also banned tour groups of more than 25 people, loudspeakers and megaphones, and even standing on narrow streets to listen to tour guides.
“It was necessary to establish a system of penalties that would effectively deter potential violations,” Pesce said when the ordinance was passed in February.
“Our goal remains to combat all forms of irregularities related to overtourism in the historic lagoon city center,” she added.
“The new rules for groups accompanied by guides encourage a more sustainable form of tourism, while also ensuring greater protection and safety in the city and better balancing the needs of Venice residents and visitors.”
Brandonjex
18 Sep 25 at 6:09 am
Военная пенсия онлайн удобна, даже с мобильного. Для 2025 учла все повышения ДД на 4,5% в октябре. рапорт на отсрочку
Brentagila
18 Sep 25 at 6:10 am
Лечение начинается с всестороннего обследования, которое позволяет оценить стадию зависимости и общее состояние пациента. Это обследование помогает сформировать персонализированную программу терапии, учитывающую все особенности конкретного случая. Медикаментозное лечение направлено на детоксикацию, устранение абстинентного синдрома и поддержку функций жизненно важных органов.
Подробнее – https://narkologicheskaya-klinika-omsk0.ru/narkologi-omska
Tommydub
18 Sep 25 at 6:10 am
все онлайн займы [url=http://zaimy-14.ru]http://zaimy-14.ru[/url] .
zaimi_twSr
18 Sep 25 at 6:11 am
It’s appropriate time to make a few plans for the future and it is time to be happy.
I’ve learn this submit and if I could I wish to counsel you some attention-grabbing
issues or advice. Perhaps you could write subsequent articles
relating to this article. I desire to learn more things about it!
Crownmark Dexlin
18 Sep 25 at 6:11 am
электрокарниз двухрядный [url=https://razdvizhnoj-elektrokarniz.ru/]https://razdvizhnoj-elektrokarniz.ru/[/url] .
razdvijnoi elektrokarniz_mhei
18 Sep 25 at 6:11 am
купить диплом в чернигове недорого [url=www.educ-ua10.ru]купить диплом в чернигове недорого[/url] .
Diplomi_krKl
18 Sep 25 at 6:13 am
Лечение алкоголизма в Перми в условиях специализированной клиники обеспечивает высокий уровень безопасности и результативности. Пациенты получают квалифицированную помощь в комфортных условиях и под наблюдением опытных специалистов.
Подробнее тут – [url=https://lechenie-alkogolizma-perm0.ru/]лечение алкоголизма анонимно пермь[/url]
Timothygep
18 Sep 25 at 6:13 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Узнай первым! – https://mitinews.com/%E0%B8%82%E0%B9%88%E0%B8%B2%E0%B8%A7%E0%B8%8A%E0%B8%B2%E0%B8%A2%E0%B9%81%E0%B8%94%E0%B8%99/%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%A5%E0%B8%82%E0%B8%B2%E0%B8%98%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A8%E0%B8%B9%E0%B8%99%E0%B8%A2%E0%B9%8C%E0%B8%AD%E0%B8%B3%E0%B8%99%E0%B8%A7%E0%B8%A2
JamesHaf
18 Sep 25 at 6:14 am
[url=https://1deposit.net/]1 dollar deposit[/url]
CliftonPilky
18 Sep 25 at 6:14 am
Je trouve absolument boomerang Boomerang Casino, ca vibre avec une energie de casino digne d’un lancer. vibre avec un cercle de jeux varies. avec des machines a sous de casino modernes et circulaires. Le support du casino est disponible 24/7. assurant un support de casino immediat et boomerang. se deroulent comme une rhapsodie de ricochets. quand meme des recompenses de casino supplementaires feraient revenir. Dans l’ensemble, Boomerang Casino cadence comme une sonate de victoires pour les amoureux des slots modernes de casino! En plus la plateforme du casino brille par son style ricochet. amplifie l’immersion totale dans le casino.
boomerang casino einzahlungsbonus|
twirlshadowlynx2zef
18 Sep 25 at 6:15 am