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://prognozy-na-khokkej1.ru/]прогнозы на хоккей на сегодня[/url] .
prognozi na hokkei_ziMt
22 Aug 25 at 2:31 am
Наркологическая клиника “Ресурс здоровья” — специализированное медицинское учреждение, предназначенное для оказания профессиональной помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и восстановить контроль над своей жизнью.
Узнать больше – https://narco-vivod.ru
CharlesKef
22 Aug 25 at 2:39 am
Hello There. I found your blog using msn. This is a very well written article.
I will be sure to bookmark it and return to read more of your useful information. Thanks for the
post. I will definitely comeback.
Here is my webpage – AWS AMI
AWS AMI
22 Aug 25 at 2:40 am
Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
[url=https://kra22a.cc]kra25 cc[/url]
“The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
[url=https://kpa29.cc]kra27[/url]
“Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”
At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.
“This was a demonstrative and cynical Russian strike,” Zelensky added.
kra25 at
https://kraken23-at.net
Rafaelwem
22 Aug 25 at 2:40 am
https://wanderlog.com/view/ztpdqymlkf/купить-экстази-кокаин-амфетамин-мале/shared
GroverPycle
22 Aug 25 at 2:43 am
купить диплом украины цена [url=https://www.educ-ua4.ru]купить диплом украины цена[/url] .
Diplomi_ttPl
22 Aug 25 at 2:45 am
лампа лупа косметологическая лампа лупа для косметолога купить
kosmetologicheskoe-oborudovanie-237
22 Aug 25 at 2:48 am
Hello, this weekend is pleasant designed for me,
because this occasion i am reading this great informative piece of writing here at my
house.
kikototo
22 Aug 25 at 2:50 am
I have read so many articles or reviews about the blogger lovers however this article is actually a nice piece of writing,
keep it up.
krnl executor
22 Aug 25 at 2:51 am
Medication information sheet. What side effects?
cost of olmesartan tablets
Best about meds. Read information here.
cost of olmesartan tablets
22 Aug 25 at 2:52 am
купить диплом занесенный реестр [url=https://www.arus-diplom32.ru]купить диплом занесенный реестр[/url] .
Zakazat diplom VYZa!_deEn
22 Aug 25 at 2:52 am
Excellent post but I was wondering if you could write a litte
more on this subject? I’d be very grateful if you could elaborate a little bit more.
Thanks!
https://hm88edu.com
22 Aug 25 at 2:59 am
If you want to get much from this post then you have to
apply such strategies to your won weblog. https://whitestarre.com/agent/melanie081595/
лечебное дело диплом купить
22 Aug 25 at 2:59 am
консультация психиатра по телефону
psikhiatr-moskva003.ru
психиатр на дом
psihiatrmskNeT
22 Aug 25 at 3:01 am
Undeniably believe that which you said. Your favorite justification seemed
to be on the web the simplest thing to be aware of.
I say to you, I definitely get irked while people think about worries
that they just don’t know about. You managed to hit the nail upon the top
as well as defined out the whole thing without having side
effect , people could take a signal. Will probably be back
to get more. Thanks
keo nha cai
22 Aug 25 at 3:02 am
Процедура вывода из запоя проводится опытными наркологами с применением современных протоколов и сертифицированных препаратов. Процесс включает несколько ключевых этапов:
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-odincovo6.ru/]skoraya-vyvod-iz-zapoya[/url]
Gregoryflony
22 Aug 25 at 3:03 am
виза в китай стоит Возможность онлайн оформления визы в Китай зависит от типа визы и региона подачи заявления.
Grahamkar
22 Aug 25 at 3:03 am
блочная комплектная трансформаторная подстанция [url=http://transformatornye-podstancii-kupit1.ru/]блочная комплектная трансформаторная подстанция[/url] .
transformatornie podstancii kypit_lpor
22 Aug 25 at 3:03 am
https://www.themeqx.com/forums/users/deefecuicoob/
GroverPycle
22 Aug 25 at 3:04 am
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Санкт-Петербурге приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-sankt-peterburge11.ru/]ленинградская область[/url]
GilbertHek
22 Aug 25 at 3:06 am
This design is steller! You obviously know how to
keep a reader entertained. Between your wit and your videos,
I was almost moved to start my own blog (well, almost…HaHa!) Great job.
I really enjoyed what you had to say, and more than that, how
you presented it. Too cool!
Bluewave Nexor
22 Aug 25 at 3:08 am
Hello, I enjoy reading all of your article post.
I like tto write a little comment to support you.
Review my web site – отдых в лучших курортах Турции
отдых в лучших курортах Турции
22 Aug 25 at 3:09 am
купить диплом колледжа недорого [url=http://educ-ua4.ru/]http://educ-ua4.ru/[/url] .
Diplomi_iuPl
22 Aug 25 at 3:09 am
It’s an amazing piece of writing designed for all
the online users; they will obtain benefit from it I
am sure.
Here is my web-site: 안전놀이터
안전놀이터
22 Aug 25 at 3:09 am
Атмосферная игра ждёт в Казино Cat слот 100 Lucky Bell.
Alfonzohut
22 Aug 25 at 3:11 am
vps hosting europe vps hosting germany
vps-hosting-4
22 Aug 25 at 3:12 am
NewEra Protect is a natural supplement designed to strengthen the
immune system and boost overall wellness. Its blend of carefully
chosen ingredients helps the body stay resilient, reduce fatigue,
and maintain daily vitality. Many users like it because it offers
a simple, safe, and effective way to protect long-term health.
NewEra Protect
22 Aug 25 at 3:14 am
ivermectin drops: IverGrove – ivermectin antifungal
FrankCax
22 Aug 25 at 3:20 am
Casino On-X предлагает своим игрокам уникальную
программу лояльности, которая делает каждую игру более увлекательной и выгодной.
он икс казино зеркало
22 Aug 25 at 3:20 am
Алкогольный запой представляет собой опасное состояние, когда организм не способен самостоятельно справиться с токсической нагрузкой, вызванной длительным употреблением спиртного. Если запой продолжается более двух-трёх дней, у пациента могут появляться симптомы сильной рвоты, головокружения, спутанности сознания, судорог, резких колебаний артериального давления, а также выраженный абстинентный синдром с паническими атаками и бессонницей. При таких показаниях оперативное вмешательство становится жизненно необходимым для предотвращения серьезных осложнений и ускорения процесса восстановления.
Выяснить больше – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod00.ru/]поставить капельницу от запоя в нижний новгороде[/url]
Jamesvob
22 Aug 25 at 3:23 am
Откройте для себя мир азартных игр на [url=https://888starz2.ru]888starz вход в личный кабинет russia[/url].
позволяющая пользователям наслаждаться азартными играми в удобном формате. На сайте можно найти различные игры, включая слоты и настольные игры.
888starz предлагает удобный интерфейс, что делает игру более комфортной. Каждый пользователь может найти нужный раздел без труда.
Пользователи могут быстро зарегистрироваться и начать игру. Чтобы создать аккаунт, достаточно заполнить небольшую анкету и подтвердить свои данные.
888starz радует своих игроков щедрыми бонусами и многочисленными акциями. За счет бонусов пользователи могут увеличить свои шансы на выигрыш и продлить время игры.
888starz_jton
22 Aug 25 at 3:24 am
https://ucgp.jujuy.edu.ar/profile/dnufqogib/
GroverPycle
22 Aug 25 at 3:25 am
Pretty element of content. I just stumbled upon your web site and in accession capital to assert that I get in fact loved
account your blog posts. Anyway I’ll be subscribing on your feeds and even I achievement you access persistently
fast.
http://aibotiyi.com/
22 Aug 25 at 3:25 am
изготовление перил из нержавеющей стали Перила для лестницы из дерева – это сочетание традиций и современных технологий, обеспечивающее прочность, долговечность и эстетическую привлекательность.
RandyFatty
22 Aug 25 at 3:27 am
I all the time emailed this webpage post page to all my contacts, because
if like to read it next my friends will too.
power washing near me
22 Aug 25 at 3:28 am
I’ll immediately snatch your rss as I can not in finding your email subscription hyperlink or e-newsletter service.
Do you have any? Please allow me realize in order that I could subscribe.
Thanks.
Biała marynarka letnia biała sukienka
22 Aug 25 at 3:29 am
купить диплом в черкассах [url=www.educ-ua4.ru/]www.educ-ua4.ru/[/url] .
Diplomi_prPl
22 Aug 25 at 3:34 am
https://zdorovnik.com/vidy-kapelnicz-ispolzuemyh-pri-razlichnyh-tipah-otravlen
DonaldCab
22 Aug 25 at 3:34 am
Hi there are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog?
Any help would be greatly appreciated!
power washing company
22 Aug 25 at 3:35 am
У вас есть сайт, но мало трафика и звонков? Решение очевидно — [url=https://mihaylov.digital/prodvizhenie-sajta-v-google/]продвижение сайта через гугл[/url]. Опытные специалисты знают, как грамотно оптимизировать страницы, составить контент-стратегию и привлечь целевую аудиторию. Такой подход помогает бизнесу выйти на новый уровень: увеличиваются продажи, растёт доверие к бренду, а конкуренты остаются позади. Google — это площадка, где формируется репутация, и важно занять лидирующие позиции именно там.
Mihaylov.digital — агентство комплексного SEO-продвижения сайтов. Делаем аудит, оптимизацию, выводим проекты в ТОП Google и Яндекс. Работаем с бизнесом любого масштаба. Адрес: Москва, Одесская ул., 2кС, 117638.
оптимизация сайта с оплатой за позиции цены
22 Aug 25 at 3:35 am
Hi, all the time i used to check webpage posts here in the
early hours in the break of day, as i like to learn more and more.
Escorts Services in Islamabad
22 Aug 25 at 3:37 am
Далее проводится сама процедура: при медикаментозном варианте препарат может вводиться внутривенно, внутримышечно или имплантироваться под кожу; при психотерапевтическом — работа проходит в специально оборудованном кабинете, в спокойной атмосфере. После кодирования пациент находится под наблюдением, чтобы исключить осложнения и закрепить эффект. Важно помнить, что соблюдение рекомендаций и поддержка семьи играют решающую роль в сохранении трезвости.
Исследовать вопрос подробнее – [url=https://kodirovanie-ot-alkogolizma-kolomna6.ru/]кодирование от алкоголизма[/url]
EdwardEmamn
22 Aug 25 at 3:37 am
ширма купить кушетка косметологическая с электроприводом купить
kosmetologicheskoe-oborudovanie-261
22 Aug 25 at 3:39 am
ivermectin dose for chickens: IverGrove – IverGrove
WayneViemo
22 Aug 25 at 3:39 am
PrimeBiome is a gut health supplement designed to support digestion, nutrient absorption, and overall balance in the microbiome.
Its natural blend of probiotics and supportive ingredients
works to ease bloating, improve regularity, and strengthen the immune system.
Many users appreciate it as a simple and effective way to maintain digestive wellness and boost overall vitality.
primebiome
22 Aug 25 at 3:40 am
https://mez.ink/cepaszfassl8
GroverPycle
22 Aug 25 at 3:45 am
IverGrove: stromectol 6 mg tablet – durvet ivermectin ingredients
WayneViemo
22 Aug 25 at 3:46 am
I was recommended this web site by my cousin. I’m not
sure whether this post is written by him as nobody else know such detailed about my
trouble. You’re amazing! Thanks!
yourdiamondrings.com
22 Aug 25 at 3:46 am
купить аттестаты в москве за 11 классов [url=http://arus-diplom22.ru/]купить аттестаты в москве за 11 классов[/url] .
Diplomi_nlsl
22 Aug 25 at 3:49 am
I seriously love your blog.. Excellent colors & theme.
Did you build this site yourself? Please reply back as I’m hoping to create my own website and would like
to find out where you got this from or exactly what the theme is named.
Kudos!
website mua bán ma túy
22 Aug 25 at 3:50 am