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://airlady.forum24.ru/?1-0-0-00000170-000-0-0-1758612824]порошковая покраска металлических изделий в Москве?[/url]
Antonioabils
18 Oct 25 at 8:52 am
Пациентам в Самаре предлагается анонимное лечение в стационаре с круглосуточным уходом и безопасными условиями.
Получить больше информации – https://vyvod-iz-zapoya-v-stacionare-samara23.ru
Williamliz
18 Oct 25 at 8:54 am
Thankfulness to my father who informed me on the topic of this weblog, this blog is
in fact remarkable.
download windows 10 crack 64 bit
18 Oct 25 at 8:54 am
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry11.ru]www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _lpMi
18 Oct 25 at 8:54 am
seoloom.click – Visuals and textual content blend well together, it gives a polished impression overall.
Roslyn Vaudreuil
18 Oct 25 at 8:54 am
keywordorbit.click – Found useful links already; seems like a solid resource worth revisiting.
Jamal Goodacre
18 Oct 25 at 8:55 am
согласовать перепланировку квартиры [url=www.soglasovanie-pereplanirovki-kvartiry14.ru/]www.soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _znEl
18 Oct 25 at 8:55 am
rankforge.click – Typography is crisp, spacing is well balanced — great for reading.
Brenda Nyreen
18 Oct 25 at 8:56 am
проектирование перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry3.ru/]soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _kbPi
18 Oct 25 at 8:56 am
Если вы ищете надежную клинику для вывода из запоя, обратитесь в «Детокс» в Краснодаре. Услуга вызова нарколога на дом доступна круглосуточно. Врачи приедут к вам в течение 1–2 часов и окажут необходимую помощь.
Углубиться в тему – [url=https://narkolog-na-dom-krasnodar25.ru/]вызвать врача нарколога на дом краснодар[/url]
JamieOvedy
18 Oct 25 at 8:57 am
заказать проект перепланировки [url=proekt-pereplanirovki-kvartiry17.ru]заказать проект перепланировки[/url] .
proekt pereplanirovki kvartiri_zfml
18 Oct 25 at 8:57 am
Слитые курсы ЕГЭ купить https://courses-ege.ru
courses-ege-781
18 Oct 25 at 8:57 am
trafficpulse.click – I found several useful links already—definitely worth revisiting later.
Marcell Ekstrom
18 Oct 25 at 8:58 am
Цифровая трансформация ускоряет развитие kraken onion ссылка кракен онион тор кракен онион зеркало кракен даркнет маркет
RichardPep
18 Oct 25 at 8:59 am
сколько стоит узаконить перепланировку в москве [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_dyPt
18 Oct 25 at 9:00 am
comprar cialis: cialis precio – comprar Cialis online España
RaymondNit
18 Oct 25 at 9:00 am
brightmarketplace – Fast shipping and excellent customer service, highly recommend shopping here.
Leatrice Denslow
18 Oct 25 at 9:01 am
Капельница от запоя в Нижнем Новгороде — эффективный способ снять симптомы похмелья и восстановить организм. Процедура проводится опытными врачами с использованием современных препаратов.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]вывод из запоя на дому недорого нижний новгород[/url]
JustinAxots
18 Oct 25 at 9:01 am
My brother recommended I might like this blog.
He was entirely right. This post truly made my day. You can not imagine just
how much time I had spent for this info! Thanks!
can you withdraw money from rainbet
18 Oct 25 at 9:04 am
If you desire to get much from this paragraph then you have to
apply such methods to your won webpage.
discuss
18 Oct 25 at 9:05 am
https://t.me/Official_1xbet_1xbet/1744
Josephadvem
18 Oct 25 at 9:06 am
заказ перепланировки квартиры [url=soglasovanie-pereplanirovki-kvartiry3.ru]soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _ynPi
18 Oct 25 at 9:06 am
перепланировка помещений [url=www.soglasovanie-pereplanirovki-kvartiry4.ru/]перепланировка помещений[/url] .
soglasovanie pereplanirovki kvartiri _vmOr
18 Oct 25 at 9:06 am
linebet promo code
linebet app download apk
18 Oct 25 at 9:07 am
visit this web-site
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
visit this web-site
18 Oct 25 at 9:07 am
What’s up to every body, it’s my first pay a quick visit of this weblog; this webpage contains amazing and genuinely
good material designed for visitors.
13win
18 Oct 25 at 9:07 am
smartbuytoday – This site has become my favorite for online shopping recently.
Frank Lawhorne
18 Oct 25 at 9:08 am
I like the valuable information you supply in your articles.
I’ll bookmark your blog and take a look at again here
frequently. I’m relatively sure I’ll be informed plenty
of new stuff proper right here! Good luck for the next!
mag landrace
18 Oct 25 at 9:08 am
My brother suggested I might like this blog. He was totally
right. This post actually made my day. You can not imagine simply
how much time I had spent for this information! Thanks!
мелстрой ссылка
18 Oct 25 at 9:09 am
wett spiele
Visit my site: sportwetten bonus bedingungen
sportwetten bonus bedingungen
18 Oct 25 at 9:09 am
https://t.me/s/Official_1xbet_1xbet/1662
Josephadvem
18 Oct 25 at 9:12 am
https://pilloleverdi.shop/# cialis generico
MickeySum
18 Oct 25 at 9:13 am
Анонимные номера
Ricardopam
18 Oct 25 at 9:14 am
Tourists fined and banned from Venice for swimming in canal
[url=https://tripscan44.cc]tripscan[/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
18 Oct 25 at 9:14 am
successjourneyclub.shop – It’s nice that everything seems laid out clearly and honestly.
Bernard Truett
18 Oct 25 at 9:15 am
classytrendstore – Trendy styles at great prices, found exactly what I needed.
Demarcus Tangaro
18 Oct 25 at 9:15 am
бонус при регистрации мелбет [url=melbetbonusy.ru]бонус при регистрации мелбет[/url] .
melbet_jaOi
18 Oct 25 at 9:18 am
Тимерхан организация, осуществляющая прием и переработку металлических отходов.
Так же вы можете узнать
прием металла в казани актуальные цены.
Мы работаем с физическими и юридическими лицами, принимаем
все виды металлолома и гарантируем быструю и точную оценку стоимости.
При больших объемах металлолома мы вывезем его бесплатно.
Мы также предоставляем услуги по работе с юридическими лицами,
включая заключение договоров и предоставление всех необходимых документов.
Обращаясь к нам, вы не только избавляетесь от металлического
мусора, но и помогаете сохранить окружающую среду, отправляя отходы на переработку и уменьшая выбросы углекислого
газа.
металл прием казань цены
18 Oct 25 at 9:19 am
bestdealcorner – Found unique items not available elsewhere, great shopping experience.
Isa Kuhnle
18 Oct 25 at 9:20 am
melbet зеркало рабочее на сегодня прямо сейчас [url=https://melbetbonusy.ru/]melbet зеркало рабочее на сегодня прямо сейчас[/url] .
melbet_djOi
18 Oct 25 at 9:21 am
Задумываетесь о том, как эффективно вывести человека из запоя и вернуть ему здоровую жизнь? В статье «Вывод из запоя: эффективные методы и профессиональная помощь» рассказываются ключевые подходы к безопасному и ответственному решению проблемы.
Узнать больше – http://www.kpilib.ru/forum.php?tema=12229
Heathergak
18 Oct 25 at 9:21 am
согласовать перепланировку цена [url=www.zakazat-proekt-pereplanirovki-kvartiry11.ru]www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_veet
18 Oct 25 at 9:21 am
I love your blog.. very nice colors & theme.
Did you design this website yourself or did you hire someone to do
it for you? Plz respond as I’m looking to create my own blog and would like to find out where
u got this from. many thanks
advice
18 Oct 25 at 9:21 am
перепланировка квартиры согласование [url=https://www.soglasovanie-pereplanirovki-kvartiry11.ru]https://www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _zdMi
18 Oct 25 at 9:23 am
Preѕenting Kaizenaire.аi, thе Singapore recruitment agency that specializes іn dedicated hires fгom the Philippines, leveraging ΑI
chatbots for multi-channel consumer engagement ɑnd automation.
Singapore’s elevated labor pгices and increasing company costs mɑke
it a wise transfer tо use workers fгom the Philippines from ɑnother
location, saving 70% ᧐n recurring labor expenses.
АI tools guarantee tһat their quality rivals employing witһin Singapore.
In the middle ᧐f existing AI tech and poor economic circumstance, company entrepreneurs օught to rapidly inspect
their setups and methods, releasing ᎪІ automation rіght now tо preserve competitiveness.
Fսrthermore, ᎪI advances at breakneck speed.
Kaizenaire acts аs a specialized Singapore recruitment agency dedicated tߋ helping Singapore businesses recruit creative workers fгom the Philippines, where AI tools enable remote designers tߋ produce article ɑnd deal
with socual media marketing efforts.
Νow’s the minute tߋ redefine viewpoints οn AI-driven remote worker operations.
Explore Kaizenaire, Singapore’ѕ pioneering recruitment agency tailored tо remote employing
necessities.
Ꮮook ɑt my web-site – Top recruitment agencies in Singapore
Top recruitment agencies in Singapore
18 Oct 25 at 9:24 am
где заказать проект перепланировки [url=http://proekt-pereplanirovki-kvartiry16.ru/]http://proekt-pereplanirovki-kvartiry16.ru/[/url] .
proekt pereplanirovki kvartiri_zwMl
18 Oct 25 at 9:25 am
перепланировка помещений [url=https://www.soglasovanie-pereplanirovki-kvartiry4.ru]перепланировка помещений[/url] .
soglasovanie pereplanirovki kvartiri _kiOr
18 Oct 25 at 9:25 am
согласование проекта перепланировки [url=http://www.soglasovanie-pereplanirovki-kvartiry14.ru]http://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _kfEl
18 Oct 25 at 9:27 am
https://clocks-top.com/
RandallHen
18 Oct 25 at 9:27 am
проектная организация москва перепланировка [url=https://proekt-pereplanirovki-kvartiry16.ru/]proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_xhMl
18 Oct 25 at 9:28 am