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!
dragon money зеркало Драгон Мани – удобное онлайн-казино с турнирами и слотами. Быстрые выплаты и азартная атмосфера для игроков всех уровней
SteveTib
13 Sep 25 at 5:32 pm
В первые часы важно не «залить» пациента растворами, а корректно подобрать темп и состав с учётом возраста, массы тела, артериального давления, лекарственного фона (антигипертензивные, сахароснижающие, антиаритмические препараты) и переносимости. Именно поэтому мы не отдаём лечение на откуп шаблонам — каждая схема конструируется врачом на месте, а эффективность оценивается по понятным метрикам.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-ryazani14.ru/]врач вывод из запоя рязань[/url]
Jameszinee
13 Sep 25 at 5:35 pm
drgn Драгон Мани – удобное онлайн-казино с турнирами и слотами. Быстрые выплаты и азартная атмосфера для игроков всех уровней
SteveTib
13 Sep 25 at 5:36 pm
Hi, constantly i used to check webpage posts here in the early hours in the
dawn, since i love to find out more and more.
buôn bán nội tạng
13 Sep 25 at 5:37 pm
карнизы для штор купить в москве [url=http://avtomaticheskie-karnizy-dlya-shtor.ru/]карнизы для штор купить в москве[/url] .
avtomaticheskie karnizi dlya shtor_tdOr
13 Sep 25 at 5:40 pm
Нарколог на дом, это важная услуга для людей‚ страдающих от зависимости от наркотиков. Комплексный подход необходим для лечения наркомании‚ и домашняя помощь обеспечивает комфорт и анонимность. Вызов нарколога позволяет обратиться за медицинской помощью и приступить к программе детоксикации‚ не покидая домашнего уюта; Психотерапия и медицинская помощь помогают пациентам преодолеть зависимость‚ а поддержка близких играет ключевую роль в восстановлении после зависимости. Конфиденциальное лечение и профилактика наркомании также являются значимыми аспектами. Посетив vivod-iz-zapoya-vladimir015.ru‚ вы получите квалифицированную помощь и поддержку.
vivodvladimirNeT
13 Sep 25 at 5:41 pm
http://curabharatusa.com/# CuraBharat USA
CarlosPreom
13 Sep 25 at 5:44 pm
This article is in fact a pleasant one it helps new
net people, who are wishing for blogging.
Sterk Tradelux Anmeldelse
13 Sep 25 at 5:47 pm
О качестве товара отпишу в трипрепортах .Мир, и процветания этому магазину)))
https://linkin.bio/huberd5m2gerhard
сегодня оплатил заказ jwh-250 5РіСЂ. Р±СѓРґСѓ ждать, после отпишусь…
AnthonyGag
13 Sep 25 at 5:47 pm
купить диплом недорого [url=www.educ-ua16.ru]купить диплом недорого[/url] .
Diplomi_mzmi
13 Sep 25 at 5:50 pm
Приобрести диплом возможно используя официальный сайт компании. [url=http://ptcmint.com/read-blog/7131_mozhno-li-kupit-attestat-za-9-klass.html/]ptcmint.com/read-blog/7131_mozhno-li-kupit-attestat-za-9-klass.html[/url]
Sazrqmn
13 Sep 25 at 5:50 pm
[url=https://24kardio.ru/]ультразвуковые ванны для лабораторий[/url] представляют собой современное оборудование, которое используется для эффективной очистки инструментов и деталей. Принцип действия основан на ультразвуковых волнах, которые формируют микроскопические пузырьки, способные проникать в мельчайшие щели и обеспечивать качественную очистку. Оборудование помогает уменьшить ручной труд и обеспечивает высокий уровень чистоты при минимальных усилиях. Сферы применения охватывают очистку пробирок, колб, микроскопических аксессуаров и других сложных предметов. К преимуществам ультразвуковых ванн относят надежность, долгий срок службы и простоту эксплуатации. Производители предлагают широкий выбор приборов, среди которых можно найти как компактные настольные варианты, так и мощные промышленные решения. Чтобы подобрать оптимальное устройство, рекомендуется обращать внимание на характеристики мощности и качество корпуса. Стоимость оборудования может варьироваться, и правильный выбор позволяет найти баланс между ценой и качеством. Использование таких устройств положительно сказывается на результатах работы, так как гарантируется стерильность и чистота инструментов. Популярность этих устройств объясняется сочетанием эффективности, доступности и универсальности.
https://24kardio.ru/
kardiohaich
13 Sep 25 at 5:56 pm
Thanks on your marvelous posting! I actually enjoyed reading it, you’re a great author.
I will be sure to bookmark your blog and will come back someday.
I want to encourage you to continue your great job, have a nice afternoon!
Clubnika зеркало
13 Sep 25 at 5:57 pm
драгон мани официальный сайт Драгон Мани – онлайн-казино с турнирами, слотами и быстрыми призами. Отличный выбор для любителей риска и драйва!
Williamreips
13 Sep 25 at 5:57 pm
драгон мани Драгон Мани – платформа для азартных игр с турнирами и слотами. Простота, скорость и шанс на крупный выигрыш!
HowardFig
13 Sep 25 at 6:01 pm
карнизы для штор купить в москве [url=https://elektrokarniz-cena.ru/]карнизы для штор купить в москве[/url] .
elektrokarniz cena_ayPL
13 Sep 25 at 6:01 pm
Ключевая идея «ДонЗдрава» — соединить доказательную медицину и понятную пациенту логистику. Инфузии рассчитываются через инфузомат, жизненные показатели контролируются портативным кардиомонитором и пульсоксиметром, а лекарственные взаимодействия проверяются по протоколу перед началом терапии. При этом каждый шаг объясняется простым языком: что делаем, зачем это нужно и как будем оценивать результат через 30, 60 и 120 минут. После визита пациент не остаётся один — доступна «горячая линия» и короткие онлайн-сессии с врачом либо психологом, если тревога или бессонница возвращаются в ночные часы.
Подробнее – [url=https://vivod-iz-zapoya-rostov14.ru/]вывод из запоя капельница[/url]
BrianBlogy
13 Sep 25 at 6:02 pm
Важная деталь — отсутствие полипрагмазии. Мы используем «минимально достаточную фармакотерапию»: каждый препарат имеет цель, окно эффективности и критерии отмены. Это снижает побочные эффекты, убирает «тяжесть» днём и делает восстановление более естественным.
Получить дополнительную информацию – [url=https://narkologicheskaya-klinika-v-spb14.ru/]наркологическая клиника клиника помощь[/url]
Anthonygom
13 Sep 25 at 6:03 pm
http://saludfrontera.com/# meds from mexico
CarlosPreom
13 Sep 25 at 6:07 pm
Да,меня тоже!)заказал вчера тут 203-го,сегодня жду трека!
https://igli.me/andrewmorrison1961
РќРѕ зато РІ том случае Р±СѓРґСѓС‚ доказательства, что селлер обещал РѕРґРЅРѕ, Р° пришло совсем РґСЂСѓРіРѕРµ) Так что СЏ правильно написал 😉
AnthonyGag
13 Sep 25 at 6:11 pm
Have you heard about the changes in car rental in Dubai? https://test.metropolis-group.ru/forum/messages/forum1/topic601/message1162/?result=new#message1162
DanielMiz
13 Sep 25 at 6:12 pm
Have you heard about the changes in car rental in Dubai? https://www.myaspenridge.com/board/board_topic/3180173/7163475.htm
DanielMiz
13 Sep 25 at 6:16 pm
«Как отмечает врач-нарколог Андрей Николаевич Селиванов, «своевременный визит специалиста на дом позволяет избежать тяжёлых осложнений и ускоряет стабилизацию состояния»».
Подробнее тут – [url=https://narkolog-na-dom-sankt-peterburg14.ru/]вызвать нарколога на дом[/url]
Robertfloum
13 Sep 25 at 6:17 pm
«Как отмечает врач-нарколог Алексей Николаевич Прудников, «выезд нарколога на дом — это возможность стабилизировать состояние пациента в привычной обстановке, снизив стресс и риски осложнений».»
Узнать больше – http://narkolog-na-dom-v-krasnodare14.ru
PetermEn
13 Sep 25 at 6:17 pm
купить диплом стоимость [url=http://www.educ-ua19.ru]купить диплом стоимость[/url] .
Diplomi_ixml
13 Sep 25 at 6:18 pm
sin receta risperdal
Jeremylic
13 Sep 25 at 6:18 pm
Таможенный брокер в Москве поможет пройти все этапы оформления грузов быстро и без лишних затрат времени: https://tamozhenniiy-broker11.ru/
Jasonduada
13 Sep 25 at 6:20 pm
купить диплом с занесением в реестр вуза [url=http://arus-diplom34.ru]купить диплом с занесением в реестр вуза[/url] .
Diplomi_cher
13 Sep 25 at 6:20 pm
comprar Semaglutida
Jeremylic
13 Sep 25 at 6:21 pm
электрокарнизы для штор [url=www.avtomaticheskie-karnizy.ru]электрокарнизы для штор[/url] .
avtomaticheskie karnizi_vrSa
13 Sep 25 at 6:22 pm
электрокарнизы для штор [url=www.elektro-karniz77.ru]электрокарнизы для штор[/url] .
elektro karniz_qwSl
13 Sep 25 at 6:23 pm
I always used to read article in news papers but now
as I am a user of net thus from now I am using net for content, thanks to web.
online slots real money
13 Sep 25 at 6:23 pm
Spot on with this write-up, I honestly believe this site needs a lot more
attention. I’ll probably be returning to read through more, thanks for the information!
บริการรับทำบรรจุภัณฑ์
13 Sep 25 at 6:24 pm
https://saludfrontera.shop/# SaludFrontera
JeremyBip
13 Sep 25 at 6:25 pm
Undeniably imagine that which you said. Your favorite justification appeared to be at the net the easiest thing to
be mindful of. I say to you, I certainly get irked even as people consider concerns that they just do not recognize about.
You managed to hit the nail upon the top and defined out the whole thing
without having side-effects , people can take a signal. Will probably be again to get
more. Thanks
Margin Rivou Platform
13 Sep 25 at 6:31 pm
электрокарнизы для штор [url=http://www.elektrokarniz-cena.ru]электрокарнизы для штор[/url] .
elektrokarniz cena_qrPL
13 Sep 25 at 6:31 pm
Важная деталь — отсутствие полипрагмазии. Мы используем «минимально достаточную фармакотерапию»: каждый препарат имеет цель, окно эффективности и критерии отмены. Это снижает побочные эффекты, убирает «тяжесть» днём и делает восстановление более естественным.
Подробнее тут – [url=https://narkologicheskaya-klinika-v-spb14.ru/]наркологическая клиника нарколог санкт-петербург[/url]
Anthonygom
13 Sep 25 at 6:33 pm
Heya i’m for the first time here. I came across this board
and I find It really useful & it helped me out a
lot. I hope to give something back and aid others like you
aided me.
برای ورود کلیک کنید
13 Sep 25 at 6:35 pm
Отличный,ровный МАГАЗ!
https://ilm.iou.edu.gm/members/yowyjeruvureke/
трек кинули ровно оперативно как придет отпишу за качество 250
AnthonyGag
13 Sep 25 at 6:35 pm
https://www.speedrun.com/users/candetoxblend
Enfrentar un examen de drogas ya no tiene que ser una incertidumbre. Existe una alternativa científica que actúa rápido.
El secreto está en su fórmula canadiense, que sobrecarga el cuerpo con creatina, provocando que la orina oculte los marcadores de THC. Esto asegura un resultado confiable en menos de lo que imaginas, con efectividad durante 4 a 5 horas.
Lo mejor: es un plan de emergencia, diseñado para candidatos en entrevistas laborales.
Miles de clientes confirman su rapidez. Los envíos son 100% discretos, lo que refuerza la tranquilidad.
Si tu meta es asegurar tu futuro laboral, esta alternativa es la respuesta que estabas buscando.
JuniorShido
13 Sep 25 at 6:37 pm
Helpful info. Lucky me I found your web site accidentally,
and I am stunned why this accident didn’t happened earlier!
I bookmarked it.
dewascatter
13 Sep 25 at 6:37 pm
Если состояние стремительно ухудшается, ждать опасно: осложнения могут развиваться в течение часов. Немедленная помощь врача-нарколога показана, когда наблюдаются:
Исследовать вопрос подробнее – [url=https://narkologicheskaya-pomoshch-ramenskoe7.ru/]круглосуточная наркологическая помощь[/url]
LarryMub
13 Sep 25 at 6:39 pm
Как быстро запускается
Детальнее – https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/kruglosutochnaya-narkologicheskaya-pomoshch-v-orekhovo-zuevo
Donalddoume
13 Sep 25 at 6:42 pm
Актуальные методы помощи при запое в Туле предполагают интегрированном подходе, который предоставляет качественное лечение зависимости и поддержку пациента. Основная задача состоит в том, чтобы выведение токсинов, что позволяет устранить физическую зависимость. Наркологическая помощь содержит медицинскую помощь и психологическую поддержку, направленную на улучшение психоэмоционального состояния. помощь нарколога Экстренная помощь часто требуется для минимизации негативных эффектов. Крайне важно обеспечить помощь близких, так как это способствует успешной реабилитации. Персонализированный подход к индивидуальным потребностям дает возможность разработать индивидуальные планы лечения, учитывающие особенности клиента. Советы нарколога способствуют лучше осознать путь к выздоровлению после запоя, а психологическая поддержка играет ключевую роль в поддержании трезвости.
narkologiyatulaNeT
13 Sep 25 at 6:44 pm
https://truenorthpharm.shop/# canada pharmacy 24h
JeremyBip
13 Sep 25 at 6:46 pm
Pineal XT sounds fascinating, especially since it focuses on supporting pineal gland health and
boosting overall energy and clarity. I like that it’s marketed as a natural way to improve focus, balance mood, and even enhance spiritual well-being.
If it truly helps with mental sharpness and a deeper sense
of calm, Pineal XT could be a unique supplement for people who want both cognitive
and holistic benefits.
pineal xt
13 Sep 25 at 6:46 pm
https://martinnhns210.tearosediner.net/alimentos-que-pueden-alterar-un-examen-de-orina-y-qu-evitar
Superar una prueba preocupacional puede ser arriesgado. Por eso, se desarrollo un suplemento innovador creada con altos estandares.
Su mezcla premium combina nutrientes esenciales, lo que ajusta tu organismo y oculta temporalmente los metabolitos de alcaloides. El resultado: una prueba sin riesgos, lista para entregar tranquilidad.
Lo mas interesante es su accion rapida en menos de 2 horas. A diferencia de otros productos, no promete limpiezas magicas, sino una solucion temporal que te respalda en situaciones criticas.
Miles de postulantes ya han comprobado su discrecion. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si necesitas asegurar tu resultado, esta formula te ofrece confianza.
JuniorShido
13 Sep 25 at 6:46 pm
You could definitely see your expertise within the work you write.
The sector hopes for even more passionate writers such as
you who aren’t afraid to mention how they believe. Always follow
your heart.
Bonuses
13 Sep 25 at 6:48 pm
Meds information leaflet. Short-Term Effects.
can i take losartan instead of lisinopril
Everything news about pills. Read information here.
can i take losartan instead of lisinopril
13 Sep 25 at 6:51 pm
Excellent web site you have got here.. It’s difficult to find good quality writing like yours these days.
I truly appreciate people like you! Take care!!
BlorBytAi
13 Sep 25 at 6:53 pm