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://pereplanirovka-nezhilogo-pomeshcheniya8.ru]https://pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .
pereplanirovka nejilogo pomesheniya_coki
13 Oct 25 at 5:45 pm
карниз с приводом [url=http://karniz-shtor-elektroprivodom.ru]http://karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_fjer
13 Oct 25 at 5:54 pm
аренда погрузчиков в москве и московской области [url=http://arenda-ekskavatora-pogruzchika-cena-2.ru]http://arenda-ekskavatora-pogruzchika-cena-2.ru[/url] .
arenda ekskavatora pogryzchika cena_pjst
13 Oct 25 at 5:55 pm
где можно купить диплом медсестры [url=https://www.frei-diplom14.ru]где можно купить диплом медсестры[/url] .
Diplomi_fwoi
13 Oct 25 at 5:57 pm
узаконить перепланировку нежилого помещения [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_pjKl
13 Oct 25 at 5:57 pm
купить диплом медсестры [url=https://frei-diplom15.ru/]купить диплом медсестры[/url] .
Diplomi_smoi
13 Oct 25 at 5:57 pm
перепланировка в нежилом помещении [url=https://pereplanirovka-nezhilogo-pomeshcheniya8.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya8.ru/[/url] .
pereplanirovka nejilogo pomesheniya_tski
13 Oct 25 at 5:59 pm
переустройство нежилого помещения [url=www.pereplanirovka-nezhilogo-pomeshcheniya8.ru]www.pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .
pereplanirovka nejilogo pomesheniya_nwki
13 Oct 25 at 6:02 pm
http://amoxicareonline.com/# generic Amoxicillin pharmacy UK
HerbertScacy
13 Oct 25 at 6:02 pm
Частный заем денег ооо домашние деньги альтернатива банковскому кредиту. Быстро, безопасно и без бюрократии. Получите нужную сумму наличными или на карту за считанные минуты.
Grantgricy
13 Oct 25 at 6:03 pm
https://forum.geonames.org/gforum/user/profile/690411.page
https://forum.geonames.org/gforum/user/profile/690411.page
13 Oct 25 at 6:03 pm
buy viagra: Viagra online UK – British online pharmacy Viagra
Brettesofe
13 Oct 25 at 6:04 pm
перепланировка нежилых помещений [url=http://pereplanirovka-nezhilogo-pomeshcheniya8.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya8.ru/[/url] .
pereplanirovka nejilogo pomesheniya_nyki
13 Oct 25 at 6:04 pm
Je suis totalement seduit par Locowin Casino, c’est une plateforme qui bouillonne d’energie. La selection de jeux est phenomenale, comprenant des jeux compatibles avec les cryptos. Pour un demarrage en force. Les agents repondent avec rapidite, offrant des reponses claires. Les gains arrivent sans delai, mais des recompenses supplementaires seraient un atout. Dans l’ensemble, Locowin Casino garantit du fun a chaque instant pour les joueurs en quete d’excitation ! En prime le site est rapide et attrayant, amplifie le plaisir de jouer. A noter egalement les evenements communautaires engageants, qui booste l’engagement.
DГ©marrer maintenant|
QuantumLeapB8zef
13 Oct 25 at 6:04 pm
wettseiten
my web page – Einzahlungsbonus Sportwetten
Einzahlungsbonus Sportwetten
13 Oct 25 at 6:08 pm
трактор погрузчик аренда [url=http://arenda-ekskavatora-pogruzchika-cena-2.ru/]http://arenda-ekskavatora-pogruzchika-cena-2.ru/[/url] .
arenda ekskavatora pogryzchika cena_mxst
13 Oct 25 at 6:09 pm
Visitez Roulettino Casino https://roulettino-fr.com et obtenez un bonus de 500 € + 100 tours gratuits dès maintenant ! Explorez notre sélection de jeux et découvrez Roulettino Casino France, qui offre une expérience de jeu légale, réglementée et structurée, adaptée aux joueurs français. Pour en savoir plus, consultez le site web.
gosunFaula
13 Oct 25 at 6:10 pm
Heya i am for the first time here. I came across this board and I find It really helpful
& it helped me out much. I hope to provide one thing back and aid others
such as you aided me.
tits
13 Oct 25 at 6:10 pm
https://telegra.ph/Kupit-benzogenerator-bu-v-sverdlovskoj-oblasti-10-12
RobertHag
13 Oct 25 at 6:11 pm
order medication online legally in the UK: online pharmacy – pharmacy online UK
JamesDes
13 Oct 25 at 6:12 pm
https://probilets.com/
Rogerunsub
13 Oct 25 at 6:12 pm
Вывод из запоя в Твери проводится с применением современных методик, эффективность которых подтверждена медицинской практикой. Используются только проверенные препараты и процедуры, соответствующие клиническим стандартам.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-tver0.ru/]вывод из запоя с выездом тверь[/url]
Davidboots
13 Oct 25 at 6:12 pm
В «ВладЗдоровье» применяется комплексный подход, сочетающий медикаментозное лечение, психотерапию и реабилитацию. Врач-нарколог подбирает препараты индивидуально, с учётом анамнеза, переносимости компонентов и текущего состояния организма. Психотерапевтический блок включает когнитивно-поведенческую терапию, мотивационные интервью, семейную терапию и работу с посттравматическими реакциями.
Детальнее – [url=https://narkologicheskaya-pomoshh-vladimir0.ru/]оказание наркологической помощи в владимире[/url]
Russellsmugh
13 Oct 25 at 6:13 pm
карнизы с электроприводом купить [url=https://karniz-shtor-elektroprivodom.ru/]карнизы с электроприводом купить[/url] .
karniz dlya shtor s elektroprivodom_dyer
13 Oct 25 at 6:15 pm
orgy
Brentsek
13 Oct 25 at 6:15 pm
Wow that was strange. I just wrote an extremely long comment but after I
clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say
fantastic blog!
seriöses online casino deutschland
13 Oct 25 at 6:17 pm
Каждый из методов подбирается индивидуально, что позволяет учитывать медицинские показания и личные особенности пациента.
Детальнее – [url=https://lechenie-alkogolizma-perm0.ru/]лечение алкоголизма и наркомании центр пермь[/url]
Francisaxogy
13 Oct 25 at 6:17 pm
https://www.tumblr.com/candetoxblend/794393330425446400/preguntas-frecuentes-sobre-detox-para-examen-de
Limpieza para examen de orina se ha transformado en una opcion cada vez mas reconocida entre personas que requieren eliminar toxinas del cuerpo y superar pruebas de analisis de drogas. Estos productos estan disenados para ayudar a los consumidores a limpiar su cuerpo de residuos no deseadas, especialmente las relacionadas con el ingesta de cannabis u otras sustancias ilicitas.
Uno buen detox para examen de orina debe ofrecer resultados rapidos y confiables, en particular cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas alternativas, pero no todas prometen un proceso seguro o fiable.
Que funciona un producto detox? En terminos claros, estos suplementos funcionan acelerando la eliminacion de metabolitos y componentes a traves de la orina, reduciendo su presencia hasta quedar por debajo del nivel de deteccion de los tests. Algunos funcionan en cuestion de horas y su efecto puede durar entre 4 a seis horas.
Es fundamental combinar estos productos con adecuada hidratacion. Beber al menos par litros de agua por jornada antes y despues del consumo del detox puede mejorar los resultados. Ademas, se recomienda evitar alimentos pesados y bebidas azucaradas durante el proceso de preparacion.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de naturales, vitaminas del complejo B y minerales que apoyan el funcionamiento de los organos y la funcion hepatica. Entre las marcas mas vendidas, se encuentran aquellas que presentan certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de cannabis, se recomienda usar detoxes con tiempos de accion largas o iniciar una preparacion temprana. Mientras mas prolongada sea la abstinencia, mayor sera la eficacia del producto. Por eso, combinar la organizacion con el uso correcto del producto es clave.
Un error comun es suponer que todos los detox actuan identico. Existen diferencias en dosis, sabor, metodo de uso y duracion del impacto. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que incorporan fases de preparacion o preparacion previa al dia del examen. Estos programas suelen recomendar abstinencia, buena alimentacion y descanso recomendado.
Por ultimo, es importante recalcar que ningun detox garantiza 100% de exito. Siempre hay variables personales como metabolismo, historial de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no descuidarse.
JuniorShido
13 Oct 25 at 6:18 pm
https://c-ptsd-roadmap-to-light.mn.co/posts/92084612?utm_source=manual
https://c-ptsd-roadmap-to-light.mn.co/posts/92084612?utm_source=manual
13 Oct 25 at 6:19 pm
рулонные шторы автоматические купить [url=http://rulonnaya-shtora-s-elektroprivodom.ru/]http://rulonnaya-shtora-s-elektroprivodom.ru/[/url] .
rylonnaya shtora s elektroprivodom_nwKt
13 Oct 25 at 6:20 pm
Keiran Lee
Brentsek
13 Oct 25 at 6:20 pm
аренда экскаватора смена [url=www.arenda-ekskavatora-pogruzchika-cena-2.ru/]www.arenda-ekskavatora-pogruzchika-cena-2.ru/[/url] .
arenda ekskavatora pogryzchika cena_bqst
13 Oct 25 at 6:21 pm
«Как отмечает врач-нарколог Андрей Николаевич Селиванов, «своевременный визит специалиста на дом позволяет избежать тяжёлых осложнений и ускоряет стабилизацию состояния»».
Детальнее – [url=https://narkolog-na-dom-sankt-peterburg14.ru/]нарколог на дом анонимно в санкт-петербурге[/url]
Jerrysmism
13 Oct 25 at 6:21 pm
It’s the best time to make a few plans for the future and it’s time to
be happy. I’ve learn this put up annd if I may just I desire to suggest
yyou few attention-grabbing things or advice.
Maybe you could write next artjcles referring to this article.
I want to read more issues about it!
boyarka
13 Oct 25 at 6:25 pm
stellenangebote wettbüro
Also visit my site – Neue buchmacher
Neue buchmacher
13 Oct 25 at 6:29 pm
перепланировка офиса согласование [url=http://pereplanirovka-nezhilogo-pomeshcheniya8.ru]http://pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .
pereplanirovka nejilogo pomesheniya_qbki
13 Oct 25 at 6:32 pm
аренда экскаватора погрузчика цена москва [url=https://arenda-ekskavatora-pogruzchika-cena-2.ru]https://arenda-ekskavatora-pogruzchika-cena-2.ru[/url] .
arenda ekskavatora pogryzchika cena_nhst
13 Oct 25 at 6:32 pm
Today, while I was at work, my cousin stole my iPad and tested
to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views.
I know this is entirely off topic but I had to share
it with someone!
examples of securities in finance
13 Oct 25 at 6:34 pm
согласование перепланировки нежилого помещения в жилом доме [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/[/url] .
pereplanirovka nejilogo pomesheniya_maKl
13 Oct 25 at 6:35 pm
Enjoy fast VPS server with 4 gigabytes RAM, Ryzen 4-core CPU, and
4 terabytes transfer. Perfect for learners to learn applications.
free Backlinks
13 Oct 25 at 6:38 pm
دوست، در صورتی که نسبت به وبسایتهای بازیهای
شرطی فکر میکنید، ایست نمائید.
خودم تجربه مستقیم کردهام که نشان میگردد چنین سایتها وسیله جهت کلاهبرداری به
علاوه نابودی دارایی هستند.
پول سریع هدر میشود و سوءمصرف دائمی
میگردد. بهتر است پرهیز شوید و
به کمک روانشناسان توجه آورید!
site de apostas scam
13 Oct 25 at 6:38 pm
согласование проекта перепланировки нежилого помещения [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_pler
13 Oct 25 at 6:38 pm
https://probilets.com/
Stevennic
13 Oct 25 at 6:45 pm
электрокарнизы купить в москве [url=karniz-shtor-elektroprivodom.ru]электрокарнизы купить в москве[/url] .
karniz dlya shtor s elektroprivodom_bwer
13 Oct 25 at 6:46 pm
Everything typed made a bunch of sense. However, what about this?
what if you added a little content? I am not saying your content is
not good, however suppose you added a headline that grabbed folk’s attention? I mean PHP hook, building hooks in your application – Sjoerd
Maessen blog at Sjoerd Maessen blog is kinda boring. You might peek at Yahoo’s home
page and watch how they create news titles to grab viewers
to click. You might add a related video or a related pic
or two to grab readers interested about everything’ve written. In my opinion, it could bring your blog a little livelier.
Fundrex Impulso
13 Oct 25 at 6:47 pm
Все спортивные новости http://sportsat.ru в реальном времени. Итоги матчей, трансферы, рейтинги и обзоры. Следите за событиями мирового спорта и оставайтесь в курсе побед и рекордов!
sportsat-379
13 Oct 25 at 6:50 pm
https://probilets.com/
Jamesduets
13 Oct 25 at 6:50 pm
$MTAUR ICO is gaining traction over SHIB/XRP rallies. Token’s in-game convertibility ensures demand. Presale’s 1.4M USDT milestone proves it.
minotaurus presale
WilliamPargy
13 Oct 25 at 6:50 pm
Частный заем денег домашние деньги займ на карту альтернатива банковскому кредиту. Быстро, безопасно и без бюрократии. Получите нужную сумму наличными или на карту за считанные минуты.
Grantgricy
13 Oct 25 at 6:50 pm
Перед выбором метода врач проводит диагностику, оценивает физическое и психоэмоциональное состояние пациента, рассказывает о возможных рисках и особенностях процедуры. Только после согласования всех деталей назначается дата и форма кодирования.
Получить дополнительную информацию – [url=https://kodirovanie-ot-alkogolizma-ehlektrostal6.ru/]kodirovanie-ot-alkogolizma-ceny[/url]
ScottCet
13 Oct 25 at 6:51 pm