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=www.seo-prodvizhenie-reiting.ru]www.seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_prEa
21 Oct 25 at 2:33 pm
seo marketing agency [url=www.reiting-seo-kompanii.ru/]www.reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_exsn
21 Oct 25 at 2:34 pm
Howdy! This is my 1st comment here so I just wanted to
give a quick shout out and tell you I truly enjoy reading your blog posts.
Can you suggest any other blogs/websites/forums that cover the same topics?
Appreciate it!
Bedrock Restoration - Water Fire Mold Damage Service
21 Oct 25 at 2:35 pm
pin up aviator demo [url=http://pinup5007.ru/]http://pinup5007.ru/[/url]
pin_up_uz_hnsr
21 Oct 25 at 2:35 pm
Do you have a spam problem on this site; I also am a blogger, and I was wondering
your situation; we have developed some nice procedures and we are looking to swap methods with others, be sure to shoot me an e-mail if interested.
live casino utan svensk licens
21 Oct 25 at 2:36 pm
топ seo компаний [url=www.seo-prodvizhenie-reiting.ru/]www.seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_blEa
21 Oct 25 at 2:36 pm
Привет всем!
University of Masherova in Vitebsk offers a variety of educational programs in the fields of arts, humanities, and natural sciences. Students have the opportunity to receive a quality education using modern teaching methods and infrastructure. The university actively supports students’ scientific and cultural initiatives, promoting their creative and professional development.
Полная информация по ссылке – https://vsu.by/abiturientam/podgotovitelnye-kursy/internet-kursy-po-vsem-predmetam-tsentralizovannogo-testirovaniya.html
ENGLISH-LANGUAGE MASTER’S PROGRAMMES, VSU named P.M. Masherov, п»їABOUT VSU.by
ENGLISH-LANGUAGE MASTER’S PROGRAMMES, [url=https://vsu.by/cn/povyshenie-kvalifikatsii-i-perepodgotovka-cn/2019-02-20-13-12-50.html]Трансфер Шерегеш Новокузнецк цена [/url], витебск
Удачи и успехов в учебе!
KeithAligo
21 Oct 25 at 2:36 pm
сео продвижение топ [url=reiting-seo-agentstv.ru]сео продвижение топ[/url] .
reiting seo agentstv_jpsa
21 Oct 25 at 2:36 pm
Казино точно знает, каким образом выстроить механизм
игры для клиента, чтобы он чувствовал себя комфортно.
казино мотор
21 Oct 25 at 2:37 pm
digital агентства москвы [url=https://luchshie-digital-agencstva.ru/]https://luchshie-digital-agencstva.ru/[/url] .
lychshie digital agentstva_tzoi
21 Oct 25 at 2:39 pm
https://log.concept2.com/profile/2726565
VictorChash
21 Oct 25 at 2:40 pm
Zeus vs Hades – Gods of War
Danielignit
21 Oct 25 at 2:41 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. Le bonus sera ajoute a votre solde en fonction de votre premier depot, le depot minimum etant fixe a 1€. Pour eviter toute perte de bonus, veillez a copier soigneusement le code depuis la source et a le saisir dans le champ « code promo (si disponible) » lors de l’inscription, 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 — http://www.tiroavolobologna.it/media/pgs/le-code-promo-1xbet_bonus.html.
Marvinspaft
21 Oct 25 at 2:43 pm
Вызов нарколога на дом в Краснодаре — услуга клиники «Детокс». Специалисты оказывают квалифицированную помощь прямо у вас дома.
Ознакомиться с деталями – [url=https://narkolog-na-dom-krasnodar28.ru/]вызов нарколога на дом[/url]
StephenTuple
21 Oct 25 at 2:43 pm
https://zeusvshades11.com/
DarylCeviZ
21 Oct 25 at 2:44 pm
Starlight Princess
DarylCeviZ
21 Oct 25 at 2:44 pm
Если пациент не может приехать в клинику, в Краснодаре нарколог приедет к нему домой. Помощь оказывает «Детокс» круглосуточно.
Подробнее тут – [url=https://narkolog-na-dom-krasnodar26.ru/]вызов нарколога на дом[/url]
RolandNigax
21 Oct 25 at 2:44 pm
Hot Chilli
DarylCeviZ
21 Oct 25 at 2:45 pm
заказать seo продвижение сайта в топ 10 [url=www.seo-prodvizhenie-reiting-kompanij.ru/]заказать seo продвижение сайта в топ 10[/url] .
seo prodvijenie reiting kompanii_bost
21 Oct 25 at 2:46 pm
I’m curious to find out what blog system you have been using?
I’m experiencing some minor security problems with my latest site and I’d like
to find something more risk-free. Do you have any suggestions?
123bet เข้าสู่ระบบ
21 Oct 25 at 2:46 pm
[url=https://vsya-mebel77.ru/]Кресла для офиса[/url] — это важный элемент интерьера любого офиса. Хорошее кресло помогает сохранять правильную осанку и работоспособность. Сегодняшние модели разрабатываются с учетом анатомии и длительного сидения. Мы предлагаем большой выбор офисной мебели, созданные из прочных и износостойких материалов. Модели с подголовником и подлокотниками создают комфорт даже при длительном сидении. Для руководителей подойдут стильные кресла премиум-класса. Для ежедневной работы подойдут кресла с тканевой или сетчатой спинкой. Каждая модель проходит проверку на прочность и удобство, чтобы предложить лучшие решения для вашего офиса. Большое значение имеет регулировка кресла. Материалы отделки — кожа, экокожа, текстиль или сетка — подбираются с учетом стиля и условий эксплуатации. Мы предлагаем офисные кресла по разумным ценам. Мы обеспечиваем быструю обработку заказов и качественную упаковку. От выбора кресла зависит комфорт на протяжении всего рабочего дня. Создайте уютное рабочее пространство уже сегодня. Выбирайте качество и надежность, и ваш офис станет местом, где работать — одно удовольствие.
https://vsya-mebel77.ru/
RandalWoume
21 Oct 25 at 2:48 pm
Если вы ищете безопасный вывод из запоя, обратитесь в Екатеринбурге в «Похмельную Службу». Медики приедут в течение часа.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-ekaterinburg25.ru/]скорая вывод из запоя в екатеринбурге[/url]
RodneyAnivy
21 Oct 25 at 2:49 pm
рейтинг seo компаний [url=reiting-seo-kompanii.ru]рейтинг seo компаний[/url] .
reiting seo kompanii_gusn
21 Oct 25 at 2:49 pm
pin up uz [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_zhsr
21 Oct 25 at 2:49 pm
seo топ 10 [url=www.seo-prodvizhenie-reiting.ru/]www.seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_qyEa
21 Oct 25 at 2:49 pm
https://potenzvital.shop/# cialis generika
MickeySum
21 Oct 25 at 2:50 pm
https://dailyuploads.net/riowe7m6y2os/Code_Promo_1XBET_2026_Gratuit_-_Bonus_130€__.pdf
atrddta
21 Oct 25 at 2:51 pm
pin up tikish qanday qilinadi [url=https://www.pinup5007.ru]https://www.pinup5007.ru[/url]
pin_up_uz_cdsr
21 Oct 25 at 2:52 pm
MELBET-ставки на спорт,киберспорт,казино и многое другое
Лучший букмекер,со своей историей поможет вам заработать целое состояние.
Присоединяйтесь к нам ,пополняйте счет на любую сумму и забирайте свой бонус с [url=https://melbetkz.lol]MELBET[/url]
Artemstylew
21 Oct 25 at 2:53 pm
https://slotwildwestgold.com/
DarylCeviZ
21 Oct 25 at 2:53 pm
https://chilliheat82.com/
DarylCeviZ
21 Oct 25 at 2:54 pm
https://greatrhinodeluxe.com/
DarylCeviZ
21 Oct 25 at 2:54 pm
Un Code promo 1xbet 2026 : recevez un bonus de 100% sur votre premier depot, jusqu’a 130 €. Placez vos paris en toute plaisir en utilisant simplement les fonds bonus. Une fois inscrit, n’oubliez pas de recharger votre compte. Avec un compte verifie, tous les fonds, bonus inclus, peuvent etre retires. Vous pouvez trouver le code promo 1xbet sur ce lien — https://www.nuernberg-balkon.de/images/pgs/?le-code-promo-1xbet_bonus.html.
Marvinspaft
21 Oct 25 at 2:54 pm
If you want to increase your experience just keep visiting this
web site and be updated with the most up-to-date news update posted here.
Частная наркологическая клиника в Москве
21 Oct 25 at 2:55 pm
https://sweetbonanza1000p.com/
Danielignit
21 Oct 25 at 2:56 pm
https://cleocatra15.com/
DarylCeviZ
21 Oct 25 at 2:57 pm
диплом медсестры с аккредитацией купить [url=https://www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_oakt
21 Oct 25 at 2:57 pm
tadalafil senza ricetta: cialis prezzo – cialis generico
RaymondNit
21 Oct 25 at 2:57 pm
Mustang Gold
Danielignit
21 Oct 25 at 2:58 pm
Компания «СибЗТА» https://sibzta.su производит задвижки, клапаны и другую трубопроводную арматуру с 2014 года. Материалы: сталь, чугун, нержавейка. Прочные уплотнения, стандарты ГОСТ, индивидуальные решения под заказ, быстрая доставка и гарантия.
sibzta
21 Oct 25 at 2:58 pm
купить диплом техникума ссср в брянске [url=www.frei-diplom10.ru]купить диплом техникума ссср в брянске[/url] .
Diplomi_noEa
21 Oct 25 at 2:59 pm
I’m not sure exactly why but this blog is loading incredibly
slow for me. Is anyone else having this problem or is it a
problem on my end? I’ll check back later on and
see if the problem still exists.
hair transplant in turkey
21 Oct 25 at 3:00 pm
When I initially commented I clicked the “Notify me when new comments are added” checkbox and
now each time a comment is added I get four emails with the same comment.
Is there any way you can remove people from that service?
Thanks a lot!
اجاره تخت بیمارستانی
21 Oct 25 at 3:00 pm
рейтинг seo компаний [url=https://reiting-seo-kompanii.ru/]рейтинг seo компаний[/url] .
reiting seo kompanii_gusn
21 Oct 25 at 3:02 pm
Промокод при регистрации 1xBet — бонус для новых игроков. Бонус за первый депозит в 1xBet. Как получить и отыграть бонус 32500 руб в букмекерской конторе 1хБет. бесплатные промокоды для 1хбет на ставку. Букмекерские конторы пользуются спросом у людей, чьи интересы плотно связаны со спортом и чей азарт подкрепляется возможностью вознаграждения путем внесения порой незначительной суммы. Вводите промокод 1xBet в 2026 году, чтобы получить бонус на первый депозит до 32500 рублей. 1хБет промокод работает только при регистрации новых пользователей. Бесплатный промокод 1xBet при регистрации. Как ввести промокод 1xBet сегодня? Как отыграть бонус по промокоду 1xBet. Используйте промокод 1xBet при регистрации в 2026 году, чтобы получить бонус до 32500 рублей от крупнейшей букмекерской конторы!
Stanleyvonna
21 Oct 25 at 3:03 pm
https://soundcloud.com/candetoxblend
Pasar una prueba de orina puede ser un momento critico. Por eso, existe un suplemento innovador con respaldo internacional.
Su formula precisa combina nutrientes esenciales, lo que ajusta tu organismo y oculta temporalmente los rastros de toxinas. El resultado: un analisis equilibrado, lista para ser presentada.
Lo mas notable es su capacidad inmediata de respuesta. A diferencia de otros productos, no promete milagros, sino una herramienta puntual que responde en el momento justo.
Estos fórmulas están diseñados para colaborar a los consumidores a limpiar su cuerpo de sustancias no deseadas, especialmente esas relacionadas con el uso de cannabis u otras sustancias.
El buen detox para examen de orina debe proporcionar resultados rápidos y efectivos, en especial cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas alternativas, pero no todas aseguran un proceso seguro o efectivo.
Qué funciona un producto detox? En términos básicos, estos suplementos funcionan acelerando la depuración de metabolitos y residuos a través de la orina, reduciendo su presencia hasta quedar por debajo del nivel de detección de algunos tests. Algunos funcionan en cuestión de horas y su impacto puede durar entre 4 a seis horas.
Resulta fundamental combinar estos productos con adecuada hidratación. Beber al menos dos litros de agua al día antes y después del ingesta del detox puede mejorar los efectos. Además, se aconseja evitar alimentos pesados y bebidas procesadas durante el proceso de preparación.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de naturales, vitaminas del tipo B y minerales que apoyan el funcionamiento de los riñones y la función hepática. Entre las marcas más destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de cannabis, se recomienda usar detoxes con márgenes de acción largas o iniciar una preparación previa. Mientras más prolongada sea la abstinencia, mayor será la potencia del producto. Por eso, combinar la planificación con el uso correcto del detox es clave.
Un error común es creer que todos los detox actúan igual. Existen diferencias en dosis, sabor, método de toma y duración del efecto. Algunos vienen en presentación líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que incluyen fases de preparación o preparación previa al día del examen. Estos programas suelen recomendar abstinencia, buena alimentación y descanso previo.
Por último, es importante recalcar que ningún detox garantiza 100% de éxito. Siempre hay variables individuales como metabolismo, historial de consumo, y tipo de examen. Por ello, es vital seguir las instrucciones del fabricante y no descuidarse.
Miles de profesionales ya han validado su rapidez. Testimonios reales mencionan paquetes 100% confidenciales.
Si no deseas dejar nada al azar, esta solucion te ofrece respaldo.
JuniorShido
21 Oct 25 at 3:03 pm
топ диджитал агентств россии [url=http://www.luchshie-digital-agencstva.ru]топ диджитал агентств россии[/url] .
lychshie digital agentstva_tfoi
21 Oct 25 at 3:04 pm
https://starlightprincess5.com/
DarylCeviZ
21 Oct 25 at 3:05 pm
Sweet Rush Bonanza
DarylCeviZ
21 Oct 25 at 3:06 pm
https://greatrhino-megaways.com/
Danielignit
21 Oct 25 at 3:07 pm