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!
Королева Чиана Королева Чиана – автор, чье творчество отличается не только увлекательным сюжетом, но и глубоким философским подтекстом. Её произведения – это своеобразное зеркало, в котором каждый читатель может увидеть отражение своей души. Книги Королевы Чианы помогают лучше понять себя и окружающих, а также найти ответы на многие сложные вопросы.
AllanCef
16 Sep 25 at 9:28 am
перепланировка в нежилом помещении [url=https://pereplanirovka-nezhilogo-pomeshcheniya1.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya1.ru/[/url] .
pereplanirovka nejilogo pomesheniya_acsi
16 Sep 25 at 9:31 am
What’s up, yup this piece of writing is in fact nice and I have learned lot of things from it about blogging.
thanks.
bsdslot
16 Sep 25 at 9:32 am
согласовать перепланировку нежилого помещения [url=www.pereplanirovka-nezhilogo-pomeshcheniya.ru]www.pereplanirovka-nezhilogo-pomeshcheniya.ru[/url] .
pereplanirovka nejilogo pomesheniya_blKn
16 Sep 25 at 9:33 am
советские фильмы смотреть онлайн бесплатно [url=http://kinogo-11.top/]http://kinogo-11.top/[/url] .
kinogo_vtMa
16 Sep 25 at 9:35 am
Candy Gold casinos TR
Donaldbow
16 Sep 25 at 9:35 am
согласование перепланировки нежилых помещений [url=http://pereplanirovka-nezhilogo-pomeshcheniya1.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya1.ru/[/url] .
pereplanirovka nejilogo pomesheniya_tcsi
16 Sep 25 at 9:36 am
согласование перепланировки нежилого помещения в москве [url=www.pereplanirovka-nezhilogo-pomeshcheniya.ru/]www.pereplanirovka-nezhilogo-pomeshcheniya.ru/[/url] .
pereplanirovka nejilogo pomesheniya_ysKn
16 Sep 25 at 9:36 am
Tourists fined and banned from Venice for swimming in canal
[url=https://trip-scan.co]трип скан[/url]
A couple from the United Kingdom had to cut their vacation in Venice short after being caught swimming in the Grand Canal.
The 35-year-old British man and his 25-year-old Romanian girlfriend were forced to return to their home in the UK on Thursday, the same day they arrived in the city, after gondoliers reported them to local police for taking a dip in the canal.
The pair were fined €450 ($529) each and expelled from Venice for 48 hours, marking the 1,136th such sanction to be handed down to badly behaved tourists in the city so far this year, according to the Venice City Police.
The unnamed couple took the plunge near the Accademia bridge near St. Mark’s Square and gondoliers at the Rio San Vidal kiosk immediately called authorities, who removed them from the water.
“I thank the gondoliers for their cooperation and timely reporting,” said Venice Security Councillor Elisabetta Pesce in a statement published by city authorities on Friday.
https://trip-scan.co
tripskan
“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.”
Allenled
16 Sep 25 at 9:37 am
фильмы онлайн без подписки [url=http://kinogo-11.top/]http://kinogo-11.top/[/url] .
kinogo_haMa
16 Sep 25 at 9:39 am
регистрация перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya.ru]https://pereplanirovka-nezhilogo-pomeshcheniya.ru[/url] .
pereplanirovka nejilogo pomesheniya_vmKn
16 Sep 25 at 9:41 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Читать далее > – https://www.drchfeng.com/?p=5854
KennethVon
16 Sep 25 at 9:43 am
You’ve made some really good points there. I looked on the web to find out more
about the issue and found most people will go along with
your views on this web site.
جذب کارنامه سبزهای استخدامی آموزش و پرورش
16 Sep 25 at 9:48 am
фильмы ужасов смотреть онлайн [url=https://kinogo-11.top]https://kinogo-11.top[/url] .
kinogo_qoMa
16 Sep 25 at 9:49 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Откройте для себя больше – https://forbesport.com/unveiling-the-auz100x-exploring-the-next-big-thing-in-audio-technology
Thomasbloky
16 Sep 25 at 9:53 am
Хотите порадовать любимую? Выбирайте букет на странице «Цветы для девушки» — нежные розы, воздушные пионы, стильные композиции в коробках и корзинах с быстрой доставкой по Москве. Подойдет для любого повода: от первого свидания до годовщины. Перейдите по ссылке https://www.florion.ru/catalog/cvety-devushke – добавьте понравившиеся варианты в корзину и оформите заказ за пару минут — мы поможем с выбором и аккуратно доставим в удобное время.
BegageTal
16 Sep 25 at 9:56 am
перевод документов язык переводы текстов бюро
byuro-perevodov-936
16 Sep 25 at 9:57 am
смотреть фильмы бесплатно [url=http://www.kinogo-11.top]http://www.kinogo-11.top[/url] .
kinogo_xsMa
16 Sep 25 at 9:57 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Где почитать поподробнее? – https://lemondeinfos.com/header-with-ad-space
NathanVab
16 Sep 25 at 9:58 am
Наркология в владимире предлагает многочисленные программы для людей‚ страдающих от зависимости. Важно понимать‚ что эффективное лечение возможно только при комплексном подходе. Консультация нарколога — первый шаг к выздоровлению‚ который оценит состояние пациента и порекомендует индивидуальную программу. В владимире доступны кризисные центры‚ где можно получить поддержку анонимных наркологов. Психотерапия при зависимости также играет ключевую роль в восстановлении. Семейная терапия при алкоголизме помогает наладить отношения и поддержать пациента в трудный период. Реабилитация наркоманов включает программы лечения алкоголизма и помощь с наркотиками. Важно знать о методах предотвращения зависимостей и следовать рекомендациям специалистов. Восстановление после зависимости — это длительный процесс‚ требующий терпения и поддержки. Обратитесь в клинику зависимостей на vivod-iz-zapoya-vladimir017.ru для получения квалифицированной помощи.
izzapoyavladimirNeT
16 Sep 25 at 10:00 am
смотреть фильмы онлайн [url=www.kinogo-11.top/]www.kinogo-11.top/[/url] .
kinogo_rmMa
16 Sep 25 at 10:00 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Изучить вопрос глубже – https://m3dao.ru/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82-%D0%BC%D0%B8%D1%80
Anthonyblaro
16 Sep 25 at 10:00 am
What’s Taking place i’m neww to this, I
sumbled upon this I have discovered It positively useful annd it has helped me out
loads. I hope to give a contribution & help different users like
its aided me. Good job.
Monroe
16 Sep 25 at 10:03 am
kinogo [url=http://www.kinogo-11.top]http://www.kinogo-11.top[/url] .
kinogo_mvMa
16 Sep 25 at 10:04 am
https://novosti.ua/tech/virtualnui-nomer-telefonu-suchasnui-instrument-dla-reestracii-ta-bezpeky-onlain
https://novosti.ua/tech/virtualnui-nomer-telefonu-suchasnui-instrument-dla-reestracii-ta-bezpeky-onlain
16 Sep 25 at 10:05 am
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Всё, что нужно знать – https://www.spanishplains.com/what-is-so-unique-about-spain
MartinObjef
16 Sep 25 at 10:08 am
can you buy cheap furosemide without dr prescription
buy cheap furosemide for sale
16 Sep 25 at 10:10 am
https://clubkrasoty.com/zhizn/vozmozhnosti-arendy-virtualnogo-nomera-telefona/
https://clubkrasoty.com/zhizn/vozmozhnosti-arendy-virtualnogo-nomera-telefona/
16 Sep 25 at 10:16 am
Этот информативный материал предлагает содержательную информацию по множеству задач и вопросов. Мы призываем вас исследовать различные идеи и факты, обобщая их для более глубокого понимания. Наша цель — сделать обучение доступным и увлекательным.
Читать далее > – https://livingpriceless.com/index.php/2022/11/22/hello-world
Gregoryrindy
16 Sep 25 at 10:17 am
заверенный перевод документов бюро переводов апостиль
byuro-perevodov-862
16 Sep 25 at 10:22 am
gГјnstige online apotheke [url=http://mannerkraft.com/#]MannerKraft[/url] ohne rezept apotheke
StevenTilia
16 Sep 25 at 10:23 am
Howdy just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Opera.
I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know.
The design look great though! Hope you get the problem resolved soon. Many thanks
123b
16 Sep 25 at 10:23 am
Эта информационная статья охватывает широкий спектр актуальных тем и вопросов. Мы стремимся осветить ключевые факты и события с ясностью и простотой, чтобы каждый читатель мог извлечь из нее полезные знания и полезные инсайты.
Проследить причинно-следственные связи – https://www.mensider.com/mniej-jedna-trzecia-mezczyzn-regularnie-korzysta-z-zabawek-erotycznych-do-masturbacji
EdwardSor
16 Sep 25 at 10:23 am
фантастика онлайн [url=http://www.kinogo-12.top]http://www.kinogo-12.top[/url] .
kinogo_hkol
16 Sep 25 at 10:28 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
ТОП-5 причин узнать больше – https://www.penzionpatince.sk/ale-ale-webova-stranka-a-novodoba-vizitka-neblaznite-2
Richardroulp
16 Sep 25 at 10:31 am
Do you have a spam problem on this website; I also am a blogger, and I was wanting to know your situation; many of us have created some nice practices
and we are looking to trade techniques with other folks, be sure to shoot
me an e-mail if interested.
Кракен ссылка
16 Sep 25 at 10:33 am
Pretty! This has been an extremely wonderful article.
Thanks for providing these details.
apple pay casino
16 Sep 25 at 10:35 am
Candy Paradise demo
EdwardTix
16 Sep 25 at 10:36 am
My brother suggested I might like this web site.
He was totally right. This post truly made my day.
You cann’t imagine just how much time I had spent for this information! Thanks!
buôn bán nội tạng
16 Sep 25 at 10:38 am
gГјnstigste online apotheke: sildenafil tabletten online bestellen – gГјnstige online apotheke
Israelpaync
16 Sep 25 at 10:39 am
Just want to say your article is as astounding. The clearness to
your post is simply cool and that i could suppose
you are an expert in this subject. Well with your permission allow me to clutch your feed to stay up to date
with impending post. Thanks one million and please continue the rewarding work.
turkey visa for australian
16 Sep 25 at 10:41 am
where buy generic biltricide without insurance
where can i get generic biltricide pill
16 Sep 25 at 10:42 am
Привет любители онлайн КАЗИНО!
Играй свободно и выигрывай стабильно через 1win casino зеркало. Здесь собраны лучшие игры онлайн. Каждый день новые шансы для победы. Получай бонусы и призы. 1win casino зеркало работает без перебоев.
Заходите скорее на рабочее 1win casino зеркало – [url=https://t.me/s/onewincasinotoday]1win casino зеркало[/url]
Удачи и гарантированных выйгрышей в 1win casino!
Casinojence
16 Sep 25 at 10:48 am
can i order generic depakote tablets
cost of cheap depakote price
16 Sep 25 at 10:50 am
Nice article! Stripchat is packed with cool options. Exclusive spin-the-wheel brings
token rewards. Enjoy the live shows to win free rewards.
Stripchat Free Tokens
16 Sep 25 at 10:50 am
Buy Semaglutide online
JamesNency
16 Sep 25 at 10:51 am
автоматические рулонные шторы с электроприводом на окна [url=avtomaticheskie-rulonnye-shtory5.ru]автоматические рулонные шторы с электроприводом на окна[/url] .
avtomaticheskie rylonnie shtori_xgsr
16 Sep 25 at 10:52 am
рулонные шторы с электроприводом купить в москве [url=elektricheskie-rulonnye-shtory15.ru]elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_phEi
16 Sep 25 at 10:52 am
Risperdal without prescription
JamesNency
16 Sep 25 at 10:53 am
перевод документов язык бюро переводов паспортов
byuro-perevodov-558
16 Sep 25 at 10:54 am