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!
I’ve been exploring for a little bit for any high-quality articles or blog posts
on this sort of house . Exploring in Yahoo I eventually stumbled upon this website.
Reading this information So i am satisfied to convey that I have an incredibly excellent uncanny feeling I found out exactly what I needed.
I so much surely will make certain to don?t forget
this website and provides it a look on a continuing basis.
Xổ số dt68
17 Aug 25 at 9:27 pm
Hello there, You have done an incredible job. I’ll certainly digg it and personally suggest
to my friends. I am sure they’ll be benefited from this web
site.
займ
17 Aug 25 at 9:28 pm
Please let me know if you’re looking for a author for your site.
You have some really good posts and I believe I would be a
good asset. If you ever want to take some of the load off,
I’d absolutely love to write some articles for your
blog in exchange for a link back to mine. Please
shoot me an e-mail if interested. Cheers!
Pink salt trick for weight loss
17 Aug 25 at 9:31 pm
Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.
Stephenwak
17 Aug 25 at 9:32 pm
Excellent pieces. Keep writing such kind of information on your site.
Im really impressed by your blog.
Hi there, You’ve performed a great job. I’ll
certainly digg it and individually suggest to
my friends. I’m sure they will be benefited from this site.
KL99
17 Aug 25 at 9:35 pm
Миссия клиники “Перезагрузка” заключается в предоставлении высококвалифицированной помощи людям, страдающим от зависимостей. Мы стремимся создать безопасное пространство для лечения, где каждый пациент сможет получить поддержку и понимание. Наша цель — не просто избавление от зависимости, а восстановление полной жизнедеятельности человека.
Ознакомиться с деталями – [url=https://zavisim-alko.ru/]наркологический вывод из запоя[/url]
PeterNable
17 Aug 25 at 9:42 pm
Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.
Stephenwak
17 Aug 25 at 9:44 pm
I do not even understand how I ended up right here, however I assumed this post was
great. I don’t understand who you might be however certainly you’re
going to a well-known blogger for those who are not already.
Cheers!
رتبه یک کنکور تجربی ۱۴۰۴
17 Aug 25 at 9:45 pm
SildenaPeak: SildenaPeak – where to buy viagra in india
PeterTEEFS
17 Aug 25 at 9:46 pm
mostbet aplikace [url=https://mostbet11068.ru/]mostbet aplikace[/url]
mostbet_ohpn
17 Aug 25 at 9:46 pm
most bet [url=http://mostbet11075.ru/]http://mostbet11075.ru/[/url]
mostbet_kg_esei
17 Aug 25 at 9:46 pm
кашпо для цветов с автополивом [url=https://www.kashpo-s-avtopolivom-kazan.ru]кашпо для цветов с автополивом[/url] .
gorshok s avtopolivom_nymr
17 Aug 25 at 9:47 pm
Imitation timber is successfully emergate.net used in construction and finishing due to its unique properties and appearance, which resembles real timber.
Chrisprabe
17 Aug 25 at 9:48 pm
Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.
Stephenwak
17 Aug 25 at 9:50 pm
Woah! I’m really loving the template/theme
of this website. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between usability and appearance.
I must say that you’ve done a very good job with this.
In addition, the blog loads very fast for me on Opera.
Outstanding Blog!
four wheel barrow
17 Aug 25 at 9:55 pm
Hey just wanted to give you a quick heads up. The words in your post seem to
be running off the screen in Ie. I’m not sure if this
is a formatting issue or something to do with
browser compatibility but I thought I’d post to let
you know. The style and design look great though! Hope you get the problem resolved soon. Cheers
togel
17 Aug 25 at 10:01 pm
Hello there! This is my first visit to your blog!
We are a collection of volunteers and starting a new initiative in a community in the
same niche. Your blog provided us useful information to work on. You have done a outstanding job!
8kbetedu.com
17 Aug 25 at 10:07 pm
This piece of writing will assist the internet visitors for setting up new web site or even a
blog from start to end.
goaqjrj.shop
17 Aug 25 at 10:08 pm
Medicament prescribing information. Brand names.
pioglitazone generics
Everything information about medicine. Read information now.
pioglitazone generics
17 Aug 25 at 10:08 pm
мосбет [url=https://mostbet11071.ru/]https://mostbet11071.ru/[/url]
mostbet_srKr
17 Aug 25 at 10:08 pm
Каждый врач клиники обладает глубокими знаниями в области фармакологии, психофармакологии и психотерапии, посещает профессиональные конференции и семинары, следит за достижениями в области лечения зависимостей. Такой подход позволяет применять наиболее эффективные и современные методы.
Ознакомиться с деталями – [url=https://tajno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-kruglosutochno-v-rostove-na-donu.ru/]наркологический вывод из запоя в ростове-на-дону[/url]
ParisCappy
17 Aug 25 at 10:12 pm
мостбет оригинал скачать [url=mostbet11073.ru]mostbet11073.ru[/url]
mostbet_kg_jxSl
17 Aug 25 at 10:13 pm
mostbet скачать [url=www.mostbet11068.ru]www.mostbet11068.ru[/url]
mostbet_vipn
17 Aug 25 at 10:14 pm
Наркологическая клиника “Маяк надежды” — специализированное медицинское учреждение, предназначенное для оказания помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и вернуть их к здоровой и полноценной жизни.
Подробнее можно узнать тут – https://алко-лечение24.рф/vivod-iz-zapoya-v-stacionare-v-Sankt-Peterburge
JasonLoorm
17 Aug 25 at 10:15 pm
Образовательные программы: Мы уверены, что знания о зависимости и её последствиях играют важную роль в реабилитации. Мы информируем пациентов о механизмах действия наркотиков и алкоголя на организм, что способствует изменению их отношения к терапии и жизни без зависимостей.
Углубиться в тему – [url=https://srochnyj-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-stacionare-v-kazani.ru/]вывод из запоя на дому цена в казани[/url]
Richardfowly
17 Aug 25 at 10:16 pm
Заказать диплом о высшем образовании!
Мы изготавливаем дипломы любых профессий по приятным ценам— [url=http://diplomoz-197.com/]diplomoz-197.com[/url]
Lazrwhl
17 Aug 25 at 10:19 pm
It’s truly very complicated in this active life to listen news on Television, therefore I only use internet for that reason, and obtain the most up-to-date news.
kill
17 Aug 25 at 10:19 pm
Запой представляет собой непрерывное бесконтрольное употребление алкоголя в течение нескольких дней и более, при котором человек теряет способность остановиться самостоятельно. Это состояние сопровождается не только абстинентным синдромом, но и риском развития:
Подробнее – [url=https://nadezhnyj-vyvod-iz-zapoya.ru/]вывод из запоя на дому санкт-петербруг[/url]
MichaelMes
17 Aug 25 at 10:21 pm
Для максимальной эффективности и безопасности «Красмед» использует комбинированные подходы:
Получить больше информации – [url=https://medicinskij-vyvod-iz-zapoya.ru/]вывод из запоя цена в красноярске[/url]
RobertExevy
17 Aug 25 at 10:27 pm
Купить диплом ВУЗа!
Мы изготавливаем дипломы любой профессии по выгодным тарифам— [url=http://study-lingvo.ru/]study-lingvo.ru[/url]
Lazridp
17 Aug 25 at 10:28 pm
аттестат 10 11 класс с реестром купить [url=http://www.arus-diplom21.ru]аттестат 10 11 класс с реестром купить[/url] .
Bistro i prosto kypit diplom o visshem obrazovanii!_flpn
17 Aug 25 at 10:29 pm
Lucknow Game: Immerse yourself in the cultural heritage of Lucknow, solving puzzles and exploring iconic landmarks to uncover hidden treasures: best games based on Lucknow culture
HenryBlump
17 Aug 25 at 10:32 pm
Greetings I am so excited I found your web site, I really found you by accident, while I was looking on Google for something else, Anyhow I am here now and would
just like to say many thanks for a fantastic post and a all round enjoyable blog (I also love the theme/design),
I don’t have time to read through it all at the minute but I have book-marked it
and also included your RSS feeds, so when I have time I will
be back to read more, Please do keep up the superb b.
login alternatif
17 Aug 25 at 10:36 pm
Hi there! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your blog posts.
Can you suggest any other blogs/websites/forums that deal with the same topics?
Thanks a lot!
abc investissement
17 Aug 25 at 10:37 pm
Если требуется экстренная помощь при алкогольном кризисе — Narcology Clinic Москва предоставляет срочную помощь на дому: выезд нарколога, купирование симптомов, мониторинг состояния, без очередей и задержек.
Исследовать вопрос подробнее – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]экстренная наркологическая помощь москва[/url]
Robertkix
17 Aug 25 at 10:42 pm
Excellent post however I was wanting to know if you could write a litte more on this
subject? I’d be very grateful if you could elaborate
a little bit more. Appreciate it!
plumbers
17 Aug 25 at 10:43 pm
Посетите сайт https://cs2case.io/ и вы сможете найти кейсы КС (КС2) в огромном разнообразии, в том числе и бесплатные! Самый большой выбор кейсов кс го у нас на сайте. Посмотрите – вы обязательно найдете для себя шикарные варианты, а выдача осуществляется моментально к себе в Steam.
MociztCof
17 Aug 25 at 10:45 pm
официальный сайт мостбет скачать [url=mostbet11074.ru]mostbet11074.ru[/url]
mostbet_kg_kvsn
17 Aug 25 at 10:48 pm
Marvelous, what a weblog it is! This blog provides helpful facts to us, keep it up.
Also visit my web site; تلفن امداد کرمان موتور
تلفن امداد کرمان موتور
17 Aug 25 at 10:49 pm
PECITOTO menawarkan berbagai bonus menarik sebagai langkah awal menuju kemenangan maxwin dalam permaian slot gacor hari ini,
raih kemenangan mutlak surga game slot gacor hanya
di sini!
peci toto
17 Aug 25 at 10:55 pm
mostbet сайт регистрация [url=https://www.mostbet11069.ru]https://www.mostbet11069.ru[/url]
mostbet_zdSa
17 Aug 25 at 10:56 pm
delivery in new york city shipping services new york
delivery-new-york-335
17 Aug 25 at 11:00 pm
I get pleasure from, lead to I found exactly what I was having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye
https://arlekin-dance.kiev.ua/sklo-far-ta-garantiya-virobnika-scho-potribno-zn-2.html
EarnestAbent
17 Aug 25 at 11:02 pm
прогнозы на хоккей с высокой проходимостью [url=https://www.luchshie-prognozy-na-khokkej13.ru]https://www.luchshie-prognozy-na-khokkej13.ru[/url] .
lychshie prognozi na hokkei_beOl
17 Aug 25 at 11:02 pm
официальный сайт мостбет [url=https://mostbet11068.ru/]https://mostbet11068.ru/[/url]
mostbet_ispn
17 Aug 25 at 11:02 pm
I don’t know if it’s just me or if perhaps everybody else encountering issues with your
blog. It appears as if some of the written text on your content are running off the screen. Can somebody else please comment and let me know if this is happening to them as well?
This could be a problem with my web browser because I’ve had this happen before.
Appreciate it
ballboyz discount code
17 Aug 25 at 11:03 pm
Nice blog here! Also your web 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 quickly as yours lol
новые казино с минимальным депозитом 100 рублей
17 Aug 25 at 11:04 pm
мостбет контакты [url=https://mostbet11074.ru]https://mostbet11074.ru[/url]
mostbet_kg_ossn
17 Aug 25 at 11:09 pm
Greate post. Keep posting such kind of info on your site.
Im really impressed by it.
Hi there, You have done an excellent job. I will definitely digg it and for my part
recommend to my friends. I’m confident they’ll be benefited from this web
site.
رتبه برای پرستاری ۱۴۰۴
17 Aug 25 at 11:11 pm
Howdy! I know this is kinda off topic but I was
wondering if you knew where I could locate a captcha plugin for my
comment form? I’m using the same blog platform as yours and I’m having difficulty finding one?
Thanks a lot!
bet
17 Aug 25 at 11:12 pm