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!
Terrific work! This is the type of information that should be shared across the internet.
Disgrace on Google for now not positioning this put
up upper! Come on over and talk over with my web site . Thank you =)
Order Zolpidem Online
19 Oct 25 at 7:45 pm
melbet вход с мобильного зеркало [url=https://www.melbetbonusy.ru]melbet вход с мобильного зеркало[/url] .
melbet_ltOi
19 Oct 25 at 7:45 pm
https://information74063.blogminds.com/examine-este-informe-sobre-detox-examen-de-orina-34707088
Detox para examen de miccion se ha convertido en una alternativa cada vez mas popular entre personas que requieren eliminar toxinas del sistema y superar pruebas de test de drogas. Estos formulas estan disenados para ayudar a los consumidores a purgar su cuerpo de sustancias no deseadas, especialmente las relacionadas con el consumo de cannabis u otras sustancias ilicitas.
Un buen detox para examen de orina debe brindar resultados rapidos y visibles, en particular cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas opciones, pero no todas prometen un proceso seguro o efectivo.
?Como funciona un producto detox? En terminos basicos, estos suplementos operan acelerando la depuracion de metabolitos y toxinas a traves de la orina, reduciendo su concentracion hasta quedar por debajo del umbral de deteccion de algunos tests. Algunos actuan en cuestion de horas y su impacto puede durar entre 4 a 6 horas.
Resulta fundamental combinar estos productos con correcta hidratacion. Beber al menos par litros de agua por jornada antes y despues del uso del detox puede mejorar los resultados. Ademas, se aconseja evitar alimentos grasos y bebidas acidas durante el proceso de uso.
Los mejores productos de detox para orina incluyen ingredientes como extractos de hierbas, vitaminas del tipo B y minerales que respaldan el funcionamiento de los sistemas y la funcion hepatica. Entre las marcas mas vendidas, se encuentran aquellas que presentan certificaciones sanitarias y estudios de eficacia.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con tiempos de accion largas o iniciar una preparacion previa. Mientras mas prolongada sea la abstinencia, mayor sera la eficacia del producto. Por eso, combinar la disciplina con el uso correcto del suplemento es clave.
Un error comun es creer que todos los detox actuan identico. Existen diferencias en dosis, sabor, metodo de uso y duracion del impacto. Algunos vienen en envase liquido, otros en capsulas, y varios combinan ambos.
Ademas, hay productos que agregan fases de preparacion o limpieza previa al dia del examen. Estos programas suelen sugerir abstinencia, buena alimentacion y descanso previo.
Por ultimo, es importante recalcar que todo detox garantiza 100% de exito. Siempre hay variables personales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no relajarse.
JuniorShido
19 Oct 25 at 7:48 pm
Thank you for sharing your info. I really appreciate your efforts and I will be waiting for your next post thanks once again.
j88slot
19 Oct 25 at 7:49 pm
купить диплом в красноярске [url=https://www.rudik-diplom7.ru]купить диплом в красноярске[/url] .
Diplomi_byPl
19 Oct 25 at 7:50 pm
1win litsenziya [url=1win5510.ru]1win5510.ru[/url]
1win_uz_ifsi
19 Oct 25 at 7:51 pm
fastgrowthsignal.bond – Highly recommended for anyone looking to drive fast, sustainable growth.
Kyle Ahlstedt
19 Oct 25 at 7:53 pm
Fantastic website. Plenty of helpful info here. I am sending it
to several buddies ans additionally sharing in delicious.
And naturally, thanks for your sweat!
반응형홈페이지제작업체
19 Oct 25 at 7:54 pm
диплом колледжа купить с занесением в реестр [url=www.frei-diplom2.ru/]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_aiEa
19 Oct 25 at 7:57 pm
bs2web at Что, еще не слышал о сенсации, сотрясающей глубины даркнета? Blacksprut – это не просто торговая марка. Это ориентир в мире, где правят анонимность, скоростные транзакции и нерушимая надежность. Спеши на bs2best.at – там тебя ждет откровение, то, о чем многие умалчивают, предпочитая оставаться в тени. Ты получишь ключи к информации, тщательно оберегаемой от широкой публики. Только для тех, кто посвящен в суть вещей. Полное отсутствие следов. Никаких компромиссов. Лишь совершенство, имя которому Blacksprut. Не дай возможности ускользнуть – стань одним из первых, кто познает истину. bs2best.at уже распахнул свои объятия. Готов ли ты к встрече с реальностью, которая шокирует?
HermanRhype
19 Oct 25 at 7:58 pm
1win demo slotlar [url=http://1win5509.ru]http://1win5509.ru[/url]
1win_uz_uvKt
19 Oct 25 at 8:00 pm
tadalafil italiano approvato AIFA: compresse per disfunzione erettile – cialis
RaymondNit
19 Oct 25 at 8:01 pm
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ꭰr c121,
Charlotte, NC 28273, United Ѕtates
+19803517882
Basement families remodeling for
Basement families remodeling for
19 Oct 25 at 8:01 pm
I feel this is one of the such a lot important info for me.
And i’m satisfied reading your article. However
wanna commentary on some general things, The site taste
is wonderful, the articles is actually great : D.
Just right task, cheers
https://xocdia24h.com/
19 Oct 25 at 8:02 pm
farmacia online fiable en España: cialis precio – tadalafilo 5 mg precio
JosephPseus
19 Oct 25 at 8:02 pm
мелбет бонус при регистрации 2025 [url=www.melbetbonusy.ru]мелбет бонус при регистрации 2025[/url] .
melbet_owOi
19 Oct 25 at 8:07 pm
teamworkinnovation.bond – Site loads quickly and content feels relevant and fresh.
Karla Stirman
19 Oct 25 at 8:08 pm
купить диплом в воронеже [url=www.rudik-diplom6.ru]купить диплом в воронеже[/url] .
Diplomi_fdKr
19 Oct 25 at 8:08 pm
can you get tegretol without a prescription
can you get tegretol tablets
19 Oct 25 at 8:08 pm
https://www.band.us/band/99495920/
Anthonycam
19 Oct 25 at 8:10 pm
медицинские приборы [url=https://medtehnika-msk.ru/]медицинские приборы[/url] .
oborydovanie medicinskoe_fvpa
19 Oct 25 at 8:12 pm
Greetings from Florida! I’m bored at work so I decided to check
out your site on my iphone during lunch break.
I love the info you present here and can’t wait to take a look when I get home.
I’m shocked at how quick your blog loaded on my cell phone ..
I’m not even using WIFI, just 3G .. Anyhow, fantastic
blog!
situs toto
19 Oct 25 at 8:16 pm
Стационарное лечение запоя в Воронеже — гарантированная анонимность и комфортные условия. Мы предлагаем индивидуальный подход к каждому пациенту, обеспечивая полное восстановление организма и предотвращение рецидивов.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре клиника в воронеже[/url]
RichardJuids
19 Oct 25 at 8:18 pm
1вин пополнить счет [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]
1win_uz_bxsi
19 Oct 25 at 8:18 pm
купить сертификат специалиста [url=http://www.rudik-diplom6.ru]купить сертификат специалиста[/url] .
Diplomi_eaKr
19 Oct 25 at 8:20 pm
1win ios yuklab olish [url=https://www.1win5509.ru]https://www.1win5509.ru[/url]
1win_uz_ipKt
19 Oct 25 at 8:22 pm
мелбет бонусный счет [url=https://melbetbonusy.ru/]мелбет бонусный счет[/url] .
melbet_twOi
19 Oct 25 at 8:23 pm
кракен vk3
кракен vk6
JamesDaync
19 Oct 25 at 8:23 pm
казино мелбет бонусы [url=https://melbetbonusy.ru]казино мелбет бонусы[/url] .
melbet_eqOi
19 Oct 25 at 8:25 pm
This website was… how do I say it? Relevant!!
Finally I’ve found something which helped me. Thanks!
bos medan4d tukang phising
19 Oct 25 at 8:26 pm
fastgrowthsignal.cfd – Navigation is intuitive and the information seems relevant and fresh.
Drew Piske
19 Oct 25 at 8:28 pm
В современном мире, полном стрессов и тревог, анксиолитики и транквилизаторы стали настоящим спасением для многих, помогая справляться с паническими атаками, генерализованным тревожным расстройством и другими состояниями, которые мешают жить полноценно. Эти препараты, такие как бензодиазепины (диазепам, алпразолам) или небензодиазепиновые варианты вроде буспирона, действуют через усиление эффекта ГАМК в мозге, снижая нейрональную активность и принося облегчение уже через короткое время. Они особенно ценны в начале курса антидепрессантов, поскольку смягчают стартовые нежелательные реакции, вроде усиленной раздражительности или проблем со сном, повышая удобство и результативность терапии. Но стоит учитывать возможные опасности: от сонливости и ухудшения внимания до риска привыкания, из-за чего их прописывают на ограниченный период под тщательным медицинским надзором. В клинике “Эмпатия” квалифицированные эксперты, среди которых психиатры и психотерапевты, разрабатывают персонализированные планы, сводя к минимуму противопоказания, такие как нарушения дыхания или беременность. Подробнее о механизмах, применении и безопасном использовании читайте на https://empathycenter.ru/articles/anksiolitiki-i-trankvilizatory/ , где собрана вся актуальная информация для вашего спокойствия.
vucytcDooms
19 Oct 25 at 8:31 pm
купить диплом в белогорске [url=http://rudik-diplom14.ru]http://rudik-diplom14.ru[/url] .
Diplomi_idea
19 Oct 25 at 8:33 pm
1win uz [url=1win5509.ru]1win5509.ru[/url]
1win_uz_tmKt
19 Oct 25 at 8:35 pm
мелбет сайт [url=melbetbonusy.ru]мелбет сайт[/url] .
melbet_beOi
19 Oct 25 at 8:37 pm
1win virtual sport [url=http://1win5509.ru]http://1win5509.ru[/url]
1win_uz_rlKt
19 Oct 25 at 8:38 pm
купить диплом техникума спб в барнауле [url=https://frei-diplom9.ru/]купить диплом техникума спб в барнауле[/url] .
Diplomi_kpea
19 Oct 25 at 8:39 pm
kraken vk4
кракен ссылка
JamesDaync
19 Oct 25 at 8:41 pm
bs2best зеркало В курсе ли ты, что сотрясает самые глубины тёмной сети? Blacksprut — это не просто название. Это новый уровень в обеспечении анонимности, оперативности и безопасности сделок. Посети bs2best.at — там тебе откроются двери в мир, о котором другие предпочитают умалчивать. Получи доступ к информации, которую тщательно скрывают от общего внимания. Только для тех, кто понимает и разбирается. Без возможности обнаружения. Без каких-либо уступок. Только Blacksprut. Не упусти свой шанс стать одним из первых — bs2best.at уже готов принять тебя в свои ряды. Готов ли ты к тому, что узнаешь?
HermanRhype
19 Oct 25 at 8:42 pm
http://www.bergkompressor.ru Погрузитесь в инновации – Узнайте о свежих и вдохновляющих проектах.
Jeremyjoync
19 Oct 25 at 8:45 pm
После детоксикации пациентам предлагаются различные психотерапевтические методы, такие как когнитивно-поведенческая терапия, арт-терапия и групповая терапия. Эти подходы помогают выявить и проработать причины зависимости, а также развить навыки преодоления стрессовых ситуаций без употребления наркотиков. Детальнее – http://www.kpilib.ru/forum.php?tema=12657
Crystaldum
19 Oct 25 at 8:45 pm
Minotaurus presale’s $6.4M target seems achievable fast. $MTAUR’s security audits reassure. Custom minotaur appearances excite. minotaurus token
WilliamPargy
19 Oct 25 at 8:45 pm
1win tennis tikish [url=1win5509.ru]1win5509.ru[/url]
1win_uz_mmKt
19 Oct 25 at 8:46 pm
1win tennis tikish [url=http://1win5510.ru/]http://1win5510.ru/[/url]
1win_uz_lfsi
19 Oct 25 at 8:48 pm
Bullish on Minotaurus ICO’s community. $MTAUR’s boosts strategic. Market growth aligns.
minotaurus presale
WilliamPargy
19 Oct 25 at 8:49 pm
wetten bester sportwetten österreich bonus (Gilda)
Gilda
19 Oct 25 at 8:49 pm
Выезд нарколога на дом в Нижнем Новгороде — капельница от запоя с выездом на дом. Мы обеспечиваем быстрое и качественное лечение без необходимости посещения клиники.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]наркологический вывод из запоя в нижний новгороде[/url]
Miltondiolo
19 Oct 25 at 8:51 pm
Легче сказать, чем сделать.
даже по окончании истечения срока проката, [url=https://kaksdelatgarazh.ru/virtualnyj-nomer-dlya-sms-udobstvo-i-bezopasnost-v-odnom-flakone/]https://kaksdelatgarazh.ru/virtualnyj-nomer-dlya-sms-udobstvo-i-bezopasnost-v-odnom-flakone/[/url] другие люди услуг не получат сведения о переданных смс – сообщениях.
Radamebeimi
19 Oct 25 at 8:52 pm
creativegiftworld.bond – I appreciate the variety, keeps discovering new useful ideas.
Reynaldo Parkhill
19 Oct 25 at 8:52 pm
1вин лайв ставки [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]
1win_uz_jzsi
19 Oct 25 at 8:53 pm