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-diplom9.ru/]www.rudik-diplom9.ru/[/url] .
Diplomi_muei
19 Oct 25 at 5:07 pm
http://www.medtronik.ru подробная информация о регистрации и бонусных кодах
Aaronawads
19 Oct 25 at 5:09 pm
1win aviator qanday o‘ynash [url=http://1win5510.ru/]http://1win5510.ru/[/url]
1win_uz_oosi
19 Oct 25 at 5:12 pm
кафе ромашково
кафе ромашково
19 Oct 25 at 5:12 pm
кракен ios
кракен vpn
JamesDaync
19 Oct 25 at 5:13 pm
zurbo8
📯 ⚠️ Security Required: 1.4 Bitcoin transfer held. Resume here => https://graph.org/Get-your-BTC-09-04?hs=7255fc1a3bb72291f146f9661674a5a8& 📯
19 Oct 25 at 5:15 pm
купить диплом в майкопе [url=rudik-diplom13.ru]rudik-diplom13.ru[/url] .
Diplomi_oton
19 Oct 25 at 5:15 pm
купить диплом бухгалтера [url=rudik-diplom6.ru]купить диплом бухгалтера[/url] .
Diplomi_cjKr
19 Oct 25 at 5:16 pm
MELBET-бонус за первое пополнение
Лучший букмекер,со своей историей поможет вам заработать целое состояние.
Присоединяйтесь к нам ,пополняйте счет на любую сумму и забирайте свой бонус с [url=https://melbetkz.lol]MELBET[/url]
Artemstylew
19 Oct 25 at 5:18 pm
В кардиологической и психологической поддержке «Частного Медика 24» в Самаре — полный комплекс для безопасного восстановления после запоя.
Детальнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]вывод из запоя в стационаре клиника[/url]
Williamliz
19 Oct 25 at 5:20 pm
Mighty Dog Roofing
Reimer Drive North 13768
Maple Grove, MN 55311 United Տtates
(763) 280-5115
window replacement team (Tomoko)
Tomoko
19 Oct 25 at 5:22 pm
Если вы ищете надёжный и понятный путь к избавлению от алкогольной зависимости — вам стоит заглянуть в статью «Эффективные услуги лечения алкоголизма: путь к трезвой жизни». Подробнее тут – http://kremlevsk.kamrbb.ru/?x=read&razdel=5&tema=637
Heathergak
19 Oct 25 at 5:23 pm
Minotaurus token’s multi-chain support key. Presale raise impressive. Unlocks thrilling.
mtaur coin
WilliamPargy
19 Oct 25 at 5:24 pm
It is not my first time to pay a quick visit this website, i am visiting this website dailly and obtain good facts from
here everyday.
best C55 file viewer
19 Oct 25 at 5:24 pm
купить диплом в тобольске [url=rudik-diplom6.ru]rudik-diplom6.ru[/url] .
Diplomi_fkKr
19 Oct 25 at 5:25 pm
где купить диплом техникума одно [url=http://frei-diplom9.ru]где купить диплом техникума одно[/url] .
Diplomi_gxea
19 Oct 25 at 5:26 pm
melbet фрибет [url=https://www.melbetbonusy.ru]melbet фрибет[/url] .
melbet_iqOi
19 Oct 25 at 5:27 pm
В Краснодаре клиника «Детокс» предоставляет услугу вызова нарколога на дом. Специалисты приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Разобраться лучше – [url=https://narkolog-na-dom-krasnodar27.ru/]запой нарколог на дом краснодар[/url]
DanielNus
19 Oct 25 at 5:28 pm
This information is invaluable. When can I find out
more?
https://nestleresource.hashnode.dev/20
19 Oct 25 at 5:28 pm
Amazing! Its actually awesome post, I have got much clear idea on the
topic of from this article.
طراحی سایت مخصوص پزشکان
19 Oct 25 at 5:29 pm
кафе ромашково
кафе ромашково
19 Oct 25 at 5:30 pm
купить диплом в старом осколе [url=www.rudik-diplom9.ru]купить диплом в старом осколе[/url] .
Diplomi_hpei
19 Oct 25 at 5:31 pm
мелбет [url=www.melbetbonusy.ru/]мелбет[/url] .
melbet_mtOi
19 Oct 25 at 5:31 pm
1win uz [url=http://1win5509.ru/]http://1win5509.ru/[/url]
1win_uz_egKt
19 Oct 25 at 5:32 pm
1win uz [url=https://www.1win5509.ru]https://www.1win5509.ru[/url]
1win_uz_qcKt
19 Oct 25 at 5:34 pm
где купить диплом среднем [url=http://www.rudik-diplom13.ru]где купить диплом среднем[/url] .
Diplomi_jeon
19 Oct 25 at 5:35 pm
http://tadalafiloexpress.com/# cialis generico
MickeySum
19 Oct 25 at 5:36 pm
http://pilloleverdi.com/# farmacia online italiana Cialis
LarryArrix
19 Oct 25 at 5:36 pm
I visited several sites except the audio feature for audio songs present at this web page is in fact fabulous.
local pressure washing near me
19 Oct 25 at 5:39 pm
1win uz [url=https://1win5510.ru/]https://1win5510.ru/[/url]
1win_uz_amsi
19 Oct 25 at 5:42 pm
контора мелбет [url=https://melbetbonusy.ru/]контора мелбет[/url] .
melbet_rnOi
19 Oct 25 at 5:44 pm
купить диплом в камышине [url=rudik-diplom9.ru]купить диплом в камышине[/url] .
Diplomi_rpei
19 Oct 25 at 5:45 pm
купить диплом в глазове [url=https://www.rudik-diplom14.ru]купить диплом в глазове[/url] .
Diplomi_xpea
19 Oct 25 at 5:50 pm
Промокод 1xBet на сегодня можно получить прямо на сайте букмекерской компании. Сделать это станет возможным благодаря переходу по рабочей ссылке, содержащей промокод. Подобного рода бонусы могут использовать и постоянные и новые клиенты конторы. Благодаря проведению таких акций интерес игроков к ставкам остаётся высоким. Содержание. промокод на тото 1xbet. Как получить и что дает промокод в 1xBet? Где вводить промокод в 1xBet? Рабочие промокоды 1xBet на сегодня. Действующие промокоды 1xBet на сегодня. Узнайте как ввести промо код 1хБет при регистрации и получить 32500 рублей на бесплатную ставку. Как активировать и использовать промокод на 1xBet. Список рабочих бонус кодов.
Stanleyvonna
19 Oct 25 at 5:56 pm
https://rafaelcodre.ampblogs.com/se-rumorea-zumbido-en-detox-examen-de-orina-74536267
Purificacion para examen de orina se ha transformado en una solucion cada vez mas conocida entre personas que requieren eliminar toxinas del cuerpo y superar pruebas de analisis de drogas. Estos formulas estan disenados para facilitar a los consumidores a depurar su cuerpo de sustancias no deseadas, especialmente las relacionadas con el consumo de cannabis u otras drogas.
Uno buen detox para examen de orina debe ofrecer resultados rapidos y confiables, en gran cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas opciones, pero no todas aseguran un proceso seguro o rapido.
?Como funciona un producto detox? En terminos simples, estos suplementos funcionan acelerando la depuracion de metabolitos y residuos a traves de la orina, reduciendo su concentracion hasta quedar por debajo del limite de deteccion de algunos tests. Algunos trabajan en cuestion de horas y su accion puede durar entre 4 a seis horas.
Resulta fundamental combinar estos productos con correcta hidratacion. Beber al menos par litros de agua al dia antes y despues del uso del detox puede mejorar los resultados. Ademas, se sugiere evitar alimentos grasos y bebidas acidas durante el proceso de uso.
Los mejores productos de purga para orina incluyen ingredientes como extractos de naturales, vitaminas del tipo B y minerales que apoyan el funcionamiento de los organos y la funcion hepatica. Entre las marcas mas destacadas, se encuentran aquellas que tienen certificaciones sanitarias y estudios de prueba.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con tiempos de accion largas o iniciar una preparacion temprana. Mientras mas prolongada sea la abstinencia, mayor sera la efectividad del producto. Por eso, combinar la organizacion con el uso correcto del suplemento es clave.
Un error comun es pensar que todos los detox actuan lo mismo. Existen diferencias en formulacion, sabor, metodo de ingesta y duracion del efecto. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que agregan fases de preparacion o purga previa al dia del examen. Estos programas suelen instruir abstinencia, buena alimentacion y descanso recomendado.
Por ultimo, es importante recalcar que todo detox garantiza 100% de exito. Siempre hay variables individuales como metabolismo, historial de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no confiarse.
JuniorShido
19 Oct 25 at 5:58 pm
1win blackjack uz [url=http://1win5509.ru]1win blackjack uz[/url]
1win_uz_buKt
19 Oct 25 at 5:59 pm
1win uz [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]
1win_uz_dzsi
19 Oct 25 at 6:00 pm
1win kripto orqali yechish [url=http://1win5510.ru]1win kripto orqali yechish[/url]
1win_uz_vtsi
19 Oct 25 at 6:02 pm
бонус на депозит мелбет [url=https://melbetbonusy.ru]бонус на депозит мелбет[/url] .
melbet_mfOi
19 Oct 25 at 6:02 pm
The $MTAUR token presale milestones smash. Audits solid. Custom outfits stylish.
minotaurus ico
WilliamPargy
19 Oct 25 at 6:03 pm
купить диплом в анжеро-судженске [url=https://www.rudik-diplom9.ru]https://www.rudik-diplom9.ru[/url] .
Diplomi_bnei
19 Oct 25 at 6:03 pm
Hello this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if
you have to manually code with HTML. I’m starting a
blog soon but have no coding knowledge so I wanted to get guidance from someone with experience.
Any help would be enormously appreciated!
slut
19 Oct 25 at 6:04 pm
купить диплом судоводителя [url=rudik-diplom6.ru]купить диплом судоводителя[/url] .
Diplomi_ejKr
19 Oct 25 at 6:07 pm
бонус мелбет [url=https://www.melbetbonusy.ru]бонус мелбет[/url] .
melbet_vvOi
19 Oct 25 at 6:12 pm
купить диплом техникума недорого [url=http://www.frei-diplom11.ru]купить диплом техникума недорого[/url] .
Diplomi_qhsa
19 Oct 25 at 6:16 pm
казино мелбет бонусы [url=https://melbetbonusy.ru]казино мелбет бонусы[/url] .
melbet_zbOi
19 Oct 25 at 6:17 pm
The $MTAUR ICO is community-focused with events. Token’s in-game role vital. Presale value clear.
minotaurus coin
WilliamPargy
19 Oct 25 at 6:17 pm
Если пациент не может приехать в клинику, в Краснодаре нарколог приедет к нему домой. Помощь оказывает «Детокс» круглосуточно.
Подробнее – [url=https://narkolog-na-dom-krasnodar26.ru/]запой нарколог на дом[/url]
DanielCaupe
19 Oct 25 at 6:18 pm
1win apk yuklab olish [url=https://www.1win5510.ru]1win apk yuklab olish[/url]
1win_uz_fasi
19 Oct 25 at 6:18 pm
1win jonli kazino [url=https://1win5510.ru/]https://1win5510.ru/[/url]
1win_uz_fxsi
19 Oct 25 at 6:20 pm