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://mannerkraft.com/# medikament ohne rezept notfall
EnriqueVox
17 Sep 25 at 2:00 pm
купить диплом в хмельницком [url=educ-ua4.ru]educ-ua4.ru[/url] .
Diplomi_dcPl
17 Sep 25 at 2:02 pm
Eh eh, calm pom ρi pі, mathematics is one from the top disciplines at Junior College, laying base іn A-Level calculus.
In aɗdition from institution amenities, concentrate оn math f᧐r prevent typical pitfalls ѕuch as careless errors ⅾuring exams.
Eunoia Junior College represents modern-ɗay development in education, wіth its
higһ-rise school integrating community ɑreas
foг collaborative knowing аnd growth. Tһe college’s
focus on gorgeous thinking promotes intellectual іnterest
and goodwill, supported bʏ vibrant programs
in arts, sciences, аnd leadership. Modern centers, consisting оf performing arts locations, mаke it ρossible foг
trainees tо exlore passions and develop talents holistically.
Collaborations ԝith prestigious organizations supply
enhancing opportunities fοr гesearch and international direct exposure.
Students emerge аѕ thoughtful leaders, аll set tо contribute positively tо ɑ
diverse woгld.
Temasek Junior College inspires ɑ generation of pioneers Ьy
merging time-honored customs ᴡith advanced innovation, offering extensive scholastic
programs instilled ᴡith ethical values tһat direct trainees towaгd
meaningful and impactful futures. Advanced research study centers, language
laboratories, аnd elective courses in worldwide languages ɑnd carrying оut arts
provide platforms for deep intellectual engagement,
crucial analysis, аnd innovative expedition ᥙnder the mentorship of recognized educators.
Τhe dynamic cⲟ-curricular landscape, featuring competitive
sports, creative societies, аnd entrepreneurship clubs,
cultivates team effort, leadership, аnd a spirit of innovation that
complements class learning. International
partnerships, ѕuch аs joint гesearch study projects ѡith overseas institutions аnd cultural
exchange programs, enhance trainees’ global proficiency, cultural
sensitivity, ɑnd networking abilities. Alumni from Temasek Junior
College flourish in elite ցreater education institutions and
diverse expert fields, personifying tһe school’s devotion tⲟ
quality, service-oriented leadership, аnd the pursuit of
individual and social betterment.
Wah, mathematics serves аѕ the groundwork stone of primary education, assisting kids fοr dimensional thinking fⲟr architecture paths.
Ⲟh dear, lacking strong mathematics ɗuring Junior College,
еven prestigious institution kids mɑy struggle аt high school calculations, thеrefore
cultivate this promptⅼy leh.
Oi oi, Singapore moms аnd dads, math proves ⅼikely thе most crucial primary topic, fostering
imagination fоr challenge-tackling fοr creative jobs.
Listen սp, composed pom ⲣi pi, math proves аmong
in the hіghest topics іn Junior College, establishing foundation fοr Ꭺ-Level һigher calculations.
Strong Α-level Math scores impress ԁuring NS interviews tоo.
Oi oi, Singapore folks, maths іs likeⅼy the highly essential primary subject, fostering imagination іn issue-resolving іn innovative professions.
Take а l᧐ok at my blog – a level math tutor london
a level math tutor london
17 Sep 25 at 2:02 pm
Hello, There’s no doubt that your site might be having web browser compatibility
problems. When I take a look at your website in Safari, it looks fine however, if opening
in IE, it’s got some overlapping issues. I just wanted to provide you with a quick heads up!
Besides that, fantastic website!
레비트라 인터넷 구매
17 Sep 25 at 2:03 pm
Мы можем предложить документы университетов, расположенных на территории всей РФ. Приобрести диплом любого ВУЗа:
[url=http://tawtheaf.com/employer/diplomiki/]бугуруслан купить аттестат 10 и 11 класс[/url]
Diplomi_llPn
17 Sep 25 at 2:05 pm
купить диплом украины [url=http://educ-ua20.ru/]купить диплом украины[/url] .
Diplomi_inEn
17 Sep 25 at 2:06 pm
купить аттестат за 11 класс с занесением в реестр отзывы [url=arus-diplom25.ru]купить аттестат за 11 класс с занесением в реестр отзывы[/url] .
Diplomi_nxot
17 Sep 25 at 2:07 pm
купить диплом спб занесением реестр [url=http://www.arus-diplom33.ru]купить диплом спб занесением реестр[/url] .
Diplomi_snSa
17 Sep 25 at 2:08 pm
https://vgarderobe.ru/zhenskie-khudi-na-molnii-eddie-bauer-bc-5746.html
StanleyToumb
17 Sep 25 at 2:08 pm
где можно купить аттестат за 11 [url=https://www.educ-ua17.ru]где можно купить аттестат за 11[/url] .
Diplomi_qiSl
17 Sep 25 at 2:10 pm
купить диплом специалиста дешево [url=http://www.educ-ua5.ru]купить диплом специалиста дешево[/url] .
Diplomi_hnKl
17 Sep 25 at 2:10 pm
Мы можем предложить документы институтов, расположенных в любом регионе Российской Федерации. Купить диплом университета:
[url=http://silton.ru/forum/user/9340/]аттестат купить 11 кл дипломы тумен кипятком[/url]
Diplomi_yuPn
17 Sep 25 at 2:11 pm
купить диплом младшего специалиста в украине [url=https://educ-ua4.ru/]купить диплом младшего специалиста в украине[/url] .
Diplomi_fcPl
17 Sep 25 at 2:12 pm
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
17 Sep 25 at 2:12 pm
аниме смотреть онлайн [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_cvol
17 Sep 25 at 2:13 pm
Great items from you, man. I’ve take into accout your stuff prior to and you are simply too fantastic.
I really like what you have received here,
really like what you’re stating and the way in which you say it.
You are making it entertaining and you continue to
care for to stay it smart. I can not wait to
read much more from you. This is actually a terrific site.
turkey visa for australian
17 Sep 25 at 2:15 pm
купить аттестат об окончании 9 классов [url=https://educ-ua20.ru]купить аттестат об окончании 9 классов[/url] .
Diplomi_phEn
17 Sep 25 at 2:15 pm
купить аттестаты за 11 в челябинске [url=www.arus-diplom25.ru]купить аттестаты за 11 в челябинске[/url] .
Diplomi_vkot
17 Sep 25 at 2:16 pm
купить диплом высшем образовании занесением реестр [url=http://www.arus-diplom33.ru]купить диплом высшем образовании занесением реестр[/url] .
Diplomi_apSa
17 Sep 25 at 2:17 pm
за1мы онлайн [url=https://zaimy-11.ru]https://zaimy-11.ru[/url] .
zaimi_zhPt
17 Sep 25 at 2:17 pm
смотреть боевики [url=kinogo-15.top]смотреть боевики[/url] .
kinogo_xrsa
17 Sep 25 at 2:18 pm
советские фильмы смотреть онлайн бесплатно [url=https://www.kinogo-14.top]https://www.kinogo-14.top[/url] .
kinogo_uaEl
17 Sep 25 at 2:19 pm
купить диплом магистра [url=https://educ-ua5.ru/]купить диплом магистра[/url] .
Diplomi_vfKl
17 Sep 25 at 2:19 pm
фантастика онлайн [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_gcol
17 Sep 25 at 2:20 pm
диплом купить с внесением в реестр [url=http://arus-diplom33.ru/]диплом купить с внесением в реестр[/url] .
Diplomi_mqSa
17 Sep 25 at 2:22 pm
купить диплом недорого [url=www.educ-ua4.ru]купить диплом недорого[/url] .
Diplomi_vfPl
17 Sep 25 at 2:22 pm
купить диплом легальный [url=https://educ-ua13.ru/]купить диплом легальный[/url] .
Diplomi_lwpn
17 Sep 25 at 2:23 pm
займы все онлайн [url=https://zaimy-11.ru]https://zaimy-11.ru[/url] .
zaimi_kjPt
17 Sep 25 at 2:24 pm
В клинике «Решение+» предусмотрены оба основных формата: выезд на дом и лечение в стационаре. Домашний вариант подойдёт тем, чьё состояние относительно стабильно, нет риска тяжёлых осложнений. Врач приезжает с полным комплектом оборудования и медикаментов, проводит капельницу на дому и даёт инструкции по дальнейшему уходу.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-noginsk5.ru/]narkologiya-vyvod-iz-zapoya[/url]
DavidFuh
17 Sep 25 at 2:24 pm
фантастика онлайн [url=https://www.kinogo-15.top]фантастика онлайн[/url] .
kinogo_dhsa
17 Sep 25 at 2:25 pm
фильмы hd 1080 смотреть бесплатно [url=http://kinogo-14.top]http://kinogo-14.top[/url] .
kinogo_arEl
17 Sep 25 at 2:25 pm
купить диплом украины цена [url=http://educ-ua20.ru/]купить диплом украины цена[/url] .
Diplomi_pmEn
17 Sep 25 at 2:26 pm
With havin so much written content do you ever run into any issues of
plagorism or copyright infringement? My website has a lot of completely unique content I’ve either written myself or outsourced but it seems a lot of it is popping it up all over the internet without my permission. Do you know any
techniques to help prevent content from being stolen? I’d truly appreciate it.
bitcoin gambling sites
17 Sep 25 at 2:26 pm
купить аттестат за 11 класс казахстан [url=arus-diplom25.ru]купить аттестат за 11 класс казахстан[/url] .
Diplomi_dvot
17 Sep 25 at 2:27 pm
Tourists fined and banned from Venice for swimming in canal
[url=https://trip-scan.co]tripscan top[/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
tripscan top
“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.”
Donnellbut
17 Sep 25 at 2:28 pm
Hi everyone, it’s my first pay a visit at this web site, and article is truly fruitful in favor of me, keep up posting these types of articles.
на сайте tutbonus.com
Fobertsax
17 Sep 25 at 2:29 pm
взо [url=https://www.zaimy-11.ru]https://www.zaimy-11.ru[/url] .
zaimi_miPt
17 Sep 25 at 2:29 pm
купить аттестат за 9 класс украина [url=http://educ-ua5.ru]http://educ-ua5.ru[/url] .
Diplomi_gnKl
17 Sep 25 at 2:30 pm
сериалы онлайн [url=http://www.kinogo-14.top]http://www.kinogo-14.top[/url] .
kinogo_hnEl
17 Sep 25 at 2:31 pm
смотреть фильмы бесплатно [url=https://www.kinogo-15.top]смотреть фильмы бесплатно[/url] .
kinogo_uhsa
17 Sep 25 at 2:31 pm
купить диплом киев сколько [url=https://educ-ua18.ru]https://educ-ua18.ru[/url] .
Diplomi_tcPi
17 Sep 25 at 2:31 pm
I loved as much as you will receive carried out right here.
The sketch is attractive, your authored material stylish. nonetheless,
you command get got an edginess over that you wish be delivering the following.
unwell unquestionably come more formerly again as exactly the same nearly very
often inside case you shield this increase.
Genius Wave Reviews
17 Sep 25 at 2:33 pm
смотреть комедии онлайн [url=kinogo-12.top]kinogo-12.top[/url] .
kinogo_nvol
17 Sep 25 at 2:33 pm
купить диплом медсестры с занесением в реестр [url=www.educ-ua13.ru/]www.educ-ua13.ru/[/url] .
Diplomi_ckpn
17 Sep 25 at 2:33 pm
советские фильмы смотреть онлайн бесплатно [url=https://kinogo-12.top]https://kinogo-12.top[/url] .
kinogo_caol
17 Sep 25 at 2:37 pm
kamagra erfahrungen deutschland: generisches sildenafil alternative – In welchen europäischen Ländern ist Viagra frei verkäuflich
Donaldanype
17 Sep 25 at 2:37 pm
Самостоятельно выйти из запоя — почти невозможно. В Краснодаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Подробнее – [url=https://vyvod-iz-zapoya-krasnodar11.ru/]нарколог на дом недорого в краснодаре[/url]
QuincyTrine
17 Sep 25 at 2:38 pm
купить диплом об образовании в запорожье [url=https://educ-ua6.ru]купить диплом об образовании в запорожье[/url] .
Diplomi_gtMl
17 Sep 25 at 2:39 pm
диплом реестр купить [url=https://www.educ-ua13.ru]диплом реестр купить[/url] .
Diplomi_bfpn
17 Sep 25 at 2:39 pm
установка крун
Williamcem
17 Sep 25 at 2:40 pm