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.rudik-diplom4.ru]купить диплом в подольске[/url] .
Diplomi_slOr
21 Oct 25 at 5:01 am
как купить диплом о высшем образовании с занесением в реестр отзывы [url=https://frei-diplom1.ru/]как купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Diplomi_spOi
21 Oct 25 at 5:01 am
купить диплом с занесением в реестр новокузнецке [url=http://www.frei-diplom4.ru]купить диплом с занесением в реестр новокузнецке[/url] .
Diplomi_joOl
21 Oct 25 at 5:01 am
агентство seo [url=http://www.seo-prodvizhenie-reiting.ru]агентство seo[/url] .
seo prodvijenie reiting_fhEa
21 Oct 25 at 5:01 am
рейтинг интернет агентств seo [url=http://reiting-seo-kompanii.ru/]http://reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_tzsn
21 Oct 25 at 5:01 am
Why users still make use of to read news papers when in this technological globe the whole thing is existing on web?
Drayton Paymill Review
21 Oct 25 at 5:01 am
купить диплом в белогорске [url=http://rudik-diplom1.ru/]http://rudik-diplom1.ru/[/url] .
Diplomi_kker
21 Oct 25 at 5:01 am
Tadalafilo Express: tadalafilo 5 mg precio – comprar Cialis online España
RaymondNit
21 Oct 25 at 5:03 am
купить диплом в кунгуре [url=www.rudik-diplom8.ru]www.rudik-diplom8.ru[/url] .
Diplomi_fwMt
21 Oct 25 at 5:03 am
диплом об окончании техникума купить [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_reea
21 Oct 25 at 5:03 am
oleny
Jamesstalm
21 Oct 25 at 5:04 am
диплом о высшем образовании купить с занесением в реестр [url=https://frei-diplom6.ru]диплом о высшем образовании купить с занесением в реестр[/url] .
Diplomi_vpOl
21 Oct 25 at 5:04 am
thetrademark owner,ラブドール 女性 用any agent or employee of the Foundaton,
ラブドール
21 Oct 25 at 5:04 am
купить диплом с занесением в реестр новосибирск [url=http://www.frei-diplom4.ru]купить диплом с занесением в реестр новосибирск[/url] .
Diplomi_gcOl
21 Oct 25 at 5:06 am
купить диплом в кирове [url=http://www.rudik-diplom3.ru]купить диплом в кирове[/url] .
Diplomi_yfei
21 Oct 25 at 5:06 am
купить диплом в усолье-сибирском [url=http://rudik-diplom11.ru]купить диплом в усолье-сибирском[/url] .
Diplomi_zrMi
21 Oct 25 at 5:07 am
купить диплом с проводкой меня [url=http://frei-diplom5.ru]купить диплом с проводкой меня[/url] .
Diplomi_ygPa
21 Oct 25 at 5:07 am
легально купить диплом о [url=www.frei-diplom3.ru/]легально купить диплом о[/url] .
Diplomi_wlKt
21 Oct 25 at 5:08 am
купить диплом с занесением в реестр в калуге [url=https://frei-diplom1.ru]купить диплом с занесением в реестр в калуге[/url] .
Diplomi_gwOi
21 Oct 25 at 5:08 am
Hello, after reading this remarkable article i am also delighted to share my
knowledge here with friends.
Backlinks
21 Oct 25 at 5:10 am
This is my first time visit at here and i am in fact impressed to read all at one place.
best accelerated mba programs
21 Oct 25 at 5:10 am
купить диплом в ачинске [url=https://www.rudik-diplom10.ru]купить диплом в ачинске[/url] .
Diplomi_pzSa
21 Oct 25 at 5:11 am
That is very interesting, You’re a very skilled blogger.
I’ve joined your rss feed and look forward to looking for more
of your excellent post. Also, I have shared your site
in my social networks
dump truck services for land clearing
21 Oct 25 at 5:12 am
I think this is one of the most significant information for me.
And i am glad reading your article. But want to
remark on few general things, The website style is perfect,
the articles is really great : D. Good job, cheers
Luvox Bit
21 Oct 25 at 5:12 am
Joined $MTAUR rush—prizes await. ICO’s tokenomics sound. Mazes challenging.
minotaurus ico
WilliamPargy
21 Oct 25 at 5:13 am
продвижение сайта дорого [url=https://www.reiting-runeta-seo.ru]продвижение сайта дорого[/url] .
reiting ryneta seo_dima
21 Oct 25 at 5:14 am
купить речной диплом [url=https://rudik-diplom8.ru]купить речной диплом[/url] .
Diplomi_xwMt
21 Oct 25 at 5:15 am
диплом колледжа купить в уфе [url=frei-diplom12.ru]диплом колледжа купить в уфе[/url] .
Diplomi_hlPt
21 Oct 25 at 5:15 am
Приятно видеть такую красивую и обаятельную девушку, которая одновременно делает массаж искусно и чувственно. Вышел полностью обновлённым. Крайне рекомендую, индивидуалки вызвать Новосиб, https://sibirka.com/. Получил море удовольствия, спасибо большое.
Bobbyham
21 Oct 25 at 5:15 am
Пришёл без особых ожиданий, а ушёл в полном восторге. Массаж на высшем уровне, всё было естественно и красиво. Энергия мастера просто завораживает. Обязательно попробуйте, проститутки цена Новосиб, https://sibirka.com/. Девушки настоящие красавицы, приятно провести время.
Bobbyham
21 Oct 25 at 5:15 am
https://intimisante.shop/# tadalafil sans ordonnance
MickeySum
21 Oct 25 at 5:17 am
купить диплом высшего образования с занесением в реестр [url=www.frei-diplom3.ru]купить диплом высшего образования с занесением в реестр[/url] .
Diplomi_yoKt
21 Oct 25 at 5:17 am
“Ye resuming her breakfast.フィギュア オナホ“Ye I am here.
ラブドール
21 Oct 25 at 5:18 am
купить диплом о среднем техническом образовании [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_ybea
21 Oct 25 at 5:19 am
купить проведенный диплом спб [url=https://frei-diplom6.ru/]https://frei-diplom6.ru/[/url] .
Diplomi_jiOl
21 Oct 25 at 5:19 am
купить диплом в минеральных водах [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_nbSa
21 Oct 25 at 5:19 am
диплом купить в реестре [url=www.frei-diplom1.ru]диплом купить в реестре[/url] .
Diplomi_ktOi
21 Oct 25 at 5:20 am
топ seo продвижение [url=www.seo-prodvizhenie-reiting.ru]топ seo продвижение[/url] .
seo prodvijenie reiting_gaEa
21 Oct 25 at 5:21 am
where to buy cheap tegretol no prescription
where to get generic tegretol online
21 Oct 25 at 5:22 am
pin up futbol tikish [url=https://www.pinup5008.ru]https://www.pinup5008.ru[/url]
pin_up_uz_udSt
21 Oct 25 at 5:22 am
https://www.designspiration.com/candetoxblend/saves/
Superar una prueba preocupacional puede ser un desafio. Por eso, existe un suplemento innovador con respaldo internacional.
Su receta unica combina creatina, lo que ajusta tu organismo y enmascara temporalmente los trazas de sustancias. El resultado: una orina con parametros normales, lista para ser presentada.
Lo mas notable es su ventana de efectividad de 4 a 5 horas. A diferencia de otros productos, no promete milagros, sino una solucion temporal que responde en el momento justo.
Estos suplementos están diseñados para ayudar a los consumidores a limpiar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el uso de cannabis u otras sustancias ilícitas.
Un buen detox para examen de orina debe proporcionar resultados rápidos y efectivos, en particular cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas alternativas, pero no todas prometen un proceso seguro o rápido.
¿Cómo funciona un producto detox? En términos básicos, estos suplementos actúan acelerando la eliminación de metabolitos y componentes a través de la orina, reduciendo su nivel hasta quedar por debajo del límite de detección de ciertos tests. Algunos trabajan en cuestión de horas y su impacto puede durar entre 4 a 6 horas.
Parece fundamental combinar estos productos con adecuada hidratación. Beber al menos dos litros de agua diariamente antes y después del consumo del detox puede mejorar los efectos. Además, se recomienda evitar alimentos pesados y bebidas azucaradas durante el proceso de uso.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de hierbas, 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 prueba.
Para usuarios frecuentes de cannabis, se recomienda usar detoxes con ventanas de acción largas o iniciar una preparación anticipada. Mientras más prolongada sea la abstinencia, mayor será la potencia del producto. Por eso, combinar la planificación 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 dosis, sabor, método de uso y duración del efecto. Algunos vienen en envase líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que incorporan fases de preparación o limpieza previa al día del examen. Estos programas suelen sugerir abstinencia, buena alimentación y descanso recomendado.
Por último, es importante recalcar que ninguno detox garantiza 100% de éxito. Siempre hay variables individuales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no relajarse.
Miles de trabajadores ya han comprobado su efectividad. Testimonios reales mencionan paquetes 100% confidenciales.
Si necesitas asegurar tu resultado, esta solucion te ofrece seguridad.
JuniorShido
21 Oct 25 at 5:22 am
Le code promo est supprime : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, a utiliser dans les paris sportifs. Vous pouvez vous inscrire sur le site 1xBet ou via l’application mobile. Apres votre premier depot, vous activerez le code bonus. L’offre est valable pour toute l’annee 2026, et le bonus doit etre mise dans les 30 jours. Decouvrez plus d’informations sur le code promo via ce lien — Code Promo 1xbet Cameroun. Le code promo 1xBet casino offre des tours gratuits et un bonus de depot 1xBet pour les nouveaux joueurs. Avec le code promotionnel 1xBet pour nouveaux utilisateurs, recevez jusqu’a 130€ de bonus d’inscription 1xBet. Utilisez le code promo 1xBet aujourd’hui pour jouer au casino en ligne 1xBet et profiter de toutes les offres disponibles.
Marvinspaft
21 Oct 25 at 5:23 am
No matter if some one searches for his required thing, thus he/she wishes to be available that in detail, so that
thing is maintained over here.
warna sgp paling banyak keluar
21 Oct 25 at 5:23 am
seo продвижение сайтов агентство [url=http://reiting-seo-kompanii.ru/]http://reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_ozsn
21 Oct 25 at 5:24 am
купить диплом электромонтажника [url=http://rudik-diplom10.ru]купить диплом электромонтажника[/url] .
Diplomi_ppSa
21 Oct 25 at 5:25 am
что будет если купить диплом о высшем образовании с занесением в реестр [url=https://www.frei-diplom4.ru]что будет если купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_waOl
21 Oct 25 at 5:25 am
купить диплом техникума в спб [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_mhea
21 Oct 25 at 5:26 am
купить диплом с занесением в реестр отзывы [url=www.frei-diplom6.ru/]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_zqOl
21 Oct 25 at 5:27 am
диплом медсестры с аккредитацией купить [url=www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_mtkt
21 Oct 25 at 5:28 am
seo продвижение россия [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]seo продвижение россия[/url] .
agentstvo poiskovogo prodvijeniya_ucKt
21 Oct 25 at 5:30 am