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!
Футболка царь и Петрозаводск печать на футболки в Севастополе. Принты на толстовку и толстовки мужские оптом в Нальчике. Печать на футболках в Хабаровске и футболки с интересными надписи в Екатеринбурге. Мешок для одежды и все ради игры одежда в Иваново. Футболка оптом сэндвич под сублимацию и на валберис женские футболки https://futbolki-s-printom.ru/
Gregorysnisp
19 Sep 25 at 6:52 pm
cocaine in prague buy drugs in prague
prague-drugs-848
19 Sep 25 at 6:53 pm
займы все [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_okMi
19 Sep 25 at 6:54 pm
https://martinmzmwg.pointblog.net/consultoria-en-diagnostico-de-necesidades-de-capacitacion-fundamentos-explicaciГіn-84227123
El diagnostico de necesidades de capacitacion es la piedra angular para disenar programas de formacion que impacten. En el mercado chileno, muchas organizaciones invierten millones en talleres que pasan sin impacto porque nunca hicieron un levantamiento claro de lo que sus colaboradores requieren.
Motivos de hacer un diagnostico de necesidades de capacitacion?
Detecta las carencias reales de competencias.
Previene inversiones inutiles en cursos.
Conecta la inversion con la vision corporativa.
Aumenta la satisfaccion de los trabajadores.
Formas para aplicar un diagnostico de necesidades de capacitacion
Formularios internos: simples de aplicar, ideales para levantar la percepcion de los empleados.
Entrevistas con lideres: permiten detectar expectativas de cada unidad.
Monitoreo: ver el flujo real para reconocer oportunidades invisibles en papel.
Mediciones de desempeno: conectan objetivos con las habilidades que se deben mejorar.
Beneficios de un diagnostico de necesidades de capacitacion bien hecho
Cursos que responden con las brechas reales.
Eficiencia de dinero.
Evolucion profesional alineado con la vision de la empresa.
Efectos visibles en productividad.
Errores comunes al hacer un diagnostico de necesidades de capacitacion
Imitar modelos de otras empresas sin personalizar.
Reducir deseos de jefaturas con brechas reales.
Ignorar la voz de los colaboradores.
Analizar solo una vez y no revisar.
Un diagnostico de necesidades de capacitacion es la herramienta para construir una estrategia de desarrollo transformadora.
JuniorShido
19 Sep 25 at 6:55 pm
диплом реестр купить [url=http://frei-diplom2.ru/]диплом реестр купить[/url] .
Diplomi_hgEa
19 Sep 25 at 6:57 pm
Hey There. I found your blog using msn. This is an extremely well written article.
I’ll make sure to bookmark it and return to read more of
your useful info. Thanks for the post. I will definitely comeback.
Stepanie
19 Sep 25 at 6:57 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 6:58 pm
Cash Pandas игра
Davidfes
19 Sep 25 at 6:59 pm
Hello there I am so excited I found your blog, I really found you by accident, while I was looking on Askjeeve for
something else, Regardless I am here now and would just like
to say kudos for a tremendous post and a all round entertaining blog (I also love the theme/design), I don’t
have time to go through it all at the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great
deal more, Please do keep up the great b.
kontol pendek
19 Sep 25 at 6:59 pm
купить диплом в донском [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .
Diplomi_vePl
19 Sep 25 at 6:59 pm
займы онлайн все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_qgMi
19 Sep 25 at 6:59 pm
купить диплом средне техническое [url=http://rudik-diplom11.ru]купить диплом средне техническое[/url] .
Diplomi_sjMi
19 Sep 25 at 7:00 pm
https://419dfb96bd89fa04b0dc772f7d.doorkeeper.jp/
HarryPaync
19 Sep 25 at 7:01 pm
Your mode of telling all in this paragraph is in fact good,
all be able to effortlessly understand it, Thanks a lot.
비아그라 구매
19 Sep 25 at 7:01 pm
I’m really impressed with your writing skills as well as with
the layout on your blog. Is this a paid theme or did you modify it
yourself? Anyway keep up the excellent quality writing, it’s rare to see a great
blog like this one these days.
آمبولانس خصوصی قرچک
19 Sep 25 at 7:02 pm
купить диплом менеджера [url=https://rudik-diplom1.ru/]купить диплом менеджера[/url] .
Diplomi_czer
19 Sep 25 at 7:04 pm
микрозайм всем [url=www.zaimy-16.ru/]www.zaimy-16.ru/[/url] .
zaimi_oiMi
19 Sep 25 at 7:07 pm
купить диплом о среднем техническом образовании [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_jyea
19 Sep 25 at 7:08 pm
как накрутить подписчиков в тг канал
MatthewRow
19 Sep 25 at 7:10 pm
все микрозаймы на карту [url=https://zaimy-16.ru]https://zaimy-16.ru[/url] .
zaimi_ouMi
19 Sep 25 at 7:12 pm
купить диплом врача с занесением в реестр [url=https://www.frei-diplom1.ru]купить диплом врача с занесением в реестр[/url] .
Diplomi_uuOi
19 Sep 25 at 7:12 pm
займы [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .
zaimi_muMi
19 Sep 25 at 7:12 pm
купить диплом маляра [url=rudik-diplom8.ru]купить диплом маляра[/url] .
Diplomi_sbMt
19 Sep 25 at 7:15 pm
купить диплом в черкесске [url=www.rudik-diplom11.ru]купить диплом в черкесске[/url] .
Diplomi_oxMi
19 Sep 25 at 7:15 pm
Quality articles or reviews is the secret to be a focus for the users to visit the web site,
that’s what this site is providing.
비아그라 구매
19 Sep 25 at 7:16 pm
https://www.blackcollegechampionships.com/riverwalk-stadium/#comment-203415
Jeffreycen
19 Sep 25 at 7:16 pm
Hi there superb blog! Does running a blog such as this require a massive amount work?
I have absolutely no expertise in coding but I
had been hoping to start my own blog soon. Anyhow, if you have
any recommendations or techniques for new blog
owners please share. I know this is off topic nevertheless I simply needed to ask.
Cheers!
آمبولانس خصوصی ورامین
19 Sep 25 at 7:16 pm
займы все [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .
zaimi_gzMi
19 Sep 25 at 7:17 pm
Рекламные носители остаются одним из самых действенных инструментов рекламы. Среди них важным решением считается [url=https://format-ms.ru/catalog/roll-up/]ролл ап заказать с печатью[/url] ведь такой баннер сочетает эргономичность и заметность. Он заметно усиливает бренд на форуме, в шоуруме или на презентации товаров. Модель продумана для транспортировки, быстро монтируется и даёт мгновенный эффект на лояльность клиентов.
Компания Format-MS уже много лет занимается изготовлением и печатью роллапов. В студии используют экологичные ткани, новейшие методы печати и добиваются ярких цветов. Клиенты доверяют нам быстрое изготовление заказов, профессиональную установку и консультации. Адрес офиса: Москва, Нагорный проезд, дом 7, стр 1, офис 2320. Для оформления заказа всегда доступен телефон +7 (499) 390-19-85. На сайте format-ms.ru можно ознакомиться с услугами и сделать заявку.
Если вам требуется [url=https://format-ms.ru/catalog/roll-up/]roll up стоимость[/url] специалисты подберут конструкции с повышенной устойчивостью к осадкам и сырости. Плотные баннерные полотна, надёжные механизмы и стойкость красок делают такие изделия практичными даже при уличных условиях. Это решение станет важным элементом продвижения, который привлекает клиентов круглосуточно и не теряет своей выразительности.
Formaticam
19 Sep 25 at 7:17 pm
микрозаймы все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_ncMi
19 Sep 25 at 7:18 pm
купить медицинский диплом медсестры [url=http://www.frei-diplom13.ru]купить медицинский диплом медсестры[/url] .
Diplomi_dxkt
19 Sep 25 at 7:20 pm
все займы ру [url=https://www.zaimy-16.ru]https://www.zaimy-16.ru[/url] .
zaimi_agMi
19 Sep 25 at 7:20 pm
Chase for Glory играть в 1хбет
JoshuaStism
19 Sep 25 at 7:23 pm
накрутка подписчиков в тг смм накрутка
JerryBealo
19 Sep 25 at 7:24 pm
http://www.pageorama.com/?p=ehbadoha
HarryPaync
19 Sep 25 at 7:26 pm
Заказать диплом университета мы поможем. Купить диплом техникума, колледжа в Сургуте – [url=http://diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-surgute/]diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-surgute[/url]
Cazrjyi
19 Sep 25 at 7:28 pm
buy coke in prague buy cocaine prague
prague-drugs-140
19 Sep 25 at 7:28 pm
купить диплом в славянске-на-кубани [url=http://rudik-diplom10.ru/]http://rudik-diplom10.ru/[/url] .
Diplomi_neSa
19 Sep 25 at 7:30 pm
купить диплом сварщика [url=http://rudik-diplom7.ru/]купить диплом сварщика[/url] .
Diplomi_liPl
19 Sep 25 at 7:30 pm
Состав подбирается персонально, без шаблонов: корректируется гидратация, электролиты, витамины, антиоксидантная и гепатопротекторная поддержка. Ниже приведены ориентировочные модели, иллюстрирующие подход к детоксу при разных клинических сценариях.
Разобраться лучше – [url=https://vyvod-iz-zapoya-ulan-ude0.ru/]вывод из запоя на дому недорого улан-удэ[/url]
SimonTon
19 Sep 25 at 7:31 pm
liquid prohormones for sale
References:
Anadrol Weight Gain (Forum.Issabel.Org)
Forum.Issabel.Org
19 Sep 25 at 7:33 pm
I blog frequently and I genuinely thank you for your content.
The article has truly peaked my interest. I am going to take a
note of your website and keep checking for new information about once a week.
I subscribed to your RSS feed too.
آمبولانس خصوصی ورامین
19 Sep 25 at 7:34 pm
Meaning, oriigin ɑnd history оf tһe name Evangelina
Also visit my blog … Dorinda Merley Ѕays Sonja Morgan’s “Complete Meltdown” Wass Scary, frankiepeach.com,
frankiepeach.com
19 Sep 25 at 7:35 pm
все займы онлайн [url=https://www.zaimy-16.ru]все займы онлайн[/url] .
zaimi_cvMi
19 Sep 25 at 7:35 pm
http://tretinoinwebpin.mex.tl/?gb=1#top
Jeffreycen
19 Sep 25 at 7:38 pm
Way cool! Some very valid points! I appreciate you writing this article
and the rest of the site is extremely good.
https://github.com
19 Sep 25 at 7:38 pm
все микрозаймы на карту [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_oeMi
19 Sep 25 at 7:40 pm
Quality content is the key to invite the people to go to
see the web site, that’s what this web site is providing.
OrtevalexAi TEST
19 Sep 25 at 7:41 pm
займы онлайн все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_dhMi
19 Sep 25 at 7:43 pm
Hello just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly.
I’m not sure why but I think its a linking issue.
I’ve tried it in two different internet browsers and both show the same outcome.
비아그라 구입
19 Sep 25 at 7:43 pm