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!
linebet inscription
partenaire linebet
17 Oct 25 at 9:30 pm
купить диплом в донском [url=http://www.rudik-diplom12.ru]http://www.rudik-diplom12.ru[/url] .
Diplomi_gyPi
17 Oct 25 at 9:30 pm
https://t.me/Official_1xbet_1xbet/1848
Josephadvem
17 Oct 25 at 9:38 pm
Привет всем!
Топ 10 компаний по установке кондиционеров — это не маркетинг, а результат работы с тысячами клиентов. Профессиональные компании по установке кондиционеров предоставляют гарантию на материалы и работу. В рейтинге компаний по установке кондиционеров лидируют те, кто использует оригинальные комплектующие и не экономит на изоляции. Компании по продаже и установке кондиционеров с бесплатной консультацией — ваш первый шаг к комфорту.
Полная информация по ссылке – https://vrf-montazh.ru/
железнодорожный монтаж кондиционеров, Топ 10 компаний по установке VRV и VRF, зимой монтаж кондиционера
монтаж наружного блока кондиционера, [url=https://vrf-montazh.ru/top-10-kompaniy-po-ustanovke-vrf-2025/]компании по установке VRV и VRF и ремонту в Москве[/url], монтаж vrf кондиционеров
Удачи и хорошего климата!
AlbertBex
17 Oct 25 at 9:38 pm
https://t.me/Official_1xbet_1xbet/1847
Josephadvem
17 Oct 25 at 9:39 pm
bonus linebet
linebet download
17 Oct 25 at 9:39 pm
mosbet.uz skachat [url=https://mostbet4182.ru/]https://mostbet4182.ru/[/url]
mostbet_uz_ockt
17 Oct 25 at 9:40 pm
buy Doxycycline: safe online medication store – buy clomid
Andresstold
17 Oct 25 at 9:40 pm
Excellent write-up. I definitely appreciate this site.
Continue the good work!
시알리스 구매
17 Oct 25 at 9:41 pm
купить диплом в ульяновске [url=www.rudik-diplom12.ru]купить диплом в ульяновске[/url] .
Diplomi_izPi
17 Oct 25 at 9:42 pm
Современная наркологическая клиника в Мариуполе ориентирована на комплексное и индивидуальное лечение алкогольной и наркотической зависимости, обеспечивая пациентам высококвалифицированную помощь с использованием доказанных медицинских протоколов и новейших технологий. Зависимость — это хроническое заболевание, требующее профессионального подхода, основанного на научных данных и многолетнем опыте специалистов.
Изучить вопрос глубже – https://narkologicheskaya-klinika-mariupol13.ru/platnaya-narkologicheskaya-klinika-mariupol
Gilbertnup
17 Oct 25 at 9:42 pm
This text is worth everyone’s attention. Where can I find
out more?
warna sgp berbasis web
17 Oct 25 at 9:42 pm
Mighty Doog Roofing
Reimer Drive North 13768
Maple Grove,MN 55311 United Ѕtates
(763) 280-5115
updated exterior Siding materials
updated exterior Siding materials
17 Oct 25 at 9:43 pm
https://t.me/Official_1xbet_1xbet/1770
Josephadvem
17 Oct 25 at 9:45 pm
https://t.me/s/Official_1xbet_1xbet/1739
Josephadvem
17 Oct 25 at 9:45 pm
The Playamo online platform offers exceptional entertainment with over 3,000 top-tier slots, classic games, and real dealer options from top software providers. Whether you choose spinning games on modern slot games, applying blackjack strategies, or participating in live casino realism, the site delivers options for every player. The portal’s modern, straightforward system guarantees seamless performance on desktop and mobile, giving you to play favorite titles anytime, anywhere.
Playamo casino
AlfredLog
17 Oct 25 at 9:46 pm
This is really interesting, You’re a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of
your fantastic post. Also, I have shared your web
site in my social networks!
custom hebrew name necklace for women
17 Oct 25 at 9:47 pm
Главной задачей учреждения является полное восстановление физического и психического здоровья пациента. Для достижения этого клиника использует:
Получить дополнительные сведения – [url=https://narkologicheskaya-klinika-mariupol13.ru/]вывод наркологическая клиника в мариуполе[/url]
Gilbertnup
17 Oct 25 at 9:49 pm
Write more, thats all I have to say. Literally, it seems as though you relied
on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something informative to read?
situs toto
17 Oct 25 at 9:49 pm
mostbet sayt [url=http://mostbet4182.ru/]mostbet sayt[/url]
mostbet_uz_xukt
17 Oct 25 at 9:49 pm
Если пациент не может приехать в клинику, в Краснодаре нарколог приедет к нему домой. Помощь оказывает «Детокс» круглосуточно.
Ознакомиться с деталями – [url=https://narkolog-na-dom-krasnodar26.ru/]врач нарколог на дом в краснодаре[/url]
DanielCaupe
17 Oct 25 at 9:50 pm
разработать проект перепланировки [url=www.proekt-pereplanirovki-kvartiry16.ru]www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_uaMl
17 Oct 25 at 9:52 pm
PSE — агентство в Тимашевске, которое за 3–10 дней делает на Tilda продающие сайты с глубокой аналитикой ниши. Опыт 7+ лет и 181 проект: оффер, тексты, уникальный дизайн, метрики — всё под ключ с фиксированной сметой. Ищете разработка технических сайтов? Подробнее о услугах, сроках и примерах работ — на tim.ps-experts.ru. Есть квиз для расчёта стоимости, быстрый старт и поддержка на этапах запуска.
rorukaRow
17 Oct 25 at 9:52 pm
sportwette
Feel free to surf to my blog post … wettbüro online (1920.mywdka.nl)
1920.mywdka.nl
17 Oct 25 at 9:57 pm
купить диплом слесаря [url=https://rudik-diplom12.ru]купить диплом слесаря[/url] .
Diplomi_ypPi
17 Oct 25 at 9:59 pm
В Воронеже клиника «Частный Медик 24» предлагает программу вывода из запоя в стационаре по цене от 6500 ?. Здесь вас ждут комфортные палаты, круглосуточный медицинский контроль и безопасные методы детоксикации, включая капельницы и восстановительное лечение. Анонимность гарантирована, без лишних формальностей и без постановки на учёт.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh23.ru/]быстрый вывод из запоя в стационаре в воронеже[/url]
Anthonyvom
17 Oct 25 at 10:01 pm
https://nearby.golocaly.online/code-promo-1xbet-aujourdhui-bonus-vip-130e/
Diegodax
17 Oct 25 at 10:02 pm
seoanchor.click – Found some useful articles already; looks like a solid resource.
Kip Cutaia
17 Oct 25 at 10:05 pm
mostbet uz telegram qo‘llab-quvvatlash [url=http://mostbet4182.ru]http://mostbet4182.ru[/url]
mostbet_uz_pdkt
17 Oct 25 at 10:05 pm
netfusion.click – The layout is clean and content looks well organized across pages.
Jalisa Redinger
17 Oct 25 at 10:06 pm
https://t.me/Official_1xbet_1xbet/1730
Josephadvem
17 Oct 25 at 10:07 pm
This paragraph presents clear idea in favor of the new viewers
of blogging, that really how to do blogging.
Electric Water Heater Aventura
17 Oct 25 at 10:07 pm
https://t.me/s/Official_1xbet_1xbet/1831
Josephadvem
17 Oct 25 at 10:08 pm
mostbet uz ishlaydi [url=https://mostbet4182.ru/]https://mostbet4182.ru/[/url]
mostbet_uz_thkt
17 Oct 25 at 10:13 pm
rankmotion.click – The color scheme is elegant and not overwhelming at all.
Jim Daugaard
17 Oct 25 at 10:13 pm
https://t.me/s/Official_1xbet_1xbet/1688
Josephadvem
17 Oct 25 at 10:14 pm
clicksignal.click – The navigation is intuitive, found what I needed without trouble.
Cortez Boudreau
17 Oct 25 at 10:14 pm
pagevector.click – Overall experience is positive, feels like a solid, trustworthy site.
Tanya Fey
17 Oct 25 at 10:14 pm
Добрый день!
Монтаж VRV и VRF систем требует не только рук, но и головы. Наши инженеры разрабатывают оптимальную схему прокладки трассы, минимизируя потери хладагента. Монтаж VRF включает промывку системы азотом и контроль чистоты. Стоимость монтажа VRF систем зависит от количества поворотов и подъёмов. Предоставляем 3D-визуализацию. Гарантия — 3 года. Обращайтесь!
Полная информация по ссылке – https://vrf-montazh.ru/
установка и монтаж кондиционеры, монтаж вентиляции в частном доме, как происходит монтаж кондиционера
монтаж вентиляции и кондиционирования, [url=https://vrf-montazh.ru/top-10-kompaniy-po-ustanovke-ventilyatsii-2025/]рейтинг компаний по установке вентиляции в Москве[/url], кассетный кондиционер цена монтаж
Удачи и хорошего климата!
AlbertBex
17 Oct 25 at 10:15 pm
I think this is one of the most important information for me.
And i’m glad reading your article. But want to remark on some general things, The website style is ideal, the
articles is really excellent : D. Good job, cheers
Shisha điện tử lậu
17 Oct 25 at 10:18 pm
beste wett tipps für heute
Also visit my web page: Kostenlos Sportwetten Ohne Einzahlung
Kostenlos Sportwetten Ohne Einzahlung
17 Oct 25 at 10:18 pm
Hi there, this weekend is pleasant designed for me, since this
time i am reading this impressive informative paragraph here
at my home.
pool remodeling contractor
17 Oct 25 at 10:23 pm
https://clocks-top.com/
RandallHen
17 Oct 25 at 10:23 pm
перепланировки квартир [url=http://proekt-pereplanirovki-kvartiry16.ru]http://proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_ndMl
17 Oct 25 at 10:25 pm
https://clocks-top.com/
RandallHen
17 Oct 25 at 10:27 pm
купить диплом в чебоксарах [url=www.rudik-diplom12.ru/]купить диплом в чебоксарах[/url] .
Diplomi_bkPi
17 Oct 25 at 10:31 pm
mostbet tur [url=https://www.mostbet4182.ru]mostbet tur[/url]
mostbet_uz_vzkt
17 Oct 25 at 10:32 pm
Because the admin of this site is working, no uncertainty very soon it
will be famous, due to its quality contents.
best betting sites
17 Oct 25 at 10:33 pm
linebet download apk
linebet partner app
17 Oct 25 at 10:35 pm
https://t.me/s/Official_1xbet_1xbet/1804
Josephadvem
17 Oct 25 at 10:36 pm