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!
aviator money [url=https://www.aviator-igra-1.ru]https://www.aviator-igra-1.ru[/url] .
aviator igra_whOn
11 Sep 25 at 10:27 am
[url=https://www.zaymer.ru/]АФЕРИСТ[/url]
[url=https://zaimer.kz/]аферисты[/url]
Ronaldfed
11 Sep 25 at 10:28 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Все материалы собраны здесь – https://cartavillaluisa.com/logo
HaroldHex
11 Sep 25 at 10:28 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Более того — здесь – https://www.mayiti.net/214477-2
HectoreXore
11 Sep 25 at 10:28 am
авиатор игра 1хбет [url=https://aviator-igra-5.ru/]авиатор игра 1хбет[/url] .
aviator igra_wcKt
11 Sep 25 at 10:28 am
https://hr.rivagroup.su/
Kellynom
11 Sep 25 at 10:29 am
где играть в авиатор [url=https://aviator-igra-1.ru/]где играть в авиатор[/url] .
aviator igra_iqOn
11 Sep 25 at 10:30 am
Today, I went to the beachfront with my kids. I found a sea shell and gave it
to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to
her ear and screamed. There was a hermit crab inside and it pinched her ear.
She never wants to go back! LoL I know this is completely off topic but
I had to tell someone!
RonexisPro
11 Sep 25 at 10:30 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Посмотреть подробности – https://glenwin.com/lorem-ipsum-dolor-sit-amet
Charlesfeerm
11 Sep 25 at 10:31 am
Do you have any video of that? I’d care to find out more details.
Magda
11 Sep 25 at 10:32 am
Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
Переходите по ссылке ниже – https://dssports.com.hk/product/swim
MiguelDwero
11 Sep 25 at 10:34 am
best online casinos for Blue Diamond
EdwardTix
11 Sep 25 at 10:35 am
1уин [url=www.1win12002.ru]www.1win12002.ru[/url]
1win_tuKa
11 Sep 25 at 10:35 am
Thanks for ones marvelous posting! I quite enjoyed reading
it, you might be a great author.I will make certain to bookmark your blog and will often come back in the future.
I want to encourage yourself to continue your great work, have a nice morning!
Norris
11 Sep 25 at 10:35 am
plane game money [url=https://aviator-igra-5.ru/]aviator-igra-5.ru[/url] .
aviator igra_bbKt
11 Sep 25 at 10:36 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Обратиться к источнику – https://www.vastavkatta.com/index.php/2022/11/26/opting-out
Charlesfeerm
11 Sep 25 at 10:36 am
They wish to know if you can construct buy-in for your ideas and lead with out formal authority.
My web-site; How do SPA pools enhance wellness experiences?
How do SPA pools enhance wellness experiences?
11 Sep 25 at 10:36 am
Списался с продавцом в аське, во вторник оплатил, сказали в среду отправят. когда спросил, сказали что не отправили по тех причинам из-за СПСР, обещали в четверг. Должно было придти в течении 3х рабочих дней. Сегодня понедельник, сижу на работе, и вот мне звонят, мол вам письмо пришло, куда доставить? То есть все верно, 3 дня как и говорили! Настроение теперь на весь день поднялось)) Вечером буду делать 1к10 (ам2233), потом отпишусь как и чего!!)) В общем доволен, но пока говорю только про доставку. Позднее отпишу доволен ли я всем остальным))
https://wirtube.de/a/barbaraadkinson5135/video-channels
и Антошке пару точек,
RogerCer
11 Sep 25 at 10:36 am
клиенты знают нас и нашу работу [url=http://www.soglasovanie-pereplanirovki-kvartiry17.ru]http://www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _wxol
11 Sep 25 at 10:43 am
как зарегистрироваться в мостбет [url=mostbet12001.ru]как зарегистрироваться в мостбет[/url]
mostbet_vsOr
11 Sep 25 at 10:45 am
dark web market links nexus site official link nexus darknet market url [url=https://darkmarketsgate.com/ ]darkmarket url [/url]
Jamespem
11 Sep 25 at 10:46 am
darknet market list darknet drug market dark web market links [url=https://darkmarketlegion.com/ ]dark websites [/url]
Robertalima
11 Sep 25 at 10:46 am
plane game money [url=http://www.aviator-igra-5.ru]http://www.aviator-igra-5.ru[/url] .
aviator igra_tjKt
11 Sep 25 at 10:46 am
aviator играть [url=https://aviator-igra-1.ru]aviator играть[/url] .
aviator igra_fhOn
11 Sep 25 at 10:48 am
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry17.ru]перепланировка офиса[/url] .
soglasovanie pereplanirovki kvartiri _cfol
11 Sep 25 at 10:49 am
авиатор игра на деньги скачать [url=http://www.aviator-igra-5.ru]авиатор игра на деньги скачать[/url] .
aviator igra_ejKt
11 Sep 25 at 10:50 am
купить старый диплом техникума киев [url=educ-ua18.ru]купить старый диплом техникума киев[/url] .
Diplomi_rlPi
11 Sep 25 at 10:51 am
Nice post. I was checking continuously this blog and I am inspired!
Very helpful info particularly the remaining part 🙂 I maintain such info a lot.
I was looking for this particular info for a very lengthy time.
Thanks and best of luck.
Nordic Future AI
11 Sep 25 at 10:52 am
https://www.blogger.com/blog/post/edit/6581382424267429617/385988830035460371?hl=ru
MichaelTot
11 Sep 25 at 10:54 am
I used to be recommended this website by my cousin. I’m no longer sure whether this submit is written by him as nobody else know
such unique approximately my trouble. You are wonderful!
Thanks!
best personal injury attorneys
11 Sep 25 at 10:55 am
помощь в согласовании перепланировки квартиры [url=soglasovanie-pereplanirovki-kvartiry17.ru]soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _zxol
11 Sep 25 at 10:57 am
Everything is very open with a clear explanation of the issues.
It was definitely informative. Your website is
useful. Many thanks for sharing!
best crypto casinos poland
11 Sep 25 at 10:57 am
We are a group of volunteers and starting a new scheme in our community.
Your website offered us with valuable info to work on. You have done an impressive job
and our whole community will be grateful to you.
site
11 Sep 25 at 11:00 am
магазин ровнеый,за что им спасибо,если сами тупить не будете всё пройдёт ровно и без проблем.Товар тоже порадовал,довольно таки неплохо))
https://ilm.iou.edu.gm/members/brombloodfire835/
Запулил:$: ждёмс… отпишу…. Селер адекватный:voo-hoo:
RogerCer
11 Sep 25 at 11:00 am
https://fruitsfromchile.com/news/1xbet_promo_code___welcome_bonus_code.html
Harveyham
11 Sep 25 at 11:01 am
Very shortly this web page will be famous among all blogging
users, due to it’s fastidious articles
Teguh777
11 Sep 25 at 11:01 am
Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I get in fact enjoyed account your blog posts.
Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.
Stop by my web blog … stem cell therapy for hair loss thailand
stem cell therapy for hair loss thailand
11 Sep 25 at 11:05 am
aviator играть на деньги [url=https://aviator-igra-1.ru/]https://aviator-igra-1.ru/[/url] .
aviator igra_ctOn
11 Sep 25 at 11:05 am
Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
Следуйте по ссылке – https://www.bultepop.nl/2013/03/02/bultepop-2013-op-zaterdag-28-september-2013
SamuelGef
11 Sep 25 at 11:07 am
перепланировка согласование [url=soglasovanie-pereplanirovki-kvartiry17.ru]перепланировка согласование[/url] .
soglasovanie pereplanirovki kvartiri _hool
11 Sep 25 at 11:09 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Детальнее – https://tylerthecreatormerchofficial.com/lembaga-pengelola-dana-pendidikan-mewujudkan-akses-dan-kualitas-pendidikan-yang-lebih-baik
SamuelGef
11 Sep 25 at 11:09 am
Aw, this was an incredibly nice post. Spending some time and actual effort to generate a really
good article… but what can I say… I hesitate a lot and don’t seem to get anything done.
야동 무료 홍보
11 Sep 25 at 11:10 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Доступ к полной версии – https://lvan.in/product/faith-over-fear-with-back-design
Carlosthive
11 Sep 25 at 11:10 am
онлайн игра авиатор [url=http://aviator-igra-1.ru/]онлайн игра авиатор[/url] .
aviator igra_dtOn
11 Sep 25 at 11:11 am
авиатор игра онлайн [url=http://aviator-igra-5.ru/]авиатор игра онлайн[/url] .
aviator igra_hiKt
11 Sep 25 at 11:12 am
Howdy very cool blog!! Guy .. Beautiful .. Superb ..
I will bookmark your blog and take the feeds additionally?
I’m glad to seek out so many helpful information here in the put up, we want develop extra techniques on this regard, thank you for sharing.
. . . . .
escorte paris
11 Sep 25 at 11:13 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Перейти к статье – https://smartiptv-tv.com/iptv-le-futur-de-la-tv
DonaldVab
11 Sep 25 at 11:14 am
1win crash [url=https://aviator-igra-1.ru/]aviator-igra-1.ru[/url] .
aviator igra_zuOn
11 Sep 25 at 11:14 am
Howdy! Do you use Twitter? I’d like to follow you if that would be
ok. I’m absolutely enjoying your blog and look forward to new posts.
Here is my site: Sportsbooks
Sportsbooks
11 Sep 25 at 11:16 am
confidential delivery pharmacy UK [url=https://mediquickuk.shop/#]order medicines online discreetly[/url] trusted UK digital pharmacy
Albertmoone
11 Sep 25 at 11:17 am