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!
Hi Sjoerd,
Looks good, nice way to use the SPL libraries.
Cheers
RobT
24 May 11 at 7:47 am
Oh yeah, I built a similar example without a real observer pattern which looks more like the evenlistener setup using in languages like Flex
have a look at :
http://sourcerer.nl/eventhandlers.phps
RobT
24 May 11 at 9:26 am
Thx @RobT, your eventlistener example does indeed resembles a lot the way it works in Flex. Thx for contributing.
Sjoerd Maessen
24 May 11 at 9:45 am
SEO agencies in Mesa
PHP hook, building hooks in your application at Sjoerd Maessen blog
SEO agencies in Mesa
23 Mar 17 at 8:29 am
porcelain veneers In West Los Angeles
PHP hook, building hooks in your application at Sjoerd Maessen blog
porcelain veneers In West Los Angeles
15 May 17 at 9:34 am
Усильте позиции сайта быстро
и эффективно!
Закажите прогон Хрумером и ГСА по супернизкой цене — гарантия роста трафика и
улучшения SEO-показателей вашего ресурса.
Только проверенные базы и индивидуальный подход к каждому проекту.
Увеличьте посещаемость и прибыль прямо сейчас!
больще ифрЗДЕСЬ
web site
16 Jul 25 at 9:22 am
Мы предлагаем оформление дипломов ВУЗов В киеве — с печатями, подписями, приложением и возможностью архивной записи (по запросу).
Документ максимально приближен к оригиналу и проходит визуальную проверку.
Мы даем гарантию, что в случае проверки документа, подозрений не возникнет.
– Конфиденциально
– Доставка 3–7 дней
– Любая специальность
Уже более 925 клиентов воспользовались услугой — теперь ваша очередь.
[url=http://diplomykupit7.ru/]Купить диплом о высшем образовании недорого[/url] — ответим быстро, без лишних формальностей.
Patrickbadly
16 Jul 25 at 9:26 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Практические советы ждут тебя – https://axelzamudio.com/podcast/episode/como-se-vive-el-cancer-de-mama
AlvinBop
16 Jul 25 at 9:27 am
аттестат за 11 класс 2003 купить [url=www.arus-diplom25.ru]аттестат за 11 класс 2003 купить[/url] .
Diplomi_jrot
16 Jul 25 at 9:27 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Ссылка на источник – https://oishimadison.com/the-art-of-sushi-a-journey-to-deliciousness
JohnnyFainy
16 Jul 25 at 9:30 am
скачать мелбет на ios [url=www.melbet3002.com]www.melbet3002.com[/url]
melbet_gfOl
16 Jul 25 at 9:35 am
Эта статья предлагает живое освещение актуальной темы с множеством интересных фактов. Мы рассмотрим ключевые моменты, которые делают данную тему важной и актуальной. Подготовьтесь к насыщенному путешествию по неизвестным аспектам и узнайте больше о значимых событиях.
Нажми и узнай всё – https://www.konferenciadobrehozivota.sk/hello-world
Edwardenupe
16 Jul 25 at 9:39 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Переходите по ссылке ниже – https://robertsdaily.com/%F0%9F%8E%93-how-to-do-self-placement-for-bece-candidates-in-bece-2025-guide
Martinnus
16 Jul 25 at 9:43 am
download 1win [url=1win3047.com]download 1win[/url]
1win_rdMa
16 Jul 25 at 9:48 am
мелбет казино скачать [url=melbet3002.com]melbet3002.com[/url]
melbet_tqOl
16 Jul 25 at 9:49 am
Оформиление дипломов ВУЗов по всей Украине — с печатями, подписями, приложением и возможностью архивной записи (по запросу).
Документ максимально приближен к оригиналу и проходит визуальную проверку.
Мы даем гарантию, что в случае проверки документа, подозрений не возникнет.
– Конфиденциально
– Доставка 3–7 дней
– Любая специальность
Уже более 1608 клиентов воспользовались услугой — теперь ваша очередь.
[url=http://diplomykupit6.ru/]Купить диплом о высшем образовании Украины[/url] — ответим быстро, без лишних формальностей.
Kennethfiz
16 Jul 25 at 9:52 am
Эта статья предлагает живое освещение актуальной темы с множеством интересных фактов. Мы рассмотрим ключевые моменты, которые делают данную тему важной и актуальной. Подготовьтесь к насыщенному путешествию по неизвестным аспектам и узнайте больше о значимых событиях.
Более того — здесь – https://casino777gaminator.ru
MatthewSathe
16 Jul 25 at 9:53 am
провайдеры по адресу дома
[url=https://domashij-internet-krasnodar006.ru]domashij-internet-krasnodar006.ru[/url]
интернет провайдеры по адресу
inernetkrdelini
16 Jul 25 at 10:06 am
Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
Обратитесь за информацией – http://mosaic-platform.com/uncategorized/hello-world
Donaldodome
16 Jul 25 at 10:08 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Получить полную информацию – https://closeup.nl/tesla-to-hopefully-launch-the-model-3-in-india-this-summer-elon-musk-2
ScottOvene
16 Jul 25 at 10:08 am
Saved as a favorite, I really like your blog!
تعمير داکت اسپليت ال جي
16 Jul 25 at 10:20 am
My brother suggested I may like this website. He was once totally right.
This put up actually made my day. You can not consider simply how a
lot time I had spent for this info! Thanks!
Click This Link
16 Jul 25 at 10:23 am
купить аттестат за 11 класс в ростове на дону [url=https://www.arus-diplom23.ru]купить аттестат за 11 класс в ростове на дону[/url] .
Diplomi_ptol
16 Jul 25 at 10:30 am
A motivating discussion is definitely worth comment.
I believe that you need to publish more about this issue, it might not be a taboo matter but
generally folks don’t discuss these subjects. To the next!
Kind regards!!
Как ИИ помогает сохранять здоровье: топ-применений
16 Jul 25 at 10:35 am
трансформатор тмг [url=https://maslyanie-transformatory-kupit1.ru/]https://maslyanie-transformatory-kupit1.ru/[/url] .
maslyanie transformatori kypit_ywMn
16 Jul 25 at 10:36 am
трансформаторы тмг [url=https://maslyanie-transformatory-kupit1.ru]https://maslyanie-transformatory-kupit1.ru[/url] .
maslyanie transformatori kypit_stMn
16 Jul 25 at 10:37 am
промокод на мелбет при регистрации [url=https://www.melbet3001.com]https://www.melbet3001.com[/url]
melbet_krkn
16 Jul 25 at 10:38 am
Medicament information leaflet. Effects of Drug Abuse.
where can i buy cheap ropinirole tablets
All news about medicine. Get information here.
where can i buy cheap ropinirole tablets
16 Jul 25 at 10:38 am
Whoa! This blog looks exactly like my old one! It’s on a entirely different topic but it has
pretty much the same page layout and design. Great choice
of colors!
purchase instantly for delivery
16 Jul 25 at 10:38 am
Thanks very interesting blog!
تعمیرات مایکروفر پاناسونیک
16 Jul 25 at 10:43 am
сколько стоит сваи под фундамент цена [url=https://www.ostankino-svai.ru ]https://www.ostankino-svai.ru [/url] .
vintovie svai_srpr
16 Jul 25 at 10:44 am
1win az [url=https://www.1win3043.com]1win az[/url]
1win_tcEt
16 Jul 25 at 10:44 am
Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
Только для своих – https://dabbau.com/fakro
ScottPaw
16 Jul 25 at 10:45 am
[url=https://dtcc.edu.vn/]кракен даркнет маркет[/url]
RichardPep
16 Jul 25 at 10:46 am
где купить аттестаты за 11 класс в нижнем тагиле [url=https://arus-diplom23.ru]где купить аттестаты за 11 класс в нижнем тагиле[/url] .
Diplomi_aool
16 Jul 25 at 10:46 am
como usar el bono de casino en 1win [url=http://1win3046.com]como usar el bono de casino en 1win[/url]
1win_bfEn
16 Jul 25 at 10:49 am
трансформатор тм [url=http://maslyanie-transformatory-kupit1.ru/]http://maslyanie-transformatory-kupit1.ru/[/url] .
maslyanie transformatori kypit_ggMn
16 Jul 25 at 10:53 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Доступ к полной версии – https://servitrafick.es/producto/pagina-web-y-app-con-sistema-de-pedidos-y-delivery-para-restaurantes-fluido-y-facil-de-usar
Martinnus
16 Jul 25 at 10:55 am
강남토닥이 isn’t just a
massage shop—it’s a true healing space. The title
of women-only massage fits it perfectly.
강남여성전용마사지
16 Jul 25 at 10:55 am
Your mode of describing everything in this piece of writing is
really pleasant, every one can without difficulty understand it, Thanks a
lot.
بورس کولر گازی در تهران
16 Jul 25 at 10:56 am
get generic lisinopril online
lisinopril 40 mg pill identifier
16 Jul 25 at 10:57 am
Если ищете, где можно смотреть UFC в прямом эфире, то этот сайт отлично подойдёт. Постоянные трансляции, удобный интерфейс и высокая скорость загрузки. Всё работает стабильно и без рекламы: https://mma-fan.ru/
GarrySwicy
16 Jul 25 at 11:06 am
аттестаты за 11 класс купить [url=http://www.arus-diplom23.ru]аттестаты за 11 класс купить[/url] .
Diplomi_fjol
16 Jul 25 at 11:08 am
The other day, while I was at work, my sister stole my iphone and tested to
see if it can survive a 25 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views.
I know this is entirely off topic but I had to share it with someone!
بازار عمده تجهیزات پزشکی تهران
16 Jul 25 at 11:12 am
вывод из запоя круглосуточно
narkolog-krasnodar003.ru
лечение запоя
narkologiyakrasnodarNeT
16 Jul 25 at 11:12 am
купить аттестат за 11 классов в владивостоке [url=arus-diplom25.ru]arus-diplom25.ru[/url] .
Diplomi_nhot
16 Jul 25 at 11:17 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Практические советы ждут тебя – https://www.editions-ric.fr/2019/05/10/cagnes-sur-mer-salon-du-livre-2019-reportage-rvpb
Patricklix
16 Jul 25 at 11:19 am
В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
Узнай первым! – https://495-9220683.ru
MatthewSathe
16 Jul 25 at 11:22 am
провайдеры интернета в краснодаре по адресу проверить
[url=https://domashij-internet-krasnodar006.ru]domashij-internet-krasnodar006.ru[/url]
интернет провайдеры по адресу краснодар
inernetkrdelini
16 Jul 25 at 11:24 am
купить аттестаты за 11 класс отзывы цена [url=http://www.arus-diplom9.ru]купить аттестаты за 11 класс отзывы цена[/url] .
Kypit diplom lubogo instityta!_htPt
16 Jul 25 at 11:25 am