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!
Nice blog here! Also your site loads up very fast!
What host are you using? Can I get your affiliate link to your host?
I wish my web site loaded up as fast as yours lol
2018 Elections and Updates Edition Greenberg PDF
19 Sep 25 at 6:09 pm
http://evertrustmeds.com/# Generic Tadalafil 20mg price
RichardceaNy
19 Sep 25 at 6:10 pm
микро займы онлайн [url=https://zaimy-16.ru/]микро займы онлайн[/url] .
zaimi_boMi
19 Sep 25 at 6:10 pm
https://form.jotform.com/252575033476056
HarryPaync
19 Sep 25 at 6:10 pm
купить диплом в владивостоке [url=www.rudik-diplom1.ru/]купить диплом в владивостоке[/url] .
Diplomi_oyer
19 Sep 25 at 6:10 pm
Получить диплом о высшем образовании мы поможем. Купить диплом университета – [url=http://diplomybox.com/diplom-universiteta/]diplomybox.com/diplom-universiteta[/url]
Cazrfhs
19 Sep 25 at 6:11 pm
все займы рф [url=www.zaimy-16.ru]www.zaimy-16.ru[/url] .
zaimi_xpMi
19 Sep 25 at 6:14 pm
ed prescriptions online [url=https://vitaledgepharma.shop/#]VitalEdge Pharma[/url] VitalEdgePharma
Michealstilm
19 Sep 25 at 6:14 pm
купить диплом в туймазы [url=http://rudik-diplom7.ru]купить диплом в туймазы[/url] .
Diplomi_wnPl
19 Sep 25 at 6:14 pm
купить диплом в гатчине [url=rudik-diplom11.ru]rudik-diplom11.ru[/url] .
Diplomi_eiMi
19 Sep 25 at 6:15 pm
микрозайм все [url=http://www.zaimy-16.ru]http://www.zaimy-16.ru[/url] .
zaimi_ayMi
19 Sep 25 at 6:15 pm
На данном этапе врач уточняет, сколько времени продолжается запой, какой тип алкоголя употребляется и имеются ли сопутствующие заболевания. Тщательный анализ этих данных позволяет подобрать оптимальные методы детоксикации и снизить риск осложнений.
Узнать больше – http://narcolog-na-dom-mariupol0.ru
Romanuteda
19 Sep 25 at 6:17 pm
I will right away grasp your rss feed as I can not find your
e-mail subscription link or e-newsletter service. Do you’ve any?
Please let me understand so that I could subscribe.
Thanks.
link GACORSLOT138
19 Sep 25 at 6:18 pm
I’ve been surfing online more than 4 hours today, yet I never found any interesting article like yours.
It’s pretty worth enough for me. In my view, if all webmasters and bloggers made
good content as you did, the web will be much more useful than ever before.
비아그라 구입
19 Sep 25 at 6:18 pm
займы россии [url=www.zaimy-16.ru/]www.zaimy-16.ru/[/url] .
zaimi_aqMi
19 Sep 25 at 6:19 pm
бот для накрутки подписчиков в телеграм бесплатно
JerryBealo
19 Sep 25 at 6:21 pm
Ever Trust Meds: Generic Cialis without a doctor prescription – EverTrustMeds
DerekStops
19 Sep 25 at 6:21 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 6:22 pm
Заказать диплом о высшем образовании мы поможем. Купить аттестат Калуга – [url=http://diplomybox.com/kupit-attestat-v-kaluge/]diplomybox.com/kupit-attestat-v-kaluge[/url]
Cazrsbe
19 Sep 25 at 6:24 pm
купить диплом в симферополе [url=rudik-diplom1.ru]rudik-diplom1.ru[/url] .
Diplomi_lger
19 Sep 25 at 6:24 pm
все займы рф [url=http://zaimy-16.ru/]http://zaimy-16.ru/[/url] .
zaimi_heMi
19 Sep 25 at 6:25 pm
В проектах благоустройства города всё чаще используют [url=https://баннер-москва.рф/bannery-moya-ulitsa]баннеры моя улица[/url]. Они создают единую стилистику, делают улицы более яркими и привлекательными. Современная печать позволяет реализовать любые дизайнерские идеи: от простых узоров до сложных графических композиций. Это тренд городского оформления, который становится визитной карточкой Москвы.
Benrtima
19 Sep 25 at 6:25 pm
займы [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_vwMi
19 Sep 25 at 6:25 pm
Футболки надписи для мужчин и футболки ржд в Махачкале. Домашние брюки для женщин хлопок и рубашка детская в Ижевске. Футболки рисунки и надписи и принт футболки на заказ в Москве в Курске. Фирма с акулой одежда и одежда гто в Оренбурге. Футболка оптом фиолетовый принт и сделать футболку на заказ в Москве: футболка choppers из форсажа 2 оптом
Gregorysnisp
19 Sep 25 at 6:27 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 6:27 pm
This paragraph will assist the internet viewers for setting up new blog or even a blog from start to end.
درمان آنفولانزا ریه
19 Sep 25 at 6:28 pm
Hello friends, its wonderful piece of writing concerning cultureand fully explained, keep it up all the time.
cybersecurity
19 Sep 25 at 6:28 pm
This post will assist the internet people for setting up
new webpage or even a blog from start to
end.
Paito SGP
19 Sep 25 at 6:30 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 6:30 pm
2025: Откройте для Себя Неизвестные Шедевры!
Гид по Уникальным Кинолентам
Года!
фильмы 2025 смотреть в хорошем качестве
19 Sep 25 at 6:31 pm
всезаймыонлайн [url=https://zaimy-16.ru]https://zaimy-16.ru[/url] .
zaimi_mqMi
19 Sep 25 at 6:35 pm
диплом колледжа купить в москве [url=http://www.frei-diplom9.ru]http://www.frei-diplom9.ru[/url] .
Diplomi_tcea
19 Sep 25 at 6:36 pm
https://linkin.bio/pnxybcqxaj950
HarryPaync
19 Sep 25 at 6:36 pm
всезаймыонлайн [url=https://zaimy-16.ru]https://zaimy-16.ru[/url] .
zaimi_hqMi
19 Sep 25 at 6:37 pm
купить проведенный диплом спб [url=http://www.frei-diplom4.ru]http://www.frei-diplom4.ru[/url] .
Diplomi_noOl
19 Sep 25 at 6:37 pm
https://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 6:37 pm
купить диплом с занесением в реестр украина [url=http://www.frei-diplom5.ru]http://www.frei-diplom5.ru[/url] .
Diplomi_amPa
19 Sep 25 at 6:38 pm
диплом купить с проведением [url=www.frei-diplom3.ru]диплом купить с проведением[/url] .
Diplomi_fuKt
19 Sep 25 at 6:40 pm
как купить диплом с реестром [url=https://frei-diplom6.ru/]как купить диплом с реестром[/url] .
Diplomi_ezOl
19 Sep 25 at 6:41 pm
What’s up, I would like to subscribe for this weblog to get latest updates, therefore where
can i do it please assist.
آمبولانس خصوصی پیشوا
19 Sep 25 at 6:41 pm
После диагностики начинается активная фаза медикаментозного вмешательства. Современные препараты вводятся капельничным методом, что позволяет быстро снизить уровень токсинов в крови, восстановить нормальные обменные процессы и стабилизировать работу жизненно важных органов, таких как печень, почки и сердце.
Детальнее – [url=https://vyvod-iz-zapoya-murmansk0.ru/]вывод из запоя на дому в мурманске[/url]
AlfredDierb
19 Sep 25 at 6:41 pm
все займы [url=http://zaimy-16.ru]все займы[/url] .
zaimi_bhMi
19 Sep 25 at 6:42 pm
займы все онлайн [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_dzMi
19 Sep 25 at 6:42 pm
все займы ру [url=https://www.zaimy-16.ru]https://www.zaimy-16.ru[/url] .
zaimi_beMi
19 Sep 25 at 6:48 pm
все займы на карту [url=zaimy-16.ru]все займы на карту[/url] .
zaimi_prMi
19 Sep 25 at 6:49 pm
Wow, wonderful weblog structure! How long have you been running a blog for?
you make blogging glance easy. The overall look of your web site is
excellent, as neatly as the content!
برونشیت ریه خطرناک است
19 Sep 25 at 6:50 pm
If you’re searching for a trustworthy and powerful financial service
that handles not only cryptocurrency transactions like buying Bitcoin but also supports a wide range of fiat
operations, then you should definitely check out this discussion where users share their feedback
about a truly all-in-one crypto-financial platform.
The recommendation shared by users in the discussion made it clear that this platform
is more than just a simple exchange – it’s
a full-fledged financial ecosystem for both individuals and companies.
Whether you’re running a startup or managing
finances for a multinational corporation, the features highlighted
in this discussion could be a game-changer – multi-user accounts, compliance tools, fiat
gateways, and crypto custody all in one.
This topic could be particularly useful for anyone seeking a compliant, scalable,
and secure solution for managing both crypto and fiat funds.
The website being discussed is built to handle everything from simple BTC purchases to large-scale B2B transactions.
It’s a long read, but this forum topic offers some of the
most detailed opinions on using crypto platforms
for corporate and fiat operations alike. Definitely worth digging into this website.
topic
19 Sep 25 at 6:50 pm
Рекламные конструкции остаются одним из самых эффективных инструментов PR. Среди них лидирует [url=https://format-ms.ru/catalog/press-voll/]изготовление press wall[/url] ведь такой мобильный стенд сочетает эргономичность и выразительность. Он помогает привлечь внимание на презентации, в салоне или на конференции. Роллап создан для логистики, собирается без усилий и даёт мгновенный эффект на продвижение.
Компания Format-MS уже давно занимается разработкой и подготовкой роллапов. В студии используют сертифицированные материалы, современные печатные технологии и делают картинку максимально реалистичной. Клиенты ценят быстрое изготовление заказов, чистое исполнение и учёт всех требований. Адрес офиса: Москва, Нагорный проезд, дом 7, стр 1, офис 2320. Для уточнения деталей всегда доступен телефон +7 (499) 390-19-85. На сайте format-ms.ru можно изучить выполненные работы и запросить просчёт.
Если вам требуется [url=https://format-ms.ru/]стойки для рекламы[/url] специалисты изготовят варианты с увеличенной прочностью к осадкам и осадкам. Специальные ткани, устойчивые системы и ламинат делают такие изделия выдерживающими нагрузки даже при мобильных мероприятиях. Это продукт станет эффективной рекламной опорой, который работает на ваш бизнес каждый день и остается ярким.
Formaticam
19 Sep 25 at 6:51 pm
Применение автоматизированных систем дозирования гарантирует точное введение медикаментов, что минимизирует риск передозировки и побочных эффектов. Постоянный мониторинг жизненно важных показателей даёт врачу возможность оперативно корректировать терапевтическую схему, обеспечивая максимальную безопасность процедуры.
Подробнее тут – [url=https://vyvod-iz-zapoya-donetsk-dnr00.ru/]нарколог вывод из запоя[/url]
Michaelduxuh
19 Sep 25 at 6:51 pm
купить диплом в белогорске [url=www.rudik-diplom1.ru]www.rudik-diplom1.ru[/url] .
Diplomi_cxer
19 Sep 25 at 6:52 pm