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 года
bs2best
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 11:29 pm
https://xn--krken21-bn4c.com
Howardreomo
18 Sep 25 at 11:32 pm
I do accept as true with all of the ideas you’ve introduced to your post.
They are really convincing and can certainly work.
Still, the posts are too quick for novices. May just you please lengthen them a little from next time?
Thank you for the post.
Fundspire Axivon
18 Sep 25 at 11:33 pm
Hello, I enjoy reading through your article post.
I wanted to write a little comment to support you.
mua bảo hiểm tai nạn
18 Sep 25 at 11:33 pm
https://www.band.us/page/99929624/
RonaldWep
18 Sep 25 at 11:38 pm
VitalEdgePharma: VitalEdge Pharma – VitalEdge Pharma
DerekStops
18 Sep 25 at 11:46 pm
I am not sure where you are getting your info, but good topic.
I needs to spend some time learning more or understanding more.
Thanks for fantastic information I was looking for this info for my mission.
Shoko Takahashi
18 Sep 25 at 11:47 pm
накрутка живых подписчиков в тг
JohnnyPhido
18 Sep 25 at 11:48 pm
накрутка подписчиков в тг бот
JohnnyPhido
18 Sep 25 at 11:49 pm
накрутка подписчиков в телеграм канал
GustavoRiz
18 Sep 25 at 11:51 pm
Nous nous rendons sur la carte de départ pour commencer la recherche d’indices.
Florrie
18 Sep 25 at 11:51 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 11:52 pm
Hey there! I’m at work surfing around your blog from
my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts!
Carry on the great work!
grtoto login
18 Sep 25 at 11:56 pm
Hi to all, how is everything, I think every one is
getting more from this web page, and your views are fastidious in support of
new viewers.
My homepage … environmental sustainability
environmental sustainability
18 Sep 25 at 11:56 pm
Ищете компрессорное оборудование по лучшим ценам? Посетите сайт ПромКомТех https://promcomtech.ru/ и ознакомьтесь с каталогом, в котором вы найдете компрессоры для различных видов деятельности. Мы осуществляем оперативную доставку оборудования и комплектующих по всей России. Подробнее на сайте.
pevajWew
18 Sep 25 at 11:56 pm
Have you ever considered about including a little bit more than just your articles?
I mean, what you say is fundamental and everything. However think about if you added some great photos or videos to give
your posts more, “pop”! Your content is excellent but with images and videos, this
blog could certainly be one of the most beneficial in its field.
Good blog!
C3J data file
18 Sep 25 at 11:57 pm
This post provides clear idea in favor of the new visitors of blogging, that actually how
to do blogging.
juegos de mesa
18 Sep 25 at 11:59 pm
Hey just wanted to give you a quick heads up. The words
in your content seem to be running off the screen in Ie.
I’m not sure if this is a formatting issue or something to do with browser compatibility but
I figured I’d post to let you know. The design look
great though! Hope you get the problem resolved soon. Many thanks
امتحانات دانشگاه پیام نور ۱۴۰۴
19 Sep 25 at 12:01 am
накрутка подписчиков телеграм без отписок
Stevenplolf
19 Sep 25 at 12:01 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut Official
Jamesner
19 Sep 25 at 12:01 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 12:02 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 12:02 am
https://form.jotform.com/252537578364064
RonaldWep
19 Sep 25 at 12:03 am
당신이 작성한 것은 수많은 의미를 가진다.
그러나, 이건 어때요? 가정해보자 당신이 더
캐치한 포스트 제목을 작성한다면? 나는 당신의 블로그를 어떻게 운영해야 한다고 말하려는 것이 아니다,
하지만 사람들의 주의를 끄는 헤드라인을 추가한다면 어떨까요?
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog는 조금
평범하다. Yahoo의 프론트 페이지를 보고 그들이 어떻게 포스트 헤드라인을 만들어 뷰어이 클릭하도록 만드는지 확인할 수 있습니다.
비디오를 추가하거나 그림 한두 개를 추가해서 독자이 당신이 작성한 것에 관심을 가지도록 할 수 있습니다.
제 생각엔, 당신의 포스트를 조금 더 생동감 있게 만들
수 있을 것입니다.
Hey! Do you use Twitter? I’d like to follow you if that would be
ok. I’m definitely enjoying your blog and look forward to new posts.
비아그라 구매
19 Sep 25 at 12:07 am
Pretty! This was an incredibly wonderful post. Thank you for providing this information.
vovan casino сайт
19 Sep 25 at 12:08 am
Самостоятельно выйти из запоя — почти невозможно. В Краснодаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-krasnodar12.ru/]нарколог на дом цена в краснодаре[/url]
FrankBoymn
19 Sep 25 at 12:22 am
Prime Secured
3603 N 222nd Ѕt, Suite 102,
Elkhorn, NE 68022, United Տtates
402-289-4126
Comprehensive IT Safety
Comprehensive IT Safety
19 Sep 25 at 12:24 am
В Краснодаре решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-krasnodar17.ru/]нарколог на дом срочно город краснодар[/url]
Bobbietip
19 Sep 25 at 12:24 am
https://evertrustmeds.com/# Ever Trust Meds
RichardceaNy
19 Sep 25 at 12:27 am
https://yamap.com/users/4815758
RonaldWep
19 Sep 25 at 12:28 am
Методическая база клиники опирается на доказательные подходы и стандартизированные протоколы. Комбинация инструментов подбирается индивидуально с учётом переносимости и клинической целесообразности.
Изучить вопрос глубже – [url=https://narkologicheskaya-klinika-lugansk0.ru/]лечение в наркологической клинике луганск[/url]
Lemuelanism
19 Sep 25 at 12:29 am
Good day very cool website!! Guy .. Excellent ..
Wonderful .. I’ll bookmark your website and take the feeds also?
I am happy to search out numerous useful info right here within the
post, we need work out extra techniques in this regard, thank you for sharing.
. . . . .
اعلام نتایج امتحانات نهایی شهریور
19 Sep 25 at 12:29 am
Wonderful beat ! I wish to apprentice while you amend
your web site, how could i subscribe for a blog site?
The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea
casino
19 Sep 25 at 12:30 am
WOW just what I was looking for. Came here by searching for dintrab.net mua
bảo hiểm nhân thọ
dintrab.net mua bảo hiểm nhân thọ
19 Sep 25 at 12:31 am
Superb site you have here but I was curious about if you
knew of any user discussion forums that cover the same topics discussed
here? I’d really like to be a part of community where I can get comments from other experienced people that share the same interest.
If you have any suggestions, please let me know. Thanks a
lot!
آدرس دانشگاه صنعتی اراک
19 Sep 25 at 12:35 am
дизайнерские кашпо для цветов напольные [url=dizaynerskie-kashpo-nsk.ru]dizaynerskie-kashpo-nsk.ru[/url] .
dizainerskie kashpo_svSa
19 Sep 25 at 12:39 am
накрутка премиум подписчиков тг
GustavoRiz
19 Sep 25 at 12:39 am
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 12:40 am
Vous pouvez ainsi explorer le monde à votre rythme, sans dépendre d’autres joueurs.
Elise
19 Sep 25 at 12:40 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 12:41 am
накрутка живых подписчиков в тг бесплатно
JohnnyPhido
19 Sep 25 at 12:41 am
Tourists fined and banned from Venice for swimming in canal
[url=https://trip-scan.co]trip scan[/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.”
BryanCanda
19 Sep 25 at 12:42 am
I do not even understand how I finished up here,
however I thought this post used to be great.
I don’t understand who you are however definitely you’re going to
a well-known blogger if you are not already. Cheers!
نتایج امتحانات نهایی دوازدهم
19 Sep 25 at 12:44 am
https://vitaledgepharma.shop/# VitalEdge Pharma
RichardceaNy
19 Sep 25 at 12:45 am
Доброго!
Купить виртуальный номер для смс навсегда — ваш путь к свободе. Это отличное решение — купить виртуальный номер для смс навсегда и забыть о блокировках. С нашим сервисом легко купить виртуальный номер для смс навсегда. Мы поможем быстро купить виртуальный номер для смс навсегда и начать пользоваться.
Полная информация по ссылке – https://collinuncm05926.blogdal.com/27203959/alles-wat-je-moet-weten-over-duitse-mobiele-nummers-een-complete-gids
купить виртуальный номер навсегда, виртуальный номер, купить виртуальный номер
виртуальный номер, купить виртуальный номер для смс навсегда, виртуальный номер
Удачи и комфорта в общении!
Nomersulge
19 Sep 25 at 12:46 am
I have learn a few just right stuff here. Definitely
value bookmarking for revisiting. I wonder how so much attempt you set to make such a wonderful informative website.
Épure Fundex
19 Sep 25 at 12:49 am
Электрокарниз — это идеальное решение для вашего дома, которое позволяет легко управлять шторами с помощью пульта.
Тем не менее, многие люди предпочитают устанавливать электрокарниз самостоятельно.
Prokarniz
19 Sep 25 at 12:50 am
fhk qvx
youtubetsu
19 Sep 25 at 12:50 am
This is a topic that is close to my heart… Many thanks!
Where are your contact details though?
موضوعات کنکور عملی هنر
19 Sep 25 at 12:50 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 12:53 am