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-diplom12.ru]купить диплом техникума настоящий[/url] .
Diplomi_flPt
19 Sep 25 at 12:34 pm
всезаймы [url=https://zaimy-14.ru]https://zaimy-14.ru[/url] .
zaimi_fgSr
19 Sep 25 at 12:36 pm
Клининговая компания https://cleaningplus.ru в Москве: профессиональная уборка квартир, домов и офисов. Генеральная, ежедневная, послестроительная уборка, химчистка мебели и ковров. Доступные цены и гарантия качества.
cleaningplus-148
19 Sep 25 at 12:37 pm
There is certainly a great deal to find out about this issue.
I love all the points you have made.
making it accessible to all crypto users. Create your exclusive TRON address today and shine in every transaction!
19 Sep 25 at 12:39 pm
Как быстро определить,
настоящее ли золото вам предлагают или поддельное?
www.hobastudio.com/cherty-onlajnkazino-s-dohodnymi-slotami/
19 Sep 25 at 12:40 pm
I every time spent my half an hour to read this website’s posts everyday along with a mug of coffee.
dewascatter link alternatif
19 Sep 25 at 12:40 pm
https://rant.li/cydpucuo/kupit-marikhuanu-dmitrov
HarryPaync
19 Sep 25 at 12:43 pm
все займы онлайн на карту [url=http://zaimy-14.ru/]все займы онлайн на карту[/url] .
zaimi_gwSr
19 Sep 25 at 12:44 pm
This paragraph offers clear idea for the new viewers of blogging,
that in fact how to do running a blog.
Zeno Flow Engine
19 Sep 25 at 12:44 pm
все займы ру [url=http://zaimy-14.ru/]http://zaimy-14.ru/[/url] .
zaimi_tpSr
19 Sep 25 at 12:47 pm
In today’s fast-evolving financial landscape, it’s rare to find a platform that seamlessly bridges both crypto and fiat operations,
especially for large-scale operations. However, I came across this discussion that dives deep into a
website which supports everything from buying Bitcoin to managing fiat payments,
and it’s especially recommended for corporate accounts.
I found the forum topic to be incredibly insightful because it covers not
just the basics of buying crypto, but also the extended features like
multi-currency fiat support, bulk payment processing, and advanced tools for businesses.
Whether you’re running a startup or managing
finances for a multinational corporation, the features highlighted in this discussion could be a game-changer
– multi-user accounts, compliance tools, fiat gateways,
and crypto custody all in one.
This topic could be particularly useful for anyone seeking a compliant,
scalable, and secure solution for managing both crypto and fiat funds.
The website being discussed is built to handle everything from simple BTC purchases to large-scale B2B transactions.
It’s a long read, but this forum topic offers some of
the most detailed opinions on using crypto platforms for corporate
and fiat operations alike. Definitely worth digging into this website.
discussion
19 Sep 25 at 12:48 pm
накрутка подписчиков тг канале купить
GustavoRiz
19 Sep 25 at 12:48 pm
список займов онлайн на карту [url=http://zaimy-14.ru]http://zaimy-14.ru[/url] .
zaimi_qnSr
19 Sep 25 at 12:51 pm
Приобрести диплом любого университета поможем. Купить диплом СССР – [url=http://diplomybox.com/diplom-sssr/]diplomybox.com/diplom-sssr[/url]
Cazriad
19 Sep 25 at 12:53 pm
This is a topic that is near to my heart…
Many thanks! Exactly where are your contact details
though?
best online slots
19 Sep 25 at 12:53 pm
https://vitaledgepharma.com/# online ed prescription
AntonioRaX
19 Sep 25 at 12:53 pm
Hi there colleagues, its impressive piece of writing on the topic of teachingand entirely explained, keep it up all the
time.
web page
19 Sep 25 at 12:54 pm
Ahaa, its pleasant conversation regarding this article here at this blog, I have read
all that, so now me also commenting here.
web page
19 Sep 25 at 12:56 pm
If you are going for most excellent contents like myself,
only visit this web page everyday since it offers quality
contents, thanks
web site
19 Sep 25 at 12:57 pm
Picture this: you’re cooking dinner and the recipe calls for grams, but your scale only shows ounces. Later, you’re helping your child with homework and suddenly need to convert meters per second into kilometers per hour. The next morning, you’re preparing a presentation and realize the client wants it in PDF format. Three different situations, three different problems – and usually, three different apps.
That’s the hassle OneConverter eliminates. It’s an all-in-one online tool designed for people who want life to be simpler, faster, and smarter. No downloads, no subscriptions, no headaches – just answers, right when you need them.
Unit Conversions Made Effortless
Most conversion tools handle only the basics. OneConverter goes further – much further. With more than 50,000 unit converters, it can handle everyday situations, advanced academic work, and professional challenges without breaking a sweat.
Everyday Basics: length, weight, speed, temperature, time, area, volume, energy.
Engineering & Physics: torque, angular velocity, density, acceleration, moment of inertia.
Heat & Thermodynamics: thermal conductivity, thermal resistance, entropy, enthalpy.
Radiology: absorbed dose, equivalent dose, radiation exposure.
Fluids: viscosity, flow rate, pressure, surface tension.
Electricity & Magnetism: voltage, current, resistance, capacitance, inductance, flux.
Chemistry: molarity, concentration, molecular weight.
Astronomy: light years, parsecs, astronomical units.
Everyday Extras: cooking measures, shoe and clothing sizes, fuel efficiency.
From the classroom to the lab, from the office to your kitchen – OneConverter has a solution ready.
OneConverter
Fobertsax
19 Sep 25 at 12:59 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 1:00 pm
I am extremely inspired with your writing skills
and also with the layout for your blog. Is that this a paid subject
matter or did you customize it your self? Anyway stay up the nice
quality writing, it is uncommon to peer a nice weblog like this one today..
moto555
19 Sep 25 at 1:01 pm
This post is priceless. How can I find out more?
https://github.com
19 Sep 25 at 1:02 pm
накрутка активных подписчиков в тг канал
GustavoRiz
19 Sep 25 at 1:03 pm
https://xn--krken23-bn4c.com
Howardreomo
19 Sep 25 at 1:03 pm
диплом техникума купить цена [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_iqea
19 Sep 25 at 1:04 pm
http://hollywoodinfive.com/news/new-scientific-study-reveals-why-humans-are-attracted-to-bad-smells/0520604/
Charlesicock
19 Sep 25 at 1:08 pm
https://www.impactio.com/researcher/dietz6cl7ralf
HarryPaync
19 Sep 25 at 1:08 pm
Приобрести диплом любого университета мы поможем. Купить диплом специалиста в Иваново – [url=http://diplomybox.com/kupit-diplom-spetsialista-v-ivanovo/]diplomybox.com/kupit-diplom-spetsialista-v-ivanovo[/url]
Cazrglv
19 Sep 25 at 1:12 pm
https://clearmedshub.com/# ClearMedsHub
AntonioRaX
19 Sep 25 at 1:14 pm
Генеральная уборка https://cleaningplus.ru/services/uborka-kvartiry в Москве: квартиры, дома, офисы. Полный комплекс услуг — мытьё окон, чистка мебели, удаление пыли и грязи. Профессиональные клинеры, безопасные средства и гарантия качества.
cleaningplus-303
19 Sep 25 at 1:14 pm
Yes! Finally someone writes about online casinos nederland.
online casinos nederland
19 Sep 25 at 1:15 pm
When I stumbled upon [url=https://ataspanking.art]spanking video[/url], I was blown away! The spanking-themed artwork and illustrations are so creative and detailed. If you love unique art with a spanking twist, this site is definitely worth checking out and discussing with fellow enthusiasts!
Harryjange
19 Sep 25 at 1:17 pm
Генеральная уборка https://cleaningplus.ru/services/uborka-kvartiry в Москве: квартиры, дома, офисы. Полный комплекс услуг — мытьё окон, чистка мебели, удаление пыли и грязи. Профессиональные клинеры, безопасные средства и гарантия качества.
cleaningplus-170
19 Sep 25 at 1:17 pm
I’ve been exploring [url=https://ataspanking.site]spanking video[/url] and I have to say, it’s amazing! From adult spanking stories to engaging videos, the community here is super active. If you enjoy immersive spanking content and want to share your experiences, this is the place to be!
WilliamfoppY
19 Sep 25 at 1:18 pm
Уборка квартир https://cleaningplus.ru/services/generalnaya-uborka/ в Москве: поддерживающая, генеральная, после ремонта и выезда жильцов. Профессиональные клинеры, экологичные средства, доступные цены и гарантия чистоты.
cleaningplus-809
19 Sep 25 at 1:18 pm
It’s awesome to pay a visit this website and reading the views of all friends about this piece of
writing, while I am also keen of getting knowledge.
feet pics
19 Sep 25 at 1:20 pm
Great web site you have here.. It’s hard to find excellent writing like yours these days.
I seriously appreciate people like you! Take care!!
onlyfans for feet
19 Sep 25 at 1:23 pm
buy xtc prague prague drugstore
prague-drugs-641
19 Sep 25 at 1:23 pm
prague drugs prague plug
prague-drugs-688
19 Sep 25 at 1:23 pm
Nice answer back in return of this issue with firm
arguments and describing the whole thing about that.
drugstore online
19 Sep 25 at 1:23 pm
https://xn--krken23-bn4c.com
Howardreomo
19 Sep 25 at 1:24 pm
I like the helpful information you supply in your articles.
I will bookmark your blog and take a look at once more here frequently.
I’m moderately sure I’ll be informed a lot of new stuff right here!
Good luck for the following!
kontol pendek
19 Sep 25 at 1:29 pm
https://martinmzmwg.pointblog.net/consultoria-en-diagnostico-de-necesidades-de-capacitacion-fundamentos-explicaciГіn-84227123
El correcto diagnostico en necesidades de capacitacion es la piedra angular para construir programas de aprendizaje que den resultados. En las empresas locales, tantas companias invierten millones en cursos que no sirven porque jamas hicieron un diagnostico real de lo que sus equipos necesitan.
?Por que hacer un diagnostico en necesidades de capacitacion?
Reconoce las carencias criticas de conocimientos.
Reduce inversiones inutiles en programas.
Alinea la inversion con la estrategia organizacional.
Mejora la motivacion de los trabajadores.
Estrategias para aplicar un diagnostico en necesidades de capacitacion
Cuestionarios internos: simples de aplicar, ideales para detectar la opinion de los trabajadores.
Reuniones con lideres: permiten descubrir requerimientos de cada departamento.
Analisis directo: ver el flujo real para reconocer faltas invisibles en papel.
Mediciones de desempeno: conectan metas con las habilidades que se deben fortalecer.
Ventajas de un diagnostico en necesidades de capacitacion bien hecho
Cursos que coinciden con las faltas concretas.
Eficiencia de recursos.
Crecimiento profesional alineado con la vision de la compania.
Impacto visibles en desempeno.
Fallos comunes al hacer un diagnostico de necesidades de capacitacion
Imitar modelos de otras companias sin ajustar.
Confundir deseos de gerentes con necesidades reales.
Ignorar la voz de los colaboradores.
Analizar solo una vez y no dar seguimiento.
Un diagnostico de necesidades de capacitacion es la base para lograr una formacion real.
JuniorShido
19 Sep 25 at 1:31 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 1:32 pm
Hi, Neat post. There’s an issue together with your web
site in internet explorer, may check this? IE nonetheless is the marketplace chief and a huge
element of other folks will miss your wonderful writing due to
this problem.
bokep
19 Sep 25 at 1:33 pm
https://wanderlog.com/view/tnezgcjnzp/где-купить-кокаин-клайпеда/
HarryPaync
19 Sep 25 at 1:33 pm
Cash Box играть в 1вин
Eddiefen
19 Sep 25 at 1:35 pm
как безопасно накрутить подписчиков в телеграм
JohnnyPhido
19 Sep 25 at 1:36 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 1:38 pm