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!
https://www.tiktok.com/@candetoxblend
Aprobar un test antidoping puede ser un momento critico. Por eso, existe un metodo de enmascaramiento desarrollada en Canada.
Su formula unica combina carbohidratos, lo que prepara tu organismo y enmascara temporalmente los rastros de THC. El resultado: una orina con parametros normales, lista para pasar cualquier control.
Lo mas interesante es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete resultados permanentes, sino una herramienta puntual que te respalda en situaciones criticas.
Estos productos están diseñados para ayudar a los consumidores a limpiar su cuerpo de sustancias no deseadas, especialmente las relacionadas con el consumo de cannabis u otras drogas.
Un buen detox para examen de fluido debe ofrecer resultados rápidos y confiables, en gran cuando el tiempo para desintoxicarse es limitado. En el mercado actual, hay muchas variedades, pero no todas garantizan un proceso seguro o rápido.
De qué funciona un producto detox? En términos simples, estos suplementos funcionan acelerando la depuración de metabolitos y toxinas a través de la orina, reduciendo su nivel hasta quedar por debajo del umbral de detección de los tests. Algunos funcionan en cuestión de horas y su efecto puede durar entre 4 a seis horas.
Resulta fundamental combinar estos productos con correcta hidratación. Beber al menos par litros de agua diariamente antes y después del consumo del detox puede mejorar los resultados. Además, se aconseja evitar alimentos pesados y bebidas procesadas durante el proceso de desintoxicación.
Los mejores productos de detox para orina incluyen ingredientes como extractos de plantas, vitaminas del grupo B y minerales que apoyan el funcionamiento de los riñones y la función hepática. Entre las marcas más populares, se encuentran aquellas que tienen certificaciones sanitarias y estudios de eficacia.
Para usuarios frecuentes de THC, se recomienda usar detoxes con márgenes de acción largas o iniciar una preparación previa. Mientras más extendida sea la abstinencia, mayor será la eficacia del producto. Por eso, combinar la organización con el uso correcto del detox es clave.
Un error común es pensar que todos los detox actúan lo mismo. Existen diferencias en contenido, 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 agregan fases de preparación o preparación previa al día del examen. Estos programas suelen sugerir abstinencia, buena alimentación y descanso previo.
Por último, es importante recalcar que ninguno detox garantiza 100% de éxito. Siempre hay variables personales como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no confiarse.
Miles de postulantes ya han experimentado su rapidez. Testimonios reales mencionan paquetes 100% confidenciales.
Si necesitas asegurar tu resultado, esta alternativa te ofrece seguridad.
JuniorShido
21 Oct 25 at 12:24 am
Fabulous, what a weblog it is! This website gives helpful data to us,
keep it up.
quite a few
21 Oct 25 at 12:26 am
Just grabbed some $MTAUR coins during the presale—feels like getting in on the ground floor of something huge. The audited smart contracts give me peace of mind, unlike sketchier projects. Can’t wait for the game beta to test those power-ups.
minotaurus presale
WilliamPargy
21 Oct 25 at 12:27 am
where buy cheap accutane without insurance
where can i buy cheap accutane without dr prescription
21 Oct 25 at 12:28 am
kraken вход
kraken ios
JamesDaync
21 Oct 25 at 12:28 am
купить диплом занесением в реестр [url=https://www.frei-diplom1.ru]купить диплом занесением в реестр[/url] .
Diplomi_xiOi
21 Oct 25 at 12:29 am
best sounding clock radio [url=https://alarm-radio-clocks.com]https://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_yfOa
21 Oct 25 at 12:30 am
https://pushnews.com.ua/tsikavi-fakty-pro-osin-zminy-pryrody-tradytsii-ta-sviatkuvannia/
Jamesstalm
21 Oct 25 at 12:32 am
пин ап способы оплаты [url=https://pinup5008.ru/]https://pinup5008.ru/[/url]
pin_up_uz_hlSt
21 Oct 25 at 12:34 am
I was recommended this web site by my cousin. I am not sure whether this post is
written by him as nobody else know such
detailed about my trouble. You are wonderful!
Thanks!
stahlwandbecken set
21 Oct 25 at 12:35 am
Just bought $MTAUR; seamless swap. Vesting extensions smart. Maze treasures tempting.
minotaurus presale
WilliamPargy
21 Oct 25 at 12:35 am
мосжилинспекция проект перепланировки [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_rrot
21 Oct 25 at 12:35 am
seo firma [url=https://seo-prodvizhenie-reiting.ru/]seo firma[/url] .
seo prodvijenie reiting_rtEa
21 Oct 25 at 12:35 am
best cd radio alarm clock [url=http://alarm-radio-clocks.com]http://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_cfOa
21 Oct 25 at 12:37 am
купить диплом образование купить проведенный диплом [url=http://frei-diplom1.ru/]купить диплом образование купить проведенный диплом[/url] .
Diplomi_jvOi
21 Oct 25 at 12:38 am
kraken vk2
kraken vk3
JamesDaync
21 Oct 25 at 12:40 am
Wonderful blog you have here but I was wanting to know if you knew of any user discussion forums that cover the
same topics talked about here? I’d really like to be a part of online community where
I can get feed-back from other knowledgeable individuals that share the
same interest. If you have any recommendations, please let me know.
Thanks a lot!
수원가라오케
21 Oct 25 at 12:40 am
Listen ᥙp, Singapore framework rewards earⅼy wins, excellent
primary builds routines for O-Level distinctions ɑnd prestigious jobs.
Oi parents, placing yօur kid tо a good primary school in Singapore means establishing a strong base f᧐r PSLE
victory ɑnd top-tier secondary placements lah.
Αpart from school amenities, concentrate ᴡith math in order to ѕtop frequent pitfalls ⅼike inattentive errors іn assessments.
Guardians, competitive approach engaged lah, strong
primary masth leads fоr bеtter science grasp ɑs ԝell as construction dreams.
Alas, mіnus strong mathh during primary school, regɑrdless prestigious
school youngsters mіght falter іn next-level algebra, tһerefore develop іt
now leh.
Alas, without solid math іn primary school, even top school youngsters may falter
іn һigh school algebra, tһus cultivate thiѕ prߋmptly leh.
Oһ, math serves aѕ the base pillar in primary learning,
assisting youngsters ᴡith spatial thinking to architecture paths.
Punggol Cove Primary School cultivates ɑ lively neighborhood concentrated ⲟn comprehensive development.
Ꭲhe school nurtures ingenious аnd resilient learners.
Sengkang Green Primary School supplies environment-friendly education ᴡith innovation.
Thе school supports green thinkers.
Parents value its sustainability focus.
Нere іs mу site – Greendale Secondary School
Greendale Secondary School
21 Oct 25 at 12:42 am
дизайн проект перепланировки квартиры [url=http://www.proekt-pereplanirovki-kvartiry11.ru]дизайн проект перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_fmot
21 Oct 25 at 12:46 am
pin up savollar va javoblar [url=pinup5008.ru]pin up savollar va javoblar[/url]
pin_up_uz_izSt
21 Oct 25 at 12:47 am
вывод из запоя круглосуточно краснодар
narkolog-krasnodar018.ru
лечение запоя
vivodzapojkrasnodarNeT
21 Oct 25 at 12:48 am
I am really grateful to the owner of this web site who has shared this wonderful paragraph at here.
wd808
21 Oct 25 at 12:48 am
alarm clock with usb music player [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_icOa
21 Oct 25 at 12:49 am
купить диплом в техникуме [url=https://frei-diplom10.ru]купить диплом в техникуме[/url] .
Diplomi_wfEa
21 Oct 25 at 12:50 am
спорт футбол прогнозы на матч [url=www.kompyuternye-prognozy-na-futbol24.ru/]www.kompyuternye-prognozy-na-futbol24.ru/[/url] .
komputernie prognozi na fytbol_xesl
21 Oct 25 at 12:50 am
можно купить легальный диплом [url=https://frei-diplom1.ru]https://frei-diplom1.ru[/url] .
Diplomi_rmOi
21 Oct 25 at 12:50 am
kraken vk3
кракен ссылка
JamesDaync
21 Oct 25 at 12:51 am
if2imc
📝 📬 Incoming Alert - 1.95 BTC from exchange. Claim transfer >> https://graph.org/Get-your-BTC-09-04?hs=7255fc1a3bb72291f146f9661674a5a8& 📝
21 Oct 25 at 12:51 am
Hey there! I’ve been reading your website for some time now and finally got the courage to go ahead and give you
a shout out from Kingwood Tx! Just wanted to say keep up the fantastic work!
Angelika
21 Oct 25 at 12:52 am
Sweet blog! I found it while searching on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Thank you
quite a bit
21 Oct 25 at 12:54 am
Don’t underestimate hor, renowned ᧐nes offer
music and performing arts, enhancing imagination fߋr communication positions.
Oi oi, Ƅetter rush coommunity activities lah, creating profiles f᧐r uni and
career submissions.
Wah lao, regardless ᴡhether school іs fancy, math
serves as the mɑke-or-break topic to cultivates assurance ᴡith figures.
Alas, primary math teaches everyday uss ѕuch as money management, tһerefore ensure youг youngster gets іt correctly fгom eaгly.
Аvoid play play lah, link a reputable primary school ԝith mathematics
proficiency iin ᧐rder to ensure elevated PSLE marks ɑnd smooth transitions.
Folks, competitive mode activated lah, solid primary math guides tⲟ improved scientific grasp as wеll aѕ
tech aspirations.
Wah, math acts like tһe base pillar in primary learning, assisting children fοr geomettric thinking tο
architecture paths.
Ⴝt. Hilda’ѕ Primary School develops ɑn engaging environment promoting holistic advancement.
Ƭһе school inspires students tһrough innovative teaching.
Wellington Primary School ρrovides supportive education concentrated оn growth.
Τhe school develops skills fоr future success.
It’s trustworthy fߋr quality learning.
Alsso visit my blog: Ngee Ann Secondary School
Ngee Ann Secondary School
21 Oct 25 at 12:55 am
Нарколог на дом в Санкт-Петербурге — это востребованная медицинская услуга, позволяющая получить помощь в комфортных домашних условиях. Такой формат особенно актуален в ситуациях, когда пациент не может или не хочет обращаться в стационар. Выезд специалиста позволяет стабилизировать состояние, снять интоксикацию и оказать психологическую поддержку без нарушения анонимности.
Углубиться в тему – [url=https://narkolog-na-dom-sankt-peterburg14.ru/]нарколог на дом недорого санкт-петербург[/url]
RobertSak
21 Oct 25 at 12:56 am
купить диплом в междуреченске [url=http://rudik-diplom5.ru/]http://rudik-diplom5.ru/[/url] .
Diplomi_bama
21 Oct 25 at 12:56 am
купить аттестат за 9 класс [url=www.rudik-diplom10.ru/]купить аттестат за 9 класс[/url] .
Diplomi_doSa
21 Oct 25 at 12:56 am
The Minotaurus presale vesting is flexible genius. Token’s DAO influence key. Gaming market ripe.
minotaurus coin
WilliamPargy
21 Oct 25 at 12:58 am
Code promo pour 1xBet : utilisez-le une fois lors de l’inscription et obtenez un bonus de 100% pour l’inscription jusqu’a 130€. Augmentez le solde de vos fonds simplement en placant des paris avec un wager de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Pour activer ce code, rechargez votre compte a partir de 1€. Decouvrez cette offre exclusive sur ce lien — https://www.nuernberg-balkon.de/images/pgs/?le-code-promo-1xbet_bonus.html.
Marvinspaft
21 Oct 25 at 12:59 am
купить диплом о высшем образовании с занесением в реестр [url=https://www.frei-diplom2.ru]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_vqEa
21 Oct 25 at 12:59 am
professional Ac cleaning
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
professional Ac cleaning
21 Oct 25 at 12:59 am
Appreciating the time and effort you put into your website and detailed information you present.
It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed information. Great read!
I’ve saved your site and I’m adding your RSS feeds to my Google account.
several
21 Oct 25 at 1:00 am
кракен ios
kraken вход
JamesDaync
21 Oct 25 at 1:01 am
Купить диплом колледжа в Одесса [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_ovea
21 Oct 25 at 1:01 am
It’s going to be end of mine day, except before finish I am reading this great piece of writing to improve my knowledge.
pancur4d
21 Oct 25 at 1:01 am
диплом с проводкой купить [url=http://frei-diplom6.ru/]диплом с проводкой купить[/url] .
Diplomi_ykOl
21 Oct 25 at 1:03 am
прогнозы футбола точные на сегодня [url=kompyuternye-prognozy-na-futbol24.ru]kompyuternye-prognozy-na-futbol24.ru[/url] .
komputernie prognozi na fytbol_acsl
21 Oct 25 at 1:03 am
clock cd [url=www.alarm-radio-clocks.com/]www.alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_hoOa
21 Oct 25 at 1:04 am
мин заказ от 1гр.
Приобрести онлайн кокаин, мефедрон, гашиш, бошки
Магазин очень хороший всё чётко и быстро и селер грамотный вы правы
ArturoIcedy
21 Oct 25 at 1:05 am
купить диплом электромонтера [url=rudik-diplom11.ru]купить диплом электромонтера[/url] .
Diplomi_enMi
21 Oct 25 at 1:05 am
купить проведенный диплом кого [url=https://www.frei-diplom4.ru]купить проведенный диплом кого[/url] .
Diplomi_syOl
21 Oct 25 at 1:06 am
купить проведенный диплом моих [url=http://www.frei-diplom2.ru]купить проведенный диплом моих[/url] .
Diplomi_caEa
21 Oct 25 at 1:07 am
Le code promotionnel n’est pas necessaire : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, pour vos paris sportifs. Inscrivez-vous sur 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 — https://ville-barentin.fr/wp-content/pgs/code-promo-bonus-1xbet.html.
Marvinspaft
21 Oct 25 at 1:08 am