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!
*Метод подбирается индивидуально и применяется только по информированному согласию.
Исследовать вопрос подробнее – http://narkologicheskaya-klinika-rostov-na-donu14.ru/
Danielriz
20 Oct 25 at 6:52 pm
сделать проект квартиры для перепланировки [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_aqot
20 Oct 25 at 6:53 pm
http://potenzvital.com/# Cialis generika gunstig kaufen
LarryArrix
20 Oct 25 at 6:54 pm
диплом техникум колледж купить [url=https://frei-diplom11.ru/]диплом техникум колледж купить[/url] .
Diplomi_upsa
20 Oct 25 at 6:54 pm
диплом о высшем образовании с занесением в реестр купить [url=https://frei-diplom1.ru]диплом о высшем образовании с занесением в реестр купить[/url] .
Diplomi_soOi
20 Oct 25 at 6:54 pm
купить диплом инженера [url=www.rudik-diplom2.ru/]купить диплом инженера[/url] .
Diplomi_zkpi
20 Oct 25 at 6:55 pm
Экстренная помощь при запое в Нижнем Новгороде — капельница на дому от опытных врачей-наркологов.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]скорая вывод из запоя[/url]
TerrellOwelf
20 Oct 25 at 6:56 pm
sport wetten tipps heute
my web site; online Wettanbieter ohne oasis
online Wettanbieter ohne oasis
20 Oct 25 at 6:57 pm
виртуальный номер для Binance
Ernestadaky
20 Oct 25 at 6:59 pm
pin up virtual sport tikish [url=https://pinup5008.ru]pin up virtual sport tikish[/url]
pin_up_uz_jxSt
20 Oct 25 at 7:00 pm
Официальный сайт Вавада может
демонстрировать довольно разнообразные перечни валюты,
карты и другие методы пополнения депозита.
вавада официальный сайт вход зеркало
20 Oct 25 at 7:00 pm
Клинические протоколы стационарной терапии рекомендуют госпитализацию при средней и тяжёлой степени интоксикации.
Узнать больше – [url=https://vyvod-iz-zapoya-v-ryazani12.ru/]вывод из запоя рязань[/url]
CoreyNuAva
20 Oct 25 at 7:03 pm
best am fm clock radios [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_cnOa
20 Oct 25 at 7:05 pm
купить диплом энергетика [url=http://rudik-diplom2.ru/]купить диплом энергетика[/url] .
Diplomi_nfpi
20 Oct 25 at 7:06 pm
radio alarm clock with cd player [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_buOa
20 Oct 25 at 7:08 pm
Link exchange is nothing else except it is just placing the other person’s
webpage link on your page at proper place and other person will also do same in favor of you.
ae88
20 Oct 25 at 7:10 pm
https://www.bergkompressor.ru/ Ваш онлайн-пункт назначения – Посетите сайт для новостей, продуктов и акций.
Jeremyjoync
20 Oct 25 at 7:10 pm
Every weekend i used to go to see this site, because
i want enjoyment, as this this web page conations truly pleasant funny material too.
kra47
20 Oct 25 at 7:10 pm
пин ап рулетка [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_pxsr
20 Oct 25 at 7:11 pm
You’re so interesting! I don’t suppose I have read through
anything like that before. So good to discover someone with genuine
thoughts on this subject matter. Seriously.. many thanks for starting this
up. This web site is one thing that is required on the web,
someone with a bit of originality!
âm mưu phản động
20 Oct 25 at 7:12 pm
Где купить Метамфетамин в Белоозерскии?Вот есть https://mstime.ru
– нормальные цены, доставка гибкая. Кто-то брал у них? Насколько чистый продукта?
Stevenref
20 Oct 25 at 7:12 pm
купить диплом в керчи [url=https://www.rudik-diplom14.ru]https://www.rudik-diplom14.ru[/url] .
Diplomi_rsea
20 Oct 25 at 7:13 pm
заказать перепланировку квартиры в москве [url=https://www.proekt-pereplanirovki-kvartiry11.ru]https://www.proekt-pereplanirovki-kvartiry11.ru[/url] .
proekt pereplanirovki kvartiri_ezot
20 Oct 25 at 7:13 pm
Good day! This post could not be written any better! Reading this post reminds me of
my good old room mate! He always kept chatting about this.
I will forward this write-up to him. Pretty sure he will have a good read.
Thanks for sharing!
m98
20 Oct 25 at 7:14 pm
successmindsetnetwork.bond – Wish there were more case-studies but what’s here is useful.
Jorge Lagrand
20 Oct 25 at 7:17 pm
пин ап бонус за регистрацию [url=https://www.pinup5008.ru]https://www.pinup5008.ru[/url]
pin_up_uz_blSt
20 Oct 25 at 7:18 pm
При выводе из запоя в Ростове-на-Дону используются разные терапевтические подходы. Основной задачей является устранение токсинов и восстановление работы систем организма. Врач подбирает терапию индивидуально в зависимости от состояния пациента и длительности запоя.
Выяснить больше – [url=https://vyvod-iz-zapoya-rostov-na-donu14.ru/]вывод из запоя капельница на дому ростов-на-дону[/url]
Joshuagus
20 Oct 25 at 7:18 pm
Hey, I think your site might be having browser compatibility issues.
When I look at your blog site in Safari, it looks fine but when opening in Internet
Explorer, it has some overlapping. I just wanted to give you a quick heads up!
Other then that, fantastic blog!
we999 game download
20 Oct 25 at 7:19 pm
My brother suggested I might like this website. He was totally right.
This post actually made my day. You can not imagine simply
how much time I had spent for this info! Thanks!
ргс это резервуар
20 Oct 25 at 7:19 pm
radio with cd player and alarm clock [url=http://alarm-radio-clocks.com/]http://alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_heOa
20 Oct 25 at 7:22 pm
Nice post. I was checking continuously this blog and I am impressed!
Very helpful info specially the last part 🙂 I care for such information a lot.
I was looking for this particular information for a very long time.
Thank you and good luck.
NexisFin Avis
20 Oct 25 at 7:23 pm
I am sure this paragraph has touched all the internet people, its really really fastidious piece of writing on building up
new webpage.
casino
20 Oct 25 at 7:24 pm
can you buy allopurinol no prescription
how to get generic allopurinol price
20 Oct 25 at 7:25 pm
https://www.provenexpert.com/candetoxblend/
Pasar un control sorpresa puede ser un desafio. Por eso, se desarrollo un suplemento innovador con respaldo internacional.
Su formula eficaz combina carbohidratos, lo que prepara tu organismo y enmascara temporalmente los metabolitos de sustancias. El resultado: un analisis equilibrado, lista para ser presentada.
Lo mas interesante es su ventana de efectividad de 4 a 5 horas. A diferencia de otros productos, no promete milagros, sino una solucion temporal que te respalda en situaciones criticas.
Estos suplementos están diseñados para ayudar a los consumidores a limpiar su cuerpo de sustancias no deseadas, especialmente esas relacionadas con el uso de cannabis u otras sustancias ilícitas.
Uno buen detox para examen de fluido debe ofrecer resultados rápidos y efectivos, en particular cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas variedades, pero no todas prometen un proceso seguro o fiable.
¿Cómo funciona un producto detox? En términos básicos, estos suplementos funcionan acelerando la eliminación de metabolitos y toxinas a través de la orina, reduciendo su nivel hasta quedar por debajo del umbral de detección de ciertos tests. Algunos trabajan en cuestión de horas y su impacto puede durar entre 4 a 6 horas.
Es fundamental combinar estos productos con correcta hidratación. Beber al menos dos litros de agua al día antes y después del consumo del detox puede mejorar los efectos. Además, se aconseja evitar alimentos grasos y bebidas procesadas durante el proceso de uso.
Los mejores productos de purga para orina incluyen ingredientes como extractos de naturales, vitaminas del grupo B y minerales que respaldan el funcionamiento de los sistemas y la función hepática. Entre las marcas más destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de eficacia.
Para usuarios frecuentes de THC, se recomienda usar detoxes con ventanas de acción largas o iniciar una preparación temprana. Mientras más extendida sea la abstinencia, mayor será la eficacia del producto. Por eso, combinar la disciplina con el uso correcto del producto es clave.
Un error común es pensar que todos los detox actúan lo mismo. Existen diferencias en contenido, sabor, método de ingesta y duración del resultado. Algunos vienen en presentación líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que agregan fases de preparación o limpieza previa al día del examen. Estos programas suelen instruir abstinencia, buena alimentación y descanso previo.
Por último, es importante recalcar que todo detox garantiza 100% de éxito. Siempre hay variables individuales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no descuidarse.
Miles de trabajadores ya han comprobado su rapidez. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si necesitas asegurar tu resultado, esta solucion te ofrece tranquilidad.
JuniorShido
20 Oct 25 at 7:25 pm
Guardians, kiasu а little more hor, good primary builds
numeracy skills, basic fօr finance professions.
Aiyo, select wisely leh, leading primaries concentrate օn principles and discipline, shaping leaders f᧐r corporate
or official wins.
Do not mess ɑround lah, pair ɑ reputable primary school ѡith arithmetic excellence in оrder tߋ guarahtee һigh PSLE marks ρlus seamless transitions.
Folks, kiasu mode оn lah, robust primary arithmetic leads іn superior science comprehension ɑnd construction dreams.
Оһ dear, lacking robust mathematics аt primary school, even prestigious establishmdnt kids coսld stumble at neҳt-level calculations, ѕo build thіs immеdiately leh.
Beѕides from school resources, concentrate ᥙpon mathematics tο avoid typical
mistakes ⅼike sloppy blunders ɗuring tests.
Oh no, primary mathematics educates practical սses suсh as
budgeting, theref᧐re make ѕure your kid grasps іt rіght from eɑrly.
Jiemin Primary School ρrovides ɑ nurturing community focused ⲟn holistic development.
Ԝith caring instructors, іt inspires scholastic and individual development.
Ꮪt. Joseph’ѕ Institution Junior supplies Jesuit education fߋr yoᥙng boys.
The school fosters quality ɑnd values.
It’s a top choice for leadership preparation.
Visit my page … Whitley Secondary School
– Steve,
Steve
20 Oct 25 at 7:26 pm
«Как отмечает врач-нарколог Павел Викторович Зайцев, «эффективность терапии во многом зависит от своевременного обращения, поэтому откладывать визит в клинику опасно»».
Подробнее тут – http://narkologicheskaya-klinika-sankt-peterburg14.ru
Isaacunofs
20 Oct 25 at 7:26 pm
Have you ever considered about including a little bit more than just your articles?
I mean, what you say is fundamental and everything.
Nevertheless think of if you added some great photos or videos to give your posts more,
“pop”! Your content is excellent but with pics and videos, this blog could certainly be
one of the best in its niche. Great blog!
Futuro Token のレビュー
20 Oct 25 at 7:28 pm
https://purebeautyoutlet.bond/
Casey Richmon
20 Oct 25 at 7:28 pm
Superb blog! Do you have any tips and hints for aspiring writers?
I’m planning to start my own site soon but I’m a little lost on everything.
Would you propose starting with a free platform like WordPress
or go for a paid option? There are so many choices out there that I’m completely confused ..
Any tips? Thank you!
dewascatter login
20 Oct 25 at 7:28 pm
сделать проект перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry11.ru/]www.proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_ygot
20 Oct 25 at 7:28 pm
Карта понятна пациенту и семье: видно, что будет происходить, по каким признакам мы перейдём к следующему шагу и когда состоится проверка. Это снижает тревожность и повышает приверженность плану.
Получить дополнительную информацию – http://vyvod-iz-zapoya-petrozavodsk15.ru/vyvod-iz-zapoya-kruglosutochno-petrozavodsk/
Richardsor
20 Oct 25 at 7:30 pm
each time i used to read smaller content which as well
clear their motive, and that is also happening with this paragraph which I am reading here.
https://play-zula.casino
20 Oct 25 at 7:32 pm
The $MTAUR token presale is hot. Audited for safety. Treasures hidden well.
minotaurus coin
WilliamPargy
20 Oct 25 at 7:34 pm
купить диплом в благовещенске [url=www.rudik-diplom15.ru]купить диплом в благовещенске[/url] .
Diplomi_biPi
20 Oct 25 at 7:34 pm
Profitez d’un code promo unique sur 1xBet permettant a chaque nouveau joueur de beneficier jusqu’a 100€ de bonus sportif a hauteur de 100% en 2026. Ce bonus est credite sur votre solde de jeu en fonction du montant de votre premier depot, le depot minimum etant fixe a 1€. Assurez-vous de suivre correctement les instructions lors de l’inscription pour profiter du bonus, afin de preserver l’integrite de la combinaison. D’autres promotions existent en plus du bonus de bienvenue, d’autres combinaisons vous permettant d’obtenir des bonus supplementaires sont disponibles dans la section « Vitrine des codes promo ». Vous pouvez trouver le code promo 1xbet sur ce lien — https://ville-barentin.fr/wp-content/pgs/code-promo-bonus-1xbet.html.
Marvinspaft
20 Oct 25 at 7:35 pm
cialis kaufen ohne rezept: online apotheke rezept – cialis kaufen
RaymondNit
20 Oct 25 at 7:35 pm
https://latvijasloterijas.com/
Because the admin of this site is working, no question very quickly it will be famous, due to
its quality contents.
Loterijas
20 Oct 25 at 7:36 pm
диплом купить с внесением в реестр [url=https://frei-diplom1.ru]диплом купить с внесением в реестр[/url] .
Diplomi_piOi
20 Oct 25 at 7:36 pm
точный прогноз на футбол [url=https://kompyuternye-prognozy-na-futbol24.ru]точный прогноз на футбол[/url] .
komputernie prognozi na fytbol_jisl
20 Oct 25 at 7:41 pm
tabletop cd player and radio [url=https://alarm-radio-clocks.com/]alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_laOa
20 Oct 25 at 7:41 pm