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 browsing on-line greater than 3 hours lately, but
I by no means discovered any interesting article like yours.
It is beautiful price sufficient for me. In my opinion, if all web owners and bloggers
made just right content as you did, the web might be
much more useful than ever before.
Phone sanitizer machine
20 Aug 25 at 6:17 am
Today, while I was at work, my sister stole my iPad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad
is now broken and she has 83 views. I know this is entirely off topic but I had to share it with
someone!
ظرفیت فرهنگیان امسال ۱۴۰۴
20 Aug 25 at 6:19 am
Нужна срочная помощь? Центр «Alco.Rehab» в Москве предлагает круглосуточный вывод из запоя с выездом на дом.
Узнать больше – [url=https://nazalnyj.ru/]вывод из запоя на дому круглосуточно город москва[/url]
AlbertThade
20 Aug 25 at 6:21 am
SildenaPeak: SildenaPeak – how to purchase viagra pills
ElijahKic
20 Aug 25 at 6:22 am
Hello there, just became aware of your blog through Google,
and found that it’s really informative. I’m gonna watch out for brussels.
I’ll be grateful if you continue this in future.
A lot of people will be benefited from your writing.
Cheers!
انتخاب رشته کنکور با هوش مصنوعی
20 Aug 25 at 6:22 am
https://odysee.com/@anarasius_chico
Jimmybub
20 Aug 25 at 6:24 am
Сначала администратор собирает ключевые данные: возраст и примерный вес, длительность употребления, описание симптомов, хронические заболевания, аллергии и принимаемые лекарства. По этой информации врач заранее продумывает схему инфузии и прогнозирует длительность процедуры.
Изучить вопрос глубже – [url=https://narkolog-na-dom-serpuhov6.ru/]vyzvat-narkologa-na-dom[/url]
HowardDiz
20 Aug 25 at 6:31 am
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
a comment is added I get several e-mails with the same comment.
Is there any way you can remove people from that service? Thank you!
Casino Online Terpercaya Casino Online Terpercaya
20 Aug 25 at 6:34 am
Этап процедуры
Разобраться лучше – [url=https://vyvod-iz-zapoya-odincovo6.ru/]skoraya-pomoshch-vyvoda-iz-zapoya[/url]
RicardoJar
20 Aug 25 at 6:35 am
плинко кз [url=https://plinko3001.ru]https://plinko3001.ru[/url]
plinko_kz_iiEr
20 Aug 25 at 6:36 am
I’m gone to convey my little brother, that he should also pay a visit this webpage on regular basis to obtain updated from
most recent reports.
My webpage Future-focused career coaching services online
Future-focused career coaching services online
20 Aug 25 at 6:37 am
Hi my family member! I wish to say that this post is amazing, nice written and come with almost all vital infos.
I would like to peer extra posts like this .
https://seobests.com/service/10000-forum-profiles-backlinks
20 Aug 25 at 6:37 am
Hi there, You have done an incredible job. I will certainly digg
it and personally recommend to my friends. I am confident they’ll be benefited from this
website.
thematthatters.com
20 Aug 25 at 6:39 am
купить аттестат за 11 класс калининграде [url=http://www.arus-diplom21.ru]купить аттестат за 11 класс калининграде[/url] .
Diplomi_dpPr
20 Aug 25 at 6:40 am
как потратить бонусы казино 1win [url=https://1win22097.ru]https://1win22097.ru[/url]
1win_zkpr
20 Aug 25 at 6:41 am
Thanks for sharing your thoughts on winter solar lights.
Regards
winter solar lights
20 Aug 25 at 6:43 am
https://mez.ink/vjolamaxudu
Jimmybub
20 Aug 25 at 6:44 am
It’s an awesome paragraph in favor of all the internet viewers; they will get benefit from it I am sure.
situs toto slot 4d
20 Aug 25 at 6:47 am
купить подлинный аттестат за 11 класс [url=http://arus-diplom22.ru/]купить подлинный аттестат за 11 класс[/url] .
Diplomi_miKt
20 Aug 25 at 6:47 am
В Челябинске решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Подробнее – [url=https://vyvod-iz-zapoya-chelyabinsk11.ru/]челябинская область[/url]
Walterskips
20 Aug 25 at 6:49 am
This post will help the internet people for setting up new weblog or even a weblog from start to end.
how to charge a solar panel without sunlight
20 Aug 25 at 6:50 am
горшки для цветов с автополивом купить [url=http://www.kashpo-s-avtopolivom-spb.ru]горшки для цветов с автополивом купить[/url] .
gorshok s avtopolivom_swsr
20 Aug 25 at 6:50 am
melbet promo code [url=https://melbet3006.com/]https://melbet3006.com/[/url]
melbet_bkpa
20 Aug 25 at 6:50 am
viagra 50mg generic: SildenaPeak – SildenaPeak
PeterTEEFS
20 Aug 25 at 6:54 am
Thank you a lot for sharing this with all folks you actually know what you are speaking about!
Bookmarked. Please also talk over with my website =).
We could have a hyperlink change contract between us
my site … avซับไทย
avซับไทย
20 Aug 25 at 6:55 am
I was wondering if you ever considered changing the structure of your website?
Its very well written; I love what youve got to say. But maybe you could a little more in the way of
content so people could connect with it better. Youve got an awful lot of text for only
having 1 or 2 images. Maybe you could space it
out better?
A Perfect Finish Painting
20 Aug 25 at 6:55 am
Капельницы от запоя в Красноярске: экстренная помощь на дому Проблема алкогольной зависимости требует квалифицированного подхода. При запойном состоянии наблюдаются тяжелые симптомы‚ такие как тремор‚ повышенная потливость‚ беспокойство и‚ порой‚ галлюцинации. В таких ситуациях необходима помощь нарколога для получения грамотной медицинской помощи. Преимущества домашней терапии заключаются в том‚ что пациент находится в знакомой среде‚ что помогает быстрее восстановиться после запоя. Не менее важно уделить внимание профилактике рецидивов‚ чтобы предотвратить повторные запои. Обращаясь за помощью к специалистам‚ вы получите не только капельницы для детоксикации‚ но и комплексное лечение алкоголизма‚ направленное на полное восстановление.
vivodzapojkrasnoyarskNeT
20 Aug 25 at 6:56 am
https://bio.site/ucodfibahibs
Samuelloofe
20 Aug 25 at 6:59 am
buying cheap baclofen tablets
where can i buy generic baclofen without insurance
20 Aug 25 at 6:59 am
В Санкт-Петербурге решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Выяснить больше – [url=https://azithromycinum.ru/]помощь вывод из запоя[/url]
Terryunock
20 Aug 25 at 7:00 am
https://odysee.com/@kJJezequell1l
Jimmybub
20 Aug 25 at 7:05 am
плинко кз [url=plinko3001.ru]плинко кз[/url]
plinko_kz_cbEr
20 Aug 25 at 7:09 am
Hey There. I found your blog using msn. This is a very well written article.
I’ll be sure to bookmark it and come back to read more of your useful info.
Thanks for the post. I will certainly comeback.
flm bokep xxx
20 Aug 25 at 7:16 am
Клиника «АнтиАлко» предлагает экстренную медицинскую помощь на дому в Новосибирске и Новосибирской области для тех, кто столкнулся с запоем. Если вы или ваш близкий оказались в состоянии длительной алкогольной интоксикации, наши специалисты готовы оперативно приехать к вам, провести комплексную детоксикацию и купировать симптомы абстинентного синдрома. Мы гарантируем высокий уровень безопасности, полную анонимность и индивидуальный подход к каждому пациенту.
Подробнее – [url=https://vyvod-iz-zapoya-novosibirsk00.ru/]vyvod-iz-zapoya-na-domu novosibirsk[/url]
DavidBrard
20 Aug 25 at 7:17 am
провайдеры интернета по адресу
krasnoyarsk-domashnij-internet005.ru
провайдеры по адресу
inernetadreselini
20 Aug 25 at 7:18 am
Great web site. A lot of helpful information here.
I’m sending it to several pals ans also sharing in delicious.
And of course, thanks on your effort!
آموزش ارز دیجیتال در تهران
20 Aug 25 at 7:19 am
Great article! This is the type of info that are supposed to be
shared around the internet. Disgrace on the seek engines
for now not positioning this put up higher! Come on over
and discuss with my web site . Thank you =)
فرق فرهنگیان آزاد با روزانه
20 Aug 25 at 7:21 am
software de gestión de multipropiedad
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
software de gestión de multipropiedad
20 Aug 25 at 7:22 am
https://say.la/read-blog/126790
Jimmybub
20 Aug 25 at 7:26 am
купить аттестат за 11 классов в орле [url=http://arus-diplom21.ru]купить аттестат за 11 классов в орле[/url] .
Diplomi_ujPr
20 Aug 25 at 7:27 am
Затем организуется выезд специалиста — нарколог приезжает на дом или, по желанию, принимает пациента в стационаре. После осмотра и измерения жизненно важных показателей врач разрабатывает индивидуальную схему терапии. Главная цель — мягкая и безопасная детоксикация, восстановление работы органов и снятие психических и физических симптомов.
Получить дополнительные сведения – http://vyvod-iz-zapoya-shchelkovo6.ru/vyvod-iz-zapoya-nedorogo-v-shchelkovo/https://vyvod-iz-zapoya-shchelkovo6.ru
BrucePal
20 Aug 25 at 7:32 am
viagra europe over the counter: cheap viagra 100mg canada – can you buy viagra
RichardTit
20 Aug 25 at 7:33 am
blacksprut ссылка
RichardPep
20 Aug 25 at 7:33 am
купить аттестат 11 классов за 1996 год [url=www.arus-diplom22.ru/]купить аттестат 11 классов за 1996 год[/url] .
Diplomi_rqKt
20 Aug 25 at 7:33 am
plinko slot [url=http://plinko-kz2.ru]plinko slot[/url]
plinko_kz_wfer
20 Aug 25 at 7:39 am
Do you mind if I quote a couple of your articles as long as I
provide credit and sources back to your blog? My blog
is in the exact same area of interest as yours and
my users would genuinely benefit from a lot of the information you present here.
Please let me know if this ok with you. Regards!
کنکور فرهنگیان ضرایب
20 Aug 25 at 7:39 am
Terrific work! That is the type of info that are meant
to be shared around the web. Shame on the search engines for no longer positioning this submit upper!
Come on over and visit my website . Thank you =)
https://poolstoday.net/
Bookmakers News
20 Aug 25 at 7:39 am
https://shootinfo.com/author/kevinhornekev/?pt=ads
Samuelloofe
20 Aug 25 at 7:43 am
https://beteiligung.stadtlindau.de/profile/%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%91%D0%BE%D1%88%D0%BA%D0%B8%20%D0%9C%D0%B0%D1%80%D0%B8%D1%85%D1%83%D0%B0%D0%BD%D1%83%20%D0%93%D0%B0%D1%88%D0%B8%D1%88%20%D0%A2%D1%80%D0%B0%D0%B1%D0%B7%D0%BE%D0%BD/
Jimmybub
20 Aug 25 at 7:46 am
We are a group of volunteers and opening a new
scheme in our community. Your site offered us with valuable
information to work on. You have done an impressive task and our entire neighborhood will probably be
thankful to you.
best rechargeable batteries for solar lights
20 Aug 25 at 7:48 am