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!
купить диплом продавца [url=https://www.rudik-diplom11.ru]купить диплом продавца[/url] .
Diplomi_zfMi
19 Oct 25 at 4:54 am
купить диплом в владивостоке [url=http://rudik-diplom4.ru/]купить диплом в владивостоке[/url] .
Diplomi_euOr
19 Oct 25 at 4:55 am
купить диплом медсестры [url=www.rudik-diplom1.ru]купить диплом медсестры[/url] .
Diplomi_paer
19 Oct 25 at 4:55 am
регистрация перепланировки [url=www.soglasovanie-pereplanirovki-kvartiry4.ru/]регистрация перепланировки[/url] .
soglasovanie pereplanirovki kvartiri _nmOr
19 Oct 25 at 4:56 am
football africain telecharger 1xbet
parifoot-522
19 Oct 25 at 4:56 am
Experience Singapore’ѕ favored shopping website at
Kaizenaire.cοm, curating a vast selection оf promotions,
deals, ɑnd occasion specials fгom cherished brand names.
Singapore’s allure аs a shopping paradise is intensified
ƅy Singaporeans ԝho can not withstand diving rіght into every
promo аnd deal on deal.
Parlor game nights wіth buddies are a popular indoor task in bustling Singapore, аnd keep
іn mind to stay updated on Singapore’s newest promotions ɑnd shopping deals.
Mash-Up offеrs city streetwear ɑnd accessories, adored by youthful Singaporeans fⲟr theiг cool,
casual vibes.
The Closet Lover supplies economical trendy clothing ⲟne,
preferred Ƅy budget-conscious fashionistas іn Singapore for
theiг constant updates mah.
Dian Xiao Ꭼr roasts organic ducks аnd Chinese pгices, beloved Ьʏ Singaporeans fоr flavorful marinades
and family-style dining.
Eh, Singaporeans, Ьetter check Kaizenaire.com consistently lah, ցot
ɑll the most reсent shopping deals ɑnd promotions tⲟ save your pocketbook ߋne.
my blog – promotion
promotion
19 Oct 25 at 4:57 am
купить диплом о высшем образовании с занесением в реестр в красноярске [url=http://frei-diplom4.ru]купить диплом о высшем образовании с занесением в реестр в красноярске[/url] .
Diplomi_bnOl
19 Oct 25 at 4:57 am
экспертиза перепланировки квартиры [url=http://www.soglasovanie-pereplanirovki-kvartiry3.ru]http://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _ugPi
19 Oct 25 at 4:59 am
диплом техникума казахстана купить [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_fzea
19 Oct 25 at 5:01 am
где можно купить диплом медсестры [url=www.frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_xkkt
19 Oct 25 at 5:01 am
OMT’s interesting video clip lessons transform complex math concepts гight into amazing tales,
assisting Singapore pupils love tһe subject and feel inspired tⲟ ace their
exams.
Broaden yⲟur horizons wіth OMT’s upcoming new physical ɑrea օpening in Septembeг 2025,
offering еven morе opportunities for hands-on mathematics
expedition.
Сonsidered thаt mathematics plays ɑ critical function іn Singapore’s
financial advancement аnd progress, buying specialized
math tuition gears սp trainees ѡith
the prοblem-solvingskills needed to prosper in a competitive landscape.
primary school school math tuition іs іmportant
for PSLE preparation аs it assists students master tһe
foundational principles like portions and decimals,
ᴡhich are ցreatly checked іn the exam.
Routine simulated О Level tests in tuition settings simulate
genuine ⲣroblems, permitting pupils tߋ fine-tune tһeir
strategy and lower mistakes.
Tuition showѕ mistake evaluation techniques, helping junior college trainees prevent common pitfalls іn A Level computations аnd evidence.
OMT’s exclusive syllabus matches tһе MOE curriculum bү offering detailed malfunctions
ߋf intricate subjects, mаking sure trainees construct а stronger fundamental understanding.
Comprehensive protection ᧐f subjects ѕia, leaving no voids in expertise fοr leading mathematics success.
Tuition іn math aids Singapore pupils ⅽreate
speed ɑnd precision, vital for completing examinations
ᴡithin time frɑme.
math tuition
19 Oct 25 at 5:02 am
купить диплом ижевск с занесением в реестр [url=frei-diplom6.ru]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_hbOl
19 Oct 25 at 5:03 am
купить диплом в энгельсе [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .
Diplomi_nhei
19 Oct 25 at 5:03 am
проект перепланировки квартиры цена [url=www.proekt-pereplanirovki-kvartiry17.ru/]проект перепланировки квартиры цена[/url] .
proekt pereplanirovki kvartiri_ebml
19 Oct 25 at 5:04 am
купить диплом судоводителя [url=www.rudik-diplom11.ru]купить диплом судоводителя[/url] .
Diplomi_kkMi
19 Oct 25 at 5:04 am
Сеть стоматологических клиник Dinstom https://dinstom.ru предлагает эффективное и безопасное лечение с использованием инновационных технологий в максимально комфортной атмосфере. Ознакомьтесь на сайте с нашими услугами – от гигиены, лечения и исправления прикуса до имплантации и комплексного протезирования винирами и коронками. У нас выгодные цены и профессиональные врачи стоматологи.
falohiaccef
19 Oct 25 at 5:05 am
купить диплом стоматолога [url=www.rudik-diplom5.ru]купить диплом стоматолога[/url] .
Diplomi_ihma
19 Oct 25 at 5:05 am
купить диплом об образовании с реестром [url=www.frei-diplom5.ru]купить диплом об образовании с реестром[/url] .
Diplomi_jmPa
19 Oct 25 at 5:05 am
Клиника «Детокс» в Краснодаре предлагает услугу вызова нарколога на дом. Врачи приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Услуга доступна круглосуточно и анонимно.
Разобраться лучше – [url=https://narkolog-na-dom-krasnodar26.ru/]нарколог на дом анонимно краснодар[/url]
DanielCaupe
19 Oct 25 at 5:05 am
услуги по узакониванию перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry4.ru/]https://soglasovanie-pereplanirovki-kvartiry4.ru/[/url] .
soglasovanie pereplanirovki kvartiri _hsOr
19 Oct 25 at 5:05 am
купить морской диплом [url=https://rudik-diplom9.ru/]купить морской диплом[/url] .
Diplomi_tnei
19 Oct 25 at 5:06 am
kraken онлайн
кракен маркет
JamesDaync
19 Oct 25 at 5:07 am
купить диплом медсестры [url=https://frei-diplom13.ru/]купить диплом медсестры[/url] .
Diplomi_klkt
19 Oct 25 at 5:09 am
купить диплом медбрата [url=https://rudik-diplom10.ru/]купить диплом медбрата[/url] .
Diplomi_umSa
19 Oct 25 at 5:10 am
диплом о высшем образовании с занесением в реестр купить [url=frei-diplom6.ru]диплом о высшем образовании с занесением в реестр купить[/url] .
Diplomi_gaOl
19 Oct 25 at 5:10 am
football africain 1xbet cameroun apk
parifoot-669
19 Oct 25 at 5:11 am
цена купить диплом техникума [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_jnea
19 Oct 25 at 5:12 am
Медикаментозная детоксикация позволяет быстро и безопасно очистить организм от токсинов и продуктов распада алкоголя или наркотиков, минимизируя риски осложнений. Используются препараты, которые восстанавливают работу печени, почек и других органов, а также нормализуют электролитный баланс.
Подробнее – [url=https://narkologicheskaya-klinika-mariupol13.ru/]наркологическая клиника мариуполь[/url]
Gilbertnup
19 Oct 25 at 5:12 am
купить диплом в биробиджане [url=http://rudik-diplom5.ru/]купить диплом в биробиджане[/url] .
Diplomi_cxma
19 Oct 25 at 5:12 am
купить диплом с занесением в реестр [url=www.frei-diplom5.ru/]купить диплом с занесением в реестр[/url] .
Diplomi_cdPa
19 Oct 25 at 5:12 am
pronostic foot gratuit melbet telecharger
parifoot-742
19 Oct 25 at 5:13 am
купить диплом с занесением в реестр в калуге [url=www.frei-diplom4.ru]купить диплом с занесением в реестр в калуге[/url] .
Diplomi_xjOl
19 Oct 25 at 5:14 am
согласование перепланировки квартиры москва [url=http://www.proekt-pereplanirovki-kvartiry17.ru]согласование перепланировки квартиры москва[/url] .
proekt pereplanirovki kvartiri_zoml
19 Oct 25 at 5:14 am
кто нибудь работает медсестрой по купленному диплому [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_ihkt
19 Oct 25 at 5:14 am
купить диплом в южно-сахалинске [url=https://rudik-diplom3.ru]купить диплом в южно-сахалинске[/url] .
Diplomi_feei
19 Oct 25 at 5:14 am
Tourists fined and banned from Venice for swimming in canal
[url=https://tripscan44.cc]трипскан сайт[/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://tripscan44.cc
трипскан сайт
“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.”
GregorySak
19 Oct 25 at 5:15 am
купить диплом в мурманске с занесением в реестр [url=https://frei-diplom6.ru/]купить диплом в мурманске с занесением в реестр[/url] .
Diplomi_loOl
19 Oct 25 at 5:16 am
Estou alucinado com SpellWin Casino, parece um portal mistico cheio de adrenalina. A gama do cassino e simplesmente um feitico de prazeres, incluindo jogos de mesa de cassino com um toque de magia. A equipe do cassino entrega um atendimento que e puro encantamento, com uma ajuda que reluz como uma pocao. Os saques no cassino sao velozes como um feitico de teletransporte, mas queria mais promocoes de cassino que hipnotizam. No geral, SpellWin Casino garante uma diversao de cassino que e magica para os amantes de cassinos online! De lambuja a interface do cassino e fluida e brilha como uma pocao reluzente, adiciona um toque de encantamento ao cassino.
spellwin casino login|
zestycandycrow6zef
19 Oct 25 at 5:16 am
подготовка проекта перепланировки [url=https://proekt-pereplanirovki-kvartiry17.ru]подготовка проекта перепланировки[/url] .
proekt pereplanirovki kvartiri_zvml
19 Oct 25 at 5:17 am
перепланировка [url=http://www.soglasovanie-pereplanirovki-kvartiry4.ru]перепланировка[/url] .
soglasovanie pereplanirovki kvartiri _xpOr
19 Oct 25 at 5:17 am
купить диплом во владивостоке [url=www.rudik-diplom5.ru]купить диплом во владивостоке[/url] .
Diplomi_trma
19 Oct 25 at 5:17 am
купить диплом в москве [url=http://www.rudik-diplom10.ru]купить диплом в москве[/url] .
Diplomi_caSa
19 Oct 25 at 5:17 am
I think that AquaSculpt offers such non-invasive body sculpting solutions!
I’ve read many positive experiences about their treatments.
I’m impressed by how the team addresses trouble spots.
I’m excited to see the results! Thanks for sharing this information!
For more details, check out https://buy.aquasculpt–usa.com/.
AquaSculpt usa
19 Oct 25 at 5:18 am
Купить диплом колледжа в Херсон [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_hhea
19 Oct 25 at 5:19 am
Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.
I think that you can do with some pics to drive the message home a bit,
but instead of that, this is excellent blog. An excellent read.
I will definitely be back.
시알리스 효과
19 Oct 25 at 5:20 am
купить диплом о высшем образовании с занесением в реестр [url=https://frei-diplom4.ru]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_dfOl
19 Oct 25 at 5:21 am
Прокапывание от алкоголизма в городе Красноярске – это важный шаг в борьбе с алкоголизма. Методы детоксикации способствуют справиться с признаками абстиненции и освободиться от пьянства. Лечение в специализированных центрах включает не только прокапывание‚ но и поддержку психолога‚ что помогает восстановлению после употребления спиртного. vivod-iz-zapoya-krasnoyarsk020.ru Восстановление начинается с детоксикации‚ после которой проводятся программы восстановления. Поддержка родственников также играет значимую роль в профилактике рецидивов. Анонимные алкоголики и обращение к специалиста вполне способны оказать помощь в процессе выздоровления. Не упускайте из виду‚ что лечение алкоголизма требует комплексного подхода.
narkologiyakrasnoyarskNeT
19 Oct 25 at 5:21 am
купить диплом преподавателя [url=http://rudik-diplom13.ru/]купить диплом преподавателя[/url] .
Diplomi_xoon
19 Oct 25 at 5:22 am
купить диплом в северске [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .
Diplomi_qvei
19 Oct 25 at 5:22 am
купить диплом в уфе с реестром [url=https://frei-diplom5.ru]https://frei-diplom5.ru[/url] .
Diplomi_rlPa
19 Oct 25 at 5:22 am