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=http://zhalyuzi-s-elektroprivodom77.ru/]жалюзи с электроприводом купить[/url] .
jaluzi na okna s elektroprivodom_xopa
14 Oct 25 at 8:17 am
карниз для штор электрический [url=http://www.elektrokarnizy797.ru]карниз для штор электрический[/url] .
elektrokarnizi_olMl
14 Oct 25 at 8:18 am
Hi there it’s me, I am also visiting this website on a regular basis, this web page is truly pleasant and
the visitors are truly sharing pleasant thoughts.
Bitnex Crestfort Opiniones
14 Oct 25 at 8:19 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Прочитать подробнее – https://www.stephendasko.com/portfolio/flippin-the-bird
Howardsauri
14 Oct 25 at 8:19 am
аренда экскаватора-погрузчика [url=https://www.arenda-ekskavatora-pogruzchika-cena-2.ru]аренда экскаватора-погрузчика[/url] .
arenda ekskavatora pogryzchika cena_ftst
14 Oct 25 at 8:20 am
купить диплом в новошахтинске [url=rudik-diplom5.ru]rudik-diplom5.ru[/url] .
Diplomi_okma
14 Oct 25 at 8:20 am
I have been browsing online greater than three hours these days, but I never
found any interesting article like yours.
It is beautiful worth sufficient for me. Personally, if all webmasters
and bloggers made good content as you probably did, the net might be much more helpful than ever before.
dewascatter link alternatif
14 Oct 25 at 8:21 am
provera online
provera online
14 Oct 25 at 8:23 am
автоматические гардины для штор [url=www.karniz-elektroprivodom.ru/]www.karniz-elektroprivodom.ru/[/url] .
karniz elektroprivodom shtor kypit_enei
14 Oct 25 at 8:23 am
I know this web page gives quality based articles and extra stuff, is there any other web page which provides these kinds of information in quality?
orthodontics Gainesville GA
14 Oct 25 at 8:23 am
как легально купить диплом о [url=http://frei-diplom6.ru]как легально купить диплом о[/url] .
Diplomi_jiOl
14 Oct 25 at 8:23 am
Why users still use to read news papers when in this technological world all is accessible on web?
sports jerseys
14 Oct 25 at 8:23 am
карниз электро [url=https://karniz-shtor-elektroprivodom.ru]https://karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_qher
14 Oct 25 at 8:24 am
Aumentará la confianza en el sitio web
Valor de autoridad del dominio (DR de Ahrefs)
Aumentará la reputación en el sitio web.
El posicionamiento de tu sitio web es crucial para el SEO.
Nos especializamos en atraer arañas de búsqueda de Google a tu sitio para mejorar su ranking.
Existen dos clases básicas de robots de búsqueda:
Robots de exploración – los que analizan inicialmente el sitio.
Indexing robots – acceden siguiendo las indicaciones de los robots de rastreo.
Mientras más visitas realicen estos robots a tu sitio, mayor será tu visibilidad.
Antes de comenzar, te proporcionaremos una evidencia del DR desde Ahrefs.
Después de completar el trabajo, también te enviaremos una imagen renovada del puntaje de tu sitio en Ahrefs.
Paga solo por resultados.
Periodo de entrega: de 3 a 14 días.
El servicio se aplica a sitios con DR máximo de 50.
Para gestionar tu pedido necesitamos:
Un enlace de tu sitio web.
Una palabra clave.
Las redes sociales no son aptas para este servicio.
Autoridad de dominio
14 Oct 25 at 8:25 am
жалюзи с электроприводом [url=http://www.zhalyuzi-s-elektroprivodom77.ru]жалюзи с электроприводом[/url] .
jaluzi na okna s elektroprivodom_ujpa
14 Oct 25 at 8:25 am
рулонные шторы на окна цена [url=www.rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на окна цена[/url] .
rylonnaya shtora s elektroprivodom_pbKt
14 Oct 25 at 8:25 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Подробнее можно узнать тут – https://www.orangepublicmanagement.it/it/keeping-employees-happy
RobertDax
14 Oct 25 at 8:25 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Всё, что нужно знать – https://tourjunket.com/indias-most-instagrammed-tourist-hotspots-in-2024
BruceEmoli
14 Oct 25 at 8:25 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Полезно знать – https://hotelparkdoha.com/ar/parking-subscribers-can-enjoy-15-discount-at-restaurants-located-at-hotel-park
PhilipOxync
14 Oct 25 at 8:27 am
согласование перепланировки в нежилом помещении [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_sjSr
14 Oct 25 at 8:27 am
переустройство нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/[/url] .
pereplanirovka nejilogo pomesheniya_ekKl
14 Oct 25 at 8:27 am
medex without prescription
medex without prescription
14 Oct 25 at 8:27 am
купить диплом в нижним тагиле [url=www.rudik-diplom3.ru]купить диплом в нижним тагиле[/url] .
Diplomi_lrei
14 Oct 25 at 8:27 am
потолочкин натяжные потолки самара отзывы клиентов [url=http://www.stretch-ceilings-samara-1.ru]http://www.stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_pcsl
14 Oct 25 at 8:27 am
Начнем путешествие по магическим уголкам российских заповедников.
Для тех, кто ищет информацию по теме “Изучение ООПТ России: парки, заповедники, водоемы”, есть отличная статья.
Вот, можете почитать:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
14 Oct 25 at 8:28 am
аренда экскаватора в москве цена [url=www.arenda-mini-ekskavatora-v-moskve-2.ru]аренда экскаватора в москве цена[/url] .
arenda mini ekskavatora v moskve_kdKt
14 Oct 25 at 8:29 am
купить диплом электромонтера [url=rudik-diplom8.ru]купить диплом электромонтера[/url] .
Diplomi_hjMt
14 Oct 25 at 8:30 am
Je suis hante par Casombie, il offre une aventure aussi sombre que palpitante. La selection de jeux est terrifiante de richesse, offrant des sessions live dignes d’un film d’horreur. Le service client est d’une efficacite surnaturelle, avec une aide aussi fluide qu’un spectre. Les gains arrivent a une vitesse demoniaque, cependant des tours gratuits supplementaires feraient frissonner. Au final, Casombie merite une visite dans son antre pour les joueurs en quete de frissons ! De plus le design est sombre et captivant, facilite une experience aussi fluide qu’un spectre.
casombie promo code|
ShadowGlimmerZ3zef
14 Oct 25 at 8:30 am
диплом автотранспортного техникума купить в [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_pzea
14 Oct 25 at 8:31 am
тканевые электрожалюзи [url=zhalyuzi-s-elektroprivodom77.ru]zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_fbpa
14 Oct 25 at 8:32 am
купить диплом в красноярске [url=https://rudik-diplom4.ru]купить диплом в красноярске[/url] .
Diplomi_kwOr
14 Oct 25 at 8:32 am
купить диплом архитектора [url=http://rudik-diplom11.ru/]купить диплом архитектора[/url] .
Diplomi_yjMi
14 Oct 25 at 8:33 am
аренда экскаваторов погрузчиков [url=www.arenda-ekskavatora-pogruzchika-cena-2.ru]аренда экскаваторов погрузчиков[/url] .
arenda ekskavatora pogryzchika cena_mwst
14 Oct 25 at 8:33 am
купить легальный диплом колледжа [url=www.frei-diplom5.ru]купить легальный диплом колледжа[/url] .
Diplomi_cvPa
14 Oct 25 at 8:33 am
согласование перепланировки нежилых помещений [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .
pereplanirovka nejilogo pomesheniya_npSr
14 Oct 25 at 8:33 am
Je suis captive par Casinia Casino, c’est un casino en ligne qui s’eleve comme un chateau medieval. vibre avec un rempart de jeux varies. comprenant des jeux de casino adaptes aux cryptomonnaies. L’assistance du casino est chaleureuse et loyale. resonnant comme une legende parfaite. Le processus du casino est transparent et sans trahison. cependant des bonus de casino plus frequents seraient medievaux. Au final, Casinia Casino c’est un casino a conquerir sans tarder pour les chevaliers du casino! A noter resonne avec une melodie graphique legendaire. ce qui rend chaque session de casino encore plus noble.
casinia no deposit|
shadowwhirllynx2zef
14 Oct 25 at 8:33 am
электрокарнизы москва [url=https://karniz-elektroprivodom.ru]https://karniz-elektroprivodom.ru[/url] .
karniz elektroprivodom shtor kypit_iuei
14 Oct 25 at 8:34 am
continuously i used to read smaller content that also clear their motive, and
that is also happening with this article which I am reading
at this time.
roofing services
14 Oct 25 at 8:34 am
купить диплом о среднем образовании в реестр [url=https://www.frei-diplom4.ru]купить диплом о среднем образовании в реестр[/url] .
Diplomi_ptOl
14 Oct 25 at 8:34 am
куплю диплом с занесением [url=http://rudik-diplom3.ru]куплю диплом с занесением[/url] .
Diplomi_wiei
14 Oct 25 at 8:35 am
мини экскаватор цена за час [url=http://www.arenda-mini-ekskavatora-v-moskve-2.ru]http://www.arenda-mini-ekskavatora-v-moskve-2.ru[/url] .
arenda mini ekskavatora v moskve_gwKt
14 Oct 25 at 8:36 am
В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
ТОП-5 причин узнать больше – https://datsumask.com/wp/?p=69
MatthewRig
14 Oct 25 at 8:36 am
We are a group of volunteers and starting
a new scheme in our community. Your web site offered us with valuable information to work on. You have done a formidable job and our entire community will be thankful to you.
Hobicode
14 Oct 25 at 8:37 am
bestchangeru.com — Надежный Обменник Валют Онлайн
¦ Что такое BestChange?
[url=https://bestchangeru.com/]bestchange com[/url]
bestchangeru.com является одним из наиболее популярных сервисов мониторинга обменников электронных валют в русскоязычном сегменте сети Интернет. Платформа была создана для упрощения процесса выбора надежного онлайн-обмена валюты среди множества предложений.
¦ Основные преимущества BestChange:
https://bestchangeru.com/
обменник криптовалют bestchange
– Мониторинг лучших курсов: Лучшие курсы покупки и продажи криптовалют и электронных денег автоматически обновляются в режиме реального времени.
– Автоматическое сравнение: Удобный интерфейс позволяет мгновенно сравнить десятки предложений и выбрать оптимальное.
– Обзор отзывов пользователей: Пользователи оставляют отзывы и оценки, помогающие другим пользователям принять решение.
– Отсутствие скрытых комиссий: Информация о комиссиях отображается прозрачно и открыто.
¦ Как работает BestChange?
Пользователь вводит необходимые данные: валюту, которую хочет обменять, и желаемую сумму. После этого сервис генерирует список надежных обменных пунктов с лучшими условиями обмена.
Пример: Вы хотите обменять Bitcoin на рубли. Заходите на сайт bestchangeru.com, выбираете направление обмена («Bitcoin > Рубли»), вводите сумму и получаете таблицу проверенных обменных пунктов с наилучшими курсами.
¦ Почему выбирают BestChange?
1. Безопасность. Все обменники проходят строгую проверку перед добавлением в базу сервиса.
2. Удобство пользования. Простота интерфейса позволяет быстро находить нужную информацию даже новичкам.
3. Постоянное обновление базы данных. Курсы и условия регулярно проверяются и обновляются, обеспечивая актуальность информации.
4. Многоязычность. Помимо русского, доступна версия сайта на английском и украинском языках.
Таким образом, bestchangeru.com становится незаменимым помощником в мире цифровых финансов, позволяя легко и безопасно совершать операции обмена валют. Если вам нужен надежный и удобный способ обмена криптовалюты и электронных денег, обязательно обратите внимание на этот ресурс.
RichardFup
14 Oct 25 at 8:37 am
J’aime l’atmosphere unique de Locowin Casino, il procure une odyssee unique. La selection de jeux est spectaculaire, incluant des paris sportifs palpitants. Doublement des depots jusqu’a 200 €. L’equipe de support est remarquable, offrant des reponses claires. Les paiements sont securises et fluides, mais plus de promos regulieres seraient un plus. Au final, Locowin Casino garantit du plaisir a chaque instant pour les passionnes de jeux modernes ! Par ailleurs la navigation est simple et plaisante, amplifie le plaisir de jouer. A souligner les tournois reguliers pour la competition, renforce le sentiment de communaute.
DГ©couvrir plus|
DestinyVoiceH6zef
14 Oct 25 at 8:38 am
купить старый диплом техникума [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_ykea
14 Oct 25 at 8:38 am
автоматические рулонные шторы с электроприводом [url=http://rulonnaya-shtora-s-elektroprivodom.ru]http://rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_qqKt
14 Oct 25 at 8:38 am
купить диплом гознак [url=http://rudik-diplom4.ru]купить диплом гознак[/url] .
Diplomi_ulOr
14 Oct 25 at 8:39 am
here
Danielbaf
14 Oct 25 at 8:39 am
J’apprecie l’atmosphere de Locowin Casino, il delivre une experience unique. Les alternatives sont incroyablement etendues, proposant des jeux de table immersifs. Le bonus d’accueil est attractif. Le service est operationnel 24/7, avec une assistance exacte et veloce. Les paiements sont proteges et lisses, mais plus de promotions frequentes seraient un atout. En synthese, Locowin Casino garantit du divertissement constant pour les joueurs a la recherche d’aventure ! A mentionner la navigation est simple et engageante, ajoute un confort notable. Particulierement attractif les paiements securises en crypto, qui stimule l’engagement.
Découvrir l’avis|
ChaosReelV7zef
14 Oct 25 at 8:40 am