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://frei-diplom2.ru]купить диплом без внесения в реестр[/url] .
Diplomi_yfEa
30 Oct 25 at 2:30 pm
bisbro.com – Appreciate the typography choices; comfortable spacing improved my reading experience.
Andrea Hosaka
30 Oct 25 at 2:38 pm
After going over a few of the articles on your web site, I honestly like your way of blogging.
I bookmarked it to my bookmark webpage list and will be checking back soon. Please check out my
web site as well and tell me your opinion.
https://69vning.me
30 Oct 25 at 2:39 pm
Dəstək xidməti 24/7 işləyir.
https://www.amlsing.com/thread-121097-1-1.html
30 Oct 25 at 2:40 pm
This paragraph provides clear idea designed for
the new people of blogging, that in fact how to do blogging.
doc phim cap 3 mien phi
30 Oct 25 at 2:44 pm
двойные рулонные шторы с электроприводом [url=http://www.rulonnye-shtory-s-elektroprivodom7.ru]http://www.rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_hiMl
30 Oct 25 at 2:44 pm
где купить диплом техникума будьте [url=www.frei-diplom8.ru/]где купить диплом техникума будьте[/url] .
Diplomi_nesr
30 Oct 25 at 2:45 pm
This is my first time go to see at here and i am actually impressed to read everthing
at alone place.
Link bokep
30 Oct 25 at 2:45 pm
createandgrow.shop – Happy to help find alternatives that are fully live and ready for backlink use right now.
Alec Merritts
30 Oct 25 at 2:47 pm
Your style is really unique compared to other folks I’ve read stuff from.
I appreciate you for posting when you’ve got the opportunity, Guess I will
just bookmark this web site.
web site
30 Oct 25 at 2:48 pm
https://vitahomme.shop/# acheter Kamagra en ligne
Davidjealp
30 Oct 25 at 2:51 pm
Перед таблицей короткий переход: мы сначала исключаем несовместимости и только потом начинаем инфузии. Это защищает от скрытых конфликтов препаратов, на которые «универсальные коктейли» просто не смотрят.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-lobnya8.ru/]vyvod-iz-zapoya-lekarstva[/url]
AndrewGremn
30 Oct 25 at 2:51 pm
Although all games are based on success and RNG technology, spinrise [url=https://wdceng.co.uk/how-to-select-reputable-paper-writers/]https://wdceng.co.uk/how-to-select-reputable-paper-writers/[/url] offer gamblers the opportunity to use strategies.
SeanHurry
30 Oct 25 at 2:52 pm
findwhatyoulove.shop – The domain is live, but the homepage appears to show a directory listing rather than finished storefront content.
Alvaro Guiles
30 Oct 25 at 2:55 pm
рулонные шторы с автоматическим управлением [url=http://rulonnye-shtory-s-elektroprivodom7.ru]http://rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_fxMl
30 Oct 25 at 2:56 pm
billig Viagra Norge: ereksjonspiller på nett – billig Viagra Norge
RichardImmon
30 Oct 25 at 2:56 pm
https://t.me/s/Best_promocode_rus/1959
RouletteRogue
30 Oct 25 at 2:56 pm
FarmaciaViva: pillole per disfunzione erettile – Spedra prezzo basso Italia
ClydeExamp
30 Oct 25 at 3:02 pm
acquistare Spedra online: acquistare Spedra online – Avanafil senza ricetta
ClydeExamp
30 Oct 25 at 3:03 pm
acheter Kamagra en ligne: kamagra oral jelly – Kamagra sans ordonnance
RichardImmon
30 Oct 25 at 3:04 pm
Vita Homme: Kamagra pas cher France – kamagra oral jelly
RobertJuike
30 Oct 25 at 3:06 pm
https://t.me/Best_promocode_rus/2663
LuckyBandit
30 Oct 25 at 3:07 pm
Домашняя помощь — это клиника, перенесённая в тихую комнату. Знакомая обстановка снижает тревогу, исчезают пробки и ожидание, нет «социального шума». Врач «ПрофДетокса» приезжает без эмблем, действует спокойно и последовательно, объясняет каждое назначение простым языком. Мы не используем мифические смеси. Состав и темп капельницы подбираются под текущие показатели — давление, пульс, сатурация, выраженность тремора и тошноты, уровень тревоги, данные о лекарствах, которые человек успел принять за двое суток. Такой подход даёт не минутное облегчение, а устойчивую динамику на сутки и неделю.
Получить больше информации – http://narkolog-na-dom-ivanteevka8.ru
JerryPeect
30 Oct 25 at 3:08 pm
differenza tra Spedra e Viagra: Spedra prezzo basso Italia – Spedra
ClydeExamp
30 Oct 25 at 3:08 pm
Лечение с выездом нарколога актуально, когда у пациента нет тяжёлых психических расстройств (галлюцинаций, приступов агрессии, глубокой депрессии), отсутствуют судороги и другие острые проявления. Человек остаётся в знакомой обстановке, не испытывает дискомфорта от стен больницы и лишних взглядов.
Получить больше информации – http://
JeffreyvOt
30 Oct 25 at 3:08 pm
Discover Kaizenaire.com foг Singapore’s ideal deals,
promotions, аnd brand events.
With diverse retail alternatives, Singapore іs a shopper’s paradise ԝhere promotions maintain deal-savvy
Singaporeans pleased.
Singaporeans typically cycle ᴡith the PCN network f᧐r scenic experiences,
and keep in mind to stay upgraded on Singapore’s most current
promotions ɑnd shopping deals.
Negligent Ericka supplies edgy, speculative fashion, valued Ƅy bold Singaporeans f᧐r their daring cuts and vivid prints.
Club21retails deluxe style brands mah, ⅼiked by premium buyers іn Singapore for tһeir special collections ɑnd exceptional service ѕia.
Oddle enhances on-line food getting for dining establishments, valued Ьy diners
for seamless shipment platforms.
Wah, ᴡhy wait ѕia, ցet οn Kaizenaire.com typically to get the bеst
promotions fгom Singapore’s leading brands mah.
Нere is my web blog … singapore promotion
singapore promotion
30 Oct 25 at 3:09 pm
leki Polska
Williamgon
30 Oct 25 at 3:09 pm
производители рулонных штор [url=rulonnye-shtory-s-elektroprivodom7.ru]rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_itMl
30 Oct 25 at 3:09 pm
Thank you for sharing your thoughts. I truly appreciate your
efforts and I am waiting for your further post thank you once again.
foundation contractors austin texas
30 Oct 25 at 3:12 pm
рулонные шторы на окна недорого [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]рулонные шторы на окна недорого[/url] .
rylonnie shtori s elektroprivodom_slMl
30 Oct 25 at 3:13 pm
bisbro.com – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
Ian Mchone
30 Oct 25 at 3:16 pm
Такой подход позволяет добиться устойчивого эффекта и минимизировать риск возврата к зависимому поведению.
Выяснить больше – [url=https://narkologicheskaya-klinika-v-volgograde17.ru/]анонимная наркологическая клиника[/url]
Justinwer
30 Oct 25 at 3:17 pm
Вывод из запоя — это экстренная медицинская помощь, направленная на очищение организма от алкоголя, снятие симптомов интоксикации и восстановление работы внутренних органов. В клинике «Трезвая Линия Волгоград» используется комплексный подход, включающий капельницы, препараты для детоксикации и постоянный врачебный контроль. Лечение проводится анонимно, с индивидуальным подбором медикаментов и поддержкой пациента на каждом этапе восстановления. Главная цель специалистов — не просто стабилизировать состояние, а обеспечить безопасное возвращение к нормальному самочувствию и предотвратить повторные срывы.
Подробнее тут – [url=https://vyvod-iz-zapoia-v-volgograde17.ru/]скорая вывод из запоя волгоград[/url]
Alfredoabarf
30 Oct 25 at 3:18 pm
Oi oi, smart to chiong volunteer initiatives lah, building resumes fοr university and job requests.
Aiyo, wise tⲟ chiong musical lessons lah, cultivating
talents fоr creative industry roles.
Ꭰon’t play play lah, link a good primary school
alongside math superiority fօr ensure elevated PSLE scores as wеll as seamless shifts.
Eh eh, composed pom ρі pi, math iѕ part from the leading topics іn primary school, laying groundwork іn A-Level advanced math.
Wow, math serves ɑѕ tһe groundwork stone in primary education, aiding kids in spatial
analysis іn design paths.
Alas, lacking solid mathematics ɗuring primary school, even leading establishment children mіght falter ᴡith next-level
algebra, tһus cultivate іt рromptly leh.
Ⲟһ no, primary mathematics educates everyday implementations ⅼike budgeting,
therefore ensure youг youngster grasps іt right starting early.
CHIJ (Katong) Primary оffers ɑ faith-centered education that emphasizes holistic advancement.
Ƭhe school’s committed staff and quality programs
influence trainees to reach tһeir capacity.
Montfort Junior School uxes Lasallian education f᧐r kids’ development.
Tһe school balances academics and character building.
Parents select іt for strong ethical foundations.
Ꮮⲟoк into my blog post – Bedok Green Primary School (viralcomms.com)
viralcomms.com
30 Oct 25 at 3:19 pm
Для тех, кто предпочитает лечение в условиях стационара, предусмотрены комфортные палаты, медицинский контроль 24/7 и возможность консультаций с психотерапевтом. Врачи клиники применяют комплексные методы, направленные не только на снятие симптомов, но и на устранение причин зависимости.
Узнать больше – [url=https://narkologicheskaya-pomoshh-v-tolyatti17.ru/]наркологическая клиника клиника помощь[/url]
MarvinWeems
30 Oct 25 at 3:20 pm
comprare medicinali online legali: farmacia viva – acquistare Spedra online
ClydeExamp
30 Oct 25 at 3:22 pm
Ниже представлена таблица с основными препаратами, используемыми при выводе из запоя в Тюмени:
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-tyumeni17.ru/]вывод из запоя дешево в тюмени[/url]
Ervinquide
30 Oct 25 at 3:22 pm
Клиника обеспечивает анонимность и безопасность. Информация о пациентах не передаётся третьим лицам, а процедуры выполняются в комфортных условиях с использованием сертифицированных препаратов и современного оборудования.
Детальнее – [url=https://narkologicheskaya-klinika-v-novokuzneczke17.ru/]анонимная наркологическая клиника в новокузнецке[/url]
MatthewDrusa
30 Oct 25 at 3:22 pm
Вывод из запоя в Тольятти — это медицинская процедура, направленная на очищение организма от продуктов распада алкоголя и восстановление нормального состояния здоровья. Длительное употребление спиртных напитков приводит к серьёзной интоксикации, нарушению работы нервной, сердечно-сосудистой и пищеварительной систем. Самостоятельные попытки прекратить запой могут быть опасны, поэтому оптимальным решением является обращение к врачу-наркологу, который проведёт лечение безопасно и эффективно.
Изучить вопрос глубже – https://vyvod-iz-zapoya-v-tolyatti17.ru/vyvedenie-iz-zapoya-tolyatti/
JeffreyBef
30 Oct 25 at 3:23 pm
В таблице представлены основные виды терапии, применяемые в клинике:
Подробнее тут – https://narcologicheskaya-klinika-v-novokuzneczke17.ru/narkolog-novokuzneczk-na-dom
Phillipcon
30 Oct 25 at 3:23 pm
acheter Kamagra en ligne: Kamagra sans ordonnance – VitaHomme
RobertJuike
30 Oct 25 at 3:25 pm
купить диплом техникума недорого пять плюс [url=www.frei-diplom9.ru/]купить диплом техникума недорого пять плюс[/url] .
Diplomi_ouea
30 Oct 25 at 3:25 pm
FarmaciaViva: Spedra prezzo basso Italia – FarmaciaViva
ClydeExamp
30 Oct 25 at 3:26 pm
TG @‌LINKS_DEALER | EFFECTIVE SEO LINKS FOR SPINBETTER.LINK
Williamturdy
30 Oct 25 at 3:28 pm
двойные рулонные шторы с электроприводом [url=rulonnye-shtory-s-elektroprivodom7.ru]rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_knMl
30 Oct 25 at 3:29 pm
http://www.p2sky.com/home.php?mod=space&uid=6438482&do=profile kazinosi
zamonaviy o‘yinlar bilan tanishing. Yutuqlar real. Sport garovlari doimiy yangilanadi.
Hisob oching va o‘ynang.
http://www.p2sky.com/home.php?mod=space&uid=6438482&do=profile
30 Oct 25 at 3:29 pm
linebet 1xbet telecharger
telecharger linebet apk
30 Oct 25 at 3:30 pm
купить номер телефона навсегда
купить номер телефона навсегда
30 Oct 25 at 3:31 pm
I wanted to thank you for this good read!! I definitely loved every little bit of it.
I have you saved as a favorite to check out new stuff you post…
ankara kürtaj
30 Oct 25 at 3:32 pm
where can you buy steroids
References:
Cons of steroids in sports (git.cgkc.com)
git.cgkc.com
30 Oct 25 at 3:33 pm