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!
I always spent my half an hour to read this webpage’s content every day along with a
cup of coffee.
My web blog zborakul01
zborakul01
22 Jul 25 at 1:22 am
Its such as you learn my mind! You appear to understand so much approximately this, like you wrote the guide
in it or something. I believe that you simply could do with some
percent to pressure the message house a little bit, however other than that, that is magnificent
blog. A fantastic read. I will definitely be back.
bty9222link
22 Jul 25 at 1:23 am
купить диплом в реестр [url=https://www.arus-diplom35.ru]купить диплом в реестр[/url] .
Kypit diplom lubogo yniversiteta!_sgot
22 Jul 25 at 1:28 am
вывод из запоя калуга
vivod-iz-zapoya-kaluga005.ru
лечение запоя
vivodzapojkalugaNeT
22 Jul 25 at 1:28 am
https://tadalafilfromindia.shop/# tadalafil online no rx
TommyNex
22 Jul 25 at 1:29 am
Saw 7 Dreams mentioned on Clubhouse as the go-to for [url=https://7dreams.ae/services/corporate/]hosting corporate events[/url]. Their team really knows how to handle every aspect with style and precision. The event was flawless, and guests kept complimenting the vibe. Highly recommend if you want a smooth, memorable corporate event.
DreanciMow
22 Jul 25 at 1:31 am
Применяются растворы на основе физраствора, глюкозы, витаминов группы B, противорвотных, седативных и гепатопротекторов. Используемые препараты входят в реестр разрешённых лекарств.
Подробнее тут – [url=https://narcolog-na-dom-ekaterinburg55.ru/]нарколог на дом вывод из запоя[/url]
WesleyNelia
22 Jul 25 at 1:38 am
Spot on with this write-up, I actually feel this
website needs much more attention. I’ll probably be back again to
see more, thanks for the advice!
Shift Flarex Fin
22 Jul 25 at 1:42 am
Hi, after reading this amazing article i am as well cheerful to share my knowledge here with friends.
https://newsmuz.com/mnews/2025/kak-oplatit-podpisku-na-muzykalnyy-striming-spotify-premium-50708
EarnestAbent
22 Jul 25 at 1:45 am
I’d like to find out more? I’d love to find out some additional information.
https://sp-tagil.ru/virtualnyj-nomer-navsegda-zachem-on-nuzhen-i-kak-ego-ispolzovat-v-biznese/
OLaneDrync
22 Jul 25 at 1:47 am
Наркологическая клиника «ЧелябДоктор» специализируется на экстренной и плановой детоксикации пациентов с алкогольной зависимостью. Наши главные преимущества:
Изучить вопрос глубже – https://kapelnica-ot-zapoya-chelyabinsk13.ru/kapelnicza-ot-zapoya-czena-chelyabinsk/
ArthurTaupt
22 Jul 25 at 1:56 am
What’s Happening i am new to this, I stumbled upon this I
have discovered It positively helpful and it
has aided me out loads. I’m hoping to give a contribution &
assist different users like its helped me.
Good job.
click here
22 Jul 25 at 1:59 am
Запой – потеря контроля над алкоголем и резкое отравление организма. Лечение на дому – это быстро, конфиденциально и с индивидуальным подходом. Экстренный вывод из запоя – это быстрая детоксикация и восстановление обмена веществ. Мы выезжаем круглосуточно, чтобы оперативно оценить состояние и начать лечение. На дому мы используем лекарства и психологическую поддержку для достижения максимального эффекта. Мы сначала очистим организм от алкоголя с помощью специальных лекарств.
Выяснить больше – [url=https://vyvod-iz-zapoya-volgograd00.ru/]вывод из запоя на дому волгоград круглосуточно[/url]
Charlesmew
22 Jul 25 at 1:59 am
диплом о среднем профессиональном образовании с занесением в реестр купить [url=arus-diplom35.ru]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Zakazat diplom o visshem obrazovanii!_cqot
22 Jul 25 at 2:00 am
If you are going for most excellent contents like me, just pay a visit this web
site all the time because it gives feature contents, thanks
免费色情影片
22 Jul 25 at 2:01 am
At this moment I am ready to do my breakfast, after having my breakfast coming again to read additional
news.
situs bokep terbesar
22 Jul 25 at 2:05 am
домашний интернет тарифы
domashij-internet-rostov006.ru
подключить интернет
internetrostovelini
22 Jul 25 at 2:07 am
Запой — состояние, при котором человек теряет контроль над количеством употребляемого алкоголя и уже не может самостоятельно прекратить пить. Подобные эпизоды представляют серьёзную угрозу для здоровья, а порой и для жизни. Особенно опасен резкий отказ от спиртного после длительных запоев — это может вызвать тяжёлые абстинентные расстройства, нарушение работы сердца, печени, нервной системы, галлюцинации и даже приступы судорог. В такой ситуации необходимо срочно обращаться к профессионалам. В наркологической клинике «Спасение Плюс» в Химках вывод из запоя осуществляется с выездом врача, гарантией безопасности и индивидуальным подходом.
Разобраться лучше – https://vyvod-iz-zapoya-himki5.ru/vyvod-iz-zapoya-cena-v-himkah/
BrandonRon
22 Jul 25 at 2:11 am
https://lexapro.pro/# lexapro coupon
TommyNex
22 Jul 25 at 2:14 am
Все больше людей в Екатеринбурге выбирают капельницу на дому, и это не случайно. Данная услуга имеет несколько важных преимуществ. Во-первых, это анонимность — пациент может получить помощь без необходимости посещать медицинское учреждение. Во-вторых, лечение на дому позволяет избежать лишнего стресса, который может возникнуть при пребывании в больнице. Пациент чувствует себя в своей обстановке, что способствует лучшему восстановлению.
Подробнее тут – [url=https://kapelnica-ot-zapoya-ektb55.ru/]kapelnicza-ot-zapoya-czena ekaterinburg[/url]
KeithKeeno
22 Jul 25 at 2:16 am
Нужен дом? https://stroitelstvo-domov-kazan1.ru — от проекта до отделки. Каркасные, кирпичные, брусовые, из газобетона. Гарантия качества, соблюдение сроков, индивидуальный подход.
stroitelstvo-domov-417
22 Jul 25 at 2:21 am
Алкогольная зависимость – заболевание, при котором страдает не только тело, но и психика человека. При длительных запоях нарушается работа сердца, печени, почек, появляются острые психоэмоциональные расстройства: тревожность, страхи, агрессия, проблемы со сном. В стадии абстиненции часто отмечается учащённый пульс, скачки давления, дрожь в руках, галлюцинации. Это крайне опасное состояние, требующее профессионального вмешательства нарколога. Клиника «Решение+» в Ногинске предлагает квалифицированный вывод из запоя на дому и в стационаре — с индивидуальным подходом, круглосуточной поддержкой и полным соблюдением анонимности.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-noginsk5.ru/]srochnyj-vyvod-iz-zapoya[/url]
BrandonBus
22 Jul 25 at 2:22 am
mental health support chat [url=http://mental-health21.com/]http://mental-health21.com/[/url] .
Mental Health_qdPa
22 Jul 25 at 2:27 am
настройка внутренней рекламы на Wildberries Комплексное продвижение товара на Wildberries для вейлдберизз: Весь спектр услуг по продвижению, от создания и оптимизации карточек до управления рекламой и аналитики.
DarylHoamy
22 Jul 25 at 2:28 am
Excellent article. Keep posting such kind of info on your page. Im really impressed by your site.
Hey there, You have performed a great job. I will definitely digg it and in my view recommend to my friends. I’m confident they’ll be benefited from this web site.
https://uznavay-pervym.ru/tsifrovaya-mobilnost-i-udalyonnaya-rabota-pochemu-frilanseram-vsyo-chasche-nuzhna-dlitelnaya-arenda-virtualnogo-nomera/
ShaneDrync
22 Jul 25 at 2:29 am
Medicines information sheet. Short-Term Effects.
generic phenytoin without insurance
Some what you want to know about medicine. Read here.
generic phenytoin without insurance
22 Jul 25 at 2:30 am
Вызов врача-нарколога на дом в Санкт-Петербурге начинается с детального осмотра и оценки состояния пациента. Врач измеряет давление, пульс, уровень кислорода в крови и определяет степень интоксикации.
Изучить вопрос глубже – https://narcolog-na-dom-sankt-peterburg00.ru/vyzov-narkologa-na-dom-spb
Tomaswak
22 Jul 25 at 2:30 am
http://finasteridefromcanada.com/# cost propecia
TheronSnipt
22 Jul 25 at 2:33 am
ai therapist app [url=https://ai-therapist23.com]https://ai-therapist23.com[/url] .
AI Therapist_nyEa
22 Jul 25 at 2:34 am
Helpful info. Lucky me I found your web site accidentally, and I am surprised why this accident didn’t took place in advance! I bookmarked it.
https://daily-go.ru/virtualnyj-nomer-telefona-chto-eto-i-pochemu-on-vam-nuzhen-uzhe-segodnya.html
StephenGlona
22 Jul 25 at 2:42 am
экстренный вывод из запоя
vivod-iz-zapoya-kaluga005.ru
экстренный вывод из запоя
vivodzapojkalugaNeT
22 Jul 25 at 2:43 am
Клиника «ВолгаМед» в Волгограде обеспечивает круглосуточную анонимную помощь людям, столкнувшимся с алкогольной или наркотической зависимостью. Мы предлагаем как стационарное лечение в комфортных условиях, так и выезд врача на дом в любое время суток. Конфиденциальность, профессионализм и индивидуальный подход — ключевые принципы нашей работы. В этой статье подробно рассмотрим преимущества клиники, спектр услуг, порядок организации домашнего выезда специалистов и дополнительные возможности поддержки в период реабилитации.
Подробнее можно узнать тут – [url=https://narkologicheskaya-klinika-volgograd13.ru/]бесплатная наркологическая клиника[/url]
DustinTon
22 Jul 25 at 2:43 am
blacksprut
блэкспрут
black sprut
блэк спрут
blacksprut вход
блэкспрут ссылка
blacksprut ссылка
blacksprut onion
блэкспрут сайт
блэкспрут вход
блэкспрут онион
блэкспрут дакрнет
blacksprut darknet
blacksprut сайт
блэкспрут зеркало
blacksprut зеркало
black sprout
blacksprut com зеркало
блэкспрут не работает
blacksprut зеркала
как зайти на blacksprut
как зайти на blacksprut
RichardPep
22 Jul 25 at 2:46 am
ai mental health app [url=https://mental-health21.com/]mental-health21.com[/url] .
Mental Health_vePa
22 Jul 25 at 2:53 am
This is very interesting, You’re a very professional blogger. I have joined your feed and sit up for seeking extra of your magnificent post. Additionally, I have shared your web site in my social networks
https://art-lg.ru/kak-virtualnye-nomera-menyayut-kommunikaczii-v-biznese/
GichardMam
22 Jul 25 at 3:04 am
Its such as you learn my mind! You seem to grasp so much approximately this,
such as you wrote the ebook in it or something. I believe that you simply could do with
a few p.c. to power the message home a little bit, but instead of that, this
is wonderful blog. An excellent read. I’ll certainly be back.
About
22 Jul 25 at 3:08 am
https://zoloft.company/# Zoloft online pharmacy USA
TheronSnipt
22 Jul 25 at 3:09 am
Индивидуализация лечения: Каждый случай рассматривается отдельно, учитывая уникальные особенности пациента, его физическое состояние, предшествующий опыт лечения и социальные факторы. Такой подход позволяет создать максимально эффективный план терапии.
Узнать больше – https://alko-specialist.ru/
IsmaelLox
22 Jul 25 at 3:12 am
USA-safe Accutane sourcing: Accutane for sale – buy Accutane online
Leroymex
22 Jul 25 at 3:13 am
Нужен дом? https://stroitelstvo-domov-kazan1.ru — от проекта до отделки. Каркасные, кирпичные, брусовые, из газобетона. Гарантия качества, соблюдение сроков, индивидуальный подход.
stroitelstvo-domov-195
22 Jul 25 at 3:13 am
купить диплом об окончании техникума [url=http://arus-diplom7.ru]http://arus-diplom7.ru[/url] .
Bistro priobresti diplom lubogo VYZa!_zvOt
22 Jul 25 at 3:17 am
Зависимость от алкоголя или наркотиков — серьёзная проблема, которая постепенно разрушает жизнь, подрывает здоровье, нарушает семейные отношения и ведёт к социальной изоляции. Попытки самостоятельно справиться с заболеванием редко приводят к успеху и зачастую только усугубляют ситуацию. Важно не терять время и обращаться за профессиональной помощью. В наркологической клинике «Наркосфера» в Балашихе пациентов ждёт современное оборудование, команда опытных специалистов, индивидуальный подход и абсолютная анонимность.
Ознакомиться с деталями – https://narkologicheskaya-klinika-balashiha5.ru/chastnaya-narkologicheskaya-klinika-v-balashihe
Cletusjer
22 Jul 25 at 3:18 am
Вызывать нарколога на дом рекомендуется при следующих состояниях:
Подробнее – [url=https://narcolog-na-dom-sankt-peterburg000.ru/]нарколог на дом[/url]
Charlesnob
22 Jul 25 at 3:26 am
WOW just what I was looking for. Came here by searching for %keyword%
https://savostin.pro/marketing/vremennyj-nomer-telefona-populyarnaya-usluga-ip-telefonii-v-ukraine/
StephenGlona
22 Jul 25 at 3:27 am
Врач назначает комплекс препаратов для нормализации состояния и устранения интоксикации. Применяются детоксикационные средства для очищения организма и облегчения абстинентного синдрома. Важным компонентом терапии являются витаминные комплексы и минералы, восстанавливающие метаболический баланс. При необходимости назначаются седативные препараты для снижения тревожности и нормализации сна. Также используются гепатопротекторы и другие средства для поддержки органов, пострадавших от алкогольной интоксикации.
Получить дополнительные сведения – http://vyvod-iz-zapoya-krasnoyarsk55.ru
Williamsok
22 Jul 25 at 3:28 am
Check this site https://ejobstore.com/japan-itineraries-5-top-routes-of-japan/?unapproved=1374&moderation-hash=aae1e08f9ec00c6118d25b1bf814d8c6
Richardencuh
22 Jul 25 at 3:33 am
купить диплом советский [url=https://arus-diplom7.ru/]купить диплом советский[/url] .
Kypit diplom ob obrazovanii!_etOt
22 Jul 25 at 3:40 am
Thanks a bunch for sharing this with all of us you actually recognise what you’re talking approximately! Bookmarked. Please additionally seek advice from my website =). We will have a link trade arrangement between us
https://1vesti.kr.ua/vozmozhnosti-virtualnogo-nomera-dlya-biznesa.html
OLaneDrync
22 Jul 25 at 3:40 am
BBCR ball bearings for sale: Unlocking efficiency and precision in motion, our extensive range of ball bearings caters to diverse industrial and commercial needs. From miniature bearings for delicate instruments to robust bearings for heavy machinery, find the perfect fit for your application. Explore our online catalog or contact our expert team for personalized assistance in selecting the optimal ball bearing solution.
RobertPhasp
22 Jul 25 at 3:44 am
Каждый букмекер в маркетинговых целях, в качестве собственной рекламы и повышения привлекательности своей игровой платформы старается действенные инструменты. Одним из таких инструментов являются бонусы, с помощью которых можно достаточно быстро добиться внимания игроков, повысить интерес пользователей к собственному игровому продукту. Подобная методика характерна практически для всех букмекеров, которые сегодня пребывая в условиях жесткой конкуренции, присутствуют на рынке. Не является исключением в этом плане популярная и хорошо известная букмекерская контора 1Win.В букмекерской конторе 1Win промокод – это промокоды в для получения денег, который после активации предоставляет игроку какие-то преимущества. Как правило, преимущества выражаются в надбавке к бонусу за депозит, в порции фрибетов, фриспинов и прочих преференций, повышающие игровой потенциал клиентов.
Michaelnok
22 Jul 25 at 3:46 am