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!
Нужна срочная помощь? Центр «Alco.Rehab» в Москве предлагает круглосуточный вывод из запоя с выездом на дом.
Выяснить больше – [url=https://nazalnyj.ru/]срочный вывод из запоя город москва[/url]
DonaldFUP
21 Aug 25 at 8:20 am
https://say.la/read-blog/126394
ArturoVoift
21 Aug 25 at 8:20 am
купить аттестаты 11 [url=www.arus-diplom24.ru/]купить аттестаты 11[/url] .
Diplomi_utsa
21 Aug 25 at 8:29 am
https://paper.wf/idiiiuhy/lloret-de-mar-kupit-kokain-mefedron-marikhuanu
Charleswar
21 Aug 25 at 8:29 am
For the reason that the admin of this site is
working, no doubt very quickly it will be well-known,
due to its feature contents.
Orient Tonic natural energy booster
21 Aug 25 at 8:32 am
После выбора подходящей методики врач подробно рассказывает о сути процедуры, даёт письменные рекомендации, объясняет правила поведения и отвечает на вопросы пациента и семьи.
Выяснить больше – https://kodirovanie-ot-alkogolizma-dolgoprudnyj6.ru/kodirovanie-ot-alkogolizma-ceny-v-dolgoprudnom
Fredrichop
21 Aug 25 at 8:32 am
At this time I am going to do my breakfast, afterward having my breakfast coming yet again to read more
news.
link pg66luxe
21 Aug 25 at 8:38 am
Pretty nice post. I just stumbled upon your weblog and
wished to say that I have truly enjoyed browsing your blog posts.
After all I’ll be subscribing to your rss feed and I hope you write again soon!
site
21 Aug 25 at 8:40 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Узнать из первых рук – https://a-s-petrov.ru/?paged=36
WayneDrist
21 Aug 25 at 8:40 am
https://odysee.com/@slooshorcrown709
Nathanfal
21 Aug 25 at 8:41 am
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make
your point. You obviously know what youre talking about, why waste
your intelligence on just posting videos to your weblog when you could
be giving us something informative to read?
read here
21 Aug 25 at 8:41 am
Mitolyn is becoming popular as a supplement that
targets mitochondrial health to improve energy, metabolism, and overall vitality.
By helping the body burn fat more efficiently and reduce fatigue, it supports both weight
management and daily performance. Many people appreciate
it as a natural, safe option for staying energized and active throughout the day.
Mitolyn
21 Aug 25 at 8:41 am
Why viewers still make use of to read news
papers when in this technological globe the
whole thing is presented on web?
"eyeliner"
21 Aug 25 at 8:43 am
Tadalify: cialis lower blood pressure – cialis tadalafil & dapoxetine
PeterTEEFS
21 Aug 25 at 8:46 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Обратитесь за информацией – http://www.riasamara.ru/rus/review/paint/?2
Davidjar
21 Aug 25 at 8:47 am
Greetings, I think your web site could be having browser compatibility issues.
Whenever I take a look at your web site in Safari, it
looks fine however, when opening in Internet Explorer,
it’s got some overlapping issues. I merely wanted to give
you a quick heads up! Apart from that, excellent blog!
fire damage repair company
21 Aug 25 at 8:49 am
Keep on working, great job!
Bit4win Casino
21 Aug 25 at 8:50 am
These are actually impressive ideas in about blogging.
You have touched some good things here. Any way keep
up wrinting.
webadministrables.com
21 Aug 25 at 8:53 am
Stavki Prognozy [url=www.stavki-prognozy-two.ru/]www.stavki-prognozy-two.ru/[/url] .
stavki prognozi_pyMr
21 Aug 25 at 8:53 am
Всех приветствую! Хотите узнать больше о продвижении? Узнайте подробнее – http://stanoviska-mv.wz.cz/2024/02/stiznosti-dle-%C2%A7-175-spravniho-radu/
WilliamLig
21 Aug 25 at 8:55 am
Редкоземельные металлы и их
значение в промышленности
Редкоземельные металлы – их роль в промышленности
Для успешного продвижения в высоких технологиях необходимо уделить особое внимание элементам, которые обеспечивают высокую производительность и функциональность.
Эти уникальные вещества используются в производстве
электроники, аккумуляторов, магнитов и других ключевых компонентов.
Важно понимать, какие именно
из них имеют наибольшее значение
для конкретных отраслей.
Среди наиболее востребованных из группы таких
веществ можно выделить неодим,
который активно применяется в производстве магнитов для электродвигателей и
генераторов. Без него невозможно создать высокоэффективные решения для wind-энергетики и
электрических автомобилей, что
подчеркивает его необходимость в современном производстве.
Также следует обратить
внимание на лантан и церий, нужные в катализаторах для автомобильной отрасли,
а также в оптике. Использование этих
элементов может значительно
повысить экологические показатели автомобилей, что становится всё более актуальным в контексте глобального давления по снижению выбросов.
Тщательное изучение и как
следствие внедрение этих компонентов в
процесс производства открывает новые
горизонты для устойчивого
развития технологий.
Не забывайте о сложностях, связанных с добычей оболочек и их переработкой.
Эффективное управление ресурсами этих
элементов не только минимизирует экологический ущерб, но и открывает новые
возможности для смежных сфер.
Создание партнерств и научных исследований в этой области поможет находить более оптимальные пути
решения поставленных задач.
Применение редкоземельных элементов в производстве электроники
Использование дисплеев на основе оксида индия
и олова (ITO), содержащих элементы
из группы редкоземельных,
позволяет обеспечить высокую прозрачность и проводимость, тем
самым улучшая качество изображений в смартфонах и телевизорах.
Рекомендуется применять такие материалы для экранов,
чтобы повысить эффективность работы устройств
и снизить потребление энергии.
Магниты на основе неодима эффективно используются
в аудиосистемах и наушниках, обеспечивая мощный звук при
малых размерах. Их применение рекомендуется в высококачественной акустике и
профессиональных студийных мониторах.
Это снизит размер устройства
при сохранении его характеристик.
В аккумуляторах современных электроавтомобилей часто используются соединения, содержащие элементы из
группы лантаноидов. Это улучшает
эффективность зарядки и увеличивает
срок службы батарей. Настоятельно рекомендуется рассмотреть использование таких технологий для повышения производительности электромобилей.
Фосфоры на основе европия применяются в светодиодах и различных освещениях,
обеспечивая яркий и стабильный свет.
Их использование в новых продуктах позволит улучшить качество освещения
и снизить энергозатраты, что делает их предпочтительными для применения в многосветильных проектах.
Наконец, материалы на основе тербия находят своё применение в
системах передачи данных, повышая скорость и
надежность связи. Их внедрение
в новые решения для интернета позволит улучшить качество обслуживания и снизить задержки, что положительно скажется на опыт пользователей.
Влияние редкоземельных элементов на энергетику и возобновляемые
источники энергии
Промышленный сектор должен применять
элементы, такие как неодим и самарий,
для повышения эффективности генераторов в ветряных установках.
Увеличение выхода энергии достигается за счет применения сверхпроводящих материалов,
что ведет к сокращению размеров переплетов и снижению потерь.
Солнечные панели становятся более
производительными благодаря включению препаратов на основе иттрия и тербия.
Эти соединения позволяют минимизировать отражение света и способствуют более интенсивному поглощению солнечного излучения, что увеличивает уровень преобразования солнечной энергии в электричество.
Батареи для электромобилей становятся более долговечными и высокопроизводительными за счет литий-никель-кобальтовых соединений,
в которых используются элементы, способствующие улучшению
характеристики зарядки и разрядки.
Внедрение подобных технологий способствует увеличению дальности хода и сокращению времени зарядки.
Элементы, такие как europium и terbium, помогают в производстве
светодиодных ламп, которые используются в различных приложениях,
от освещения до дисплеев. Эти источники освещения
демонстрируют высокую энергоэффективность и долговечность,
что содействует снижению потребления энергии.
Защита окружающей среды имеет
первостепенное значение, и использование данных составных в инновационных решениях помогает минимизировать углеродный след.
Актуально развивать технологии переработки для возвращения
элементов в производственный процесс, что повысит
устойчивость и снизит зависимость от первичного извлечения.
my web-site :: https://uztm-ural.ru/catalog/redkozemelnye-i-redkie-metally/
https://uztm-ural.ru/catalog/redkozemelnye-i-redkie-metally/
21 Aug 25 at 8:55 am
I like reading through an article that will make people think.
Also, many thanks for allowing me to comment!
Game Bài TT88
21 Aug 25 at 8:55 am
купить проведенный диплом вуза [url=www.arus-diplom33.ru]www.arus-diplom33.ru[/url] .
Diplomi_afSa
21 Aug 25 at 8:56 am
Safe access to generic ED medication: Kamagra oral jelly USA availability – Safe access to generic ED medication
ElijahKic
21 Aug 25 at 8:58 am
I do not еven know how I ended up here, but I thought this post was great.
I don’t know ѡho you are but definitely you are ɡoing to
a fam᧐ᥙs blogger if you aren’t already 😉 Сheers!
My site; Oversized T Shirt Dubai
Oversized T Shirt Dubai
21 Aug 25 at 8:59 am
https://pixelfed.tokyo/diversant335
Nathanfal
21 Aug 25 at 9:02 am
https://odysee.com/@Matharoolifec
JuliusGlush
21 Aug 25 at 9:08 am
viagra canada for sale: how to get viagra in india – viagra price in us
RichardTit
21 Aug 25 at 9:13 am
прогноз от профессионалов [url=prognozy-na-sport-7.ru]прогноз от профессионалов[/url] .
prognozi na sport_xiMi
21 Aug 25 at 9:19 am
I think this is one of the most significant information for me.
And i’m glad reading your article. But wanna remark on few general
things, The website style is great, the articles is really nice :
D. Good job, cheers
live casino88
21 Aug 25 at 9:20 am
общаться с психологом онлайн
Charliesoall
21 Aug 25 at 9:20 am
I’m not sure where you’re getting your info, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for wonderful information I was looking for this information for my mission.
soi keo nha cai
21 Aug 25 at 9:22 am
https://www.themeqx.com/forums/users/xibtihuahqoa/
Nathanfal
21 Aug 25 at 9:24 am
buying cheap maxolon without a prescription
where to buy maxolon
21 Aug 25 at 9:24 am
Heya i’m for the first time here. I found this board and I find
It truly useful & it helped me out a lot. I hope to give something back and aid others like you aided me.
keonhacai com xem bong da truc tuyen
21 Aug 25 at 9:24 am
35 viagra: brand viagra price – SildenaPeak
PeterTEEFS
21 Aug 25 at 9:26 am
Affordable sildenafil citrate tablets for men: Non-prescription ED tablets discreetly shipped – Kamagra reviews from US customers
ElijahKic
21 Aug 25 at 9:26 am
где можно купить аттестат за 11 класс владивосток [url=www.arus-diplom22.ru]где можно купить аттестат за 11 класс владивосток[/url] .
Diplomi_ensl
21 Aug 25 at 9:34 am
столбовая мачтовая трансформаторная подстанция [url=https://www.transformatornye-podstancii-kupit.ru]https://www.transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_ytoi
21 Aug 25 at 9:36 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Разобраться лучше – https://alpina-eyewear.ru/?paged=49
Ralphmub
21 Aug 25 at 9:38 am
Every weekend i used to visit this website, for the
reason that i want enjoyment, since this this site conations in fact pleasant funny data too.
Ready Elm Grove roof installation near me
21 Aug 25 at 9:40 am
Компания IT-OFFSHORE большой опыт и прекрасную репутацию имеет. Благодаря нам клиенты получат доступные цены и ресурс оффшорный. Также по всем вопросам предоставим грамотную помощь. У нас квалифицированные специалисты работают. Наши основные приоритеты – качество и стабильность. Ищете купить готовую фирму в сингапуре? It-offshore.com – здесь представлена более детальная информация о нас, ознакомиться с ней можно прямо сейчас. На портале вы можете получить персональное предложение и заявку отправить. Помимо прочего у нас вы подробнее узнаете о наших преимуществах.
wifofeHow
21 Aug 25 at 9:41 am
Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
Что ещё? Расскажи всё! – https://pisali.ru/astrolab/1540
Davidjar
21 Aug 25 at 9:41 am
На сайте https://prometall.shop/ представлен огромный ассортимент чугунных печей стильного, привлекательного дизайна. За счет того, что выполнены из надежного, прочного и крепкого материала, то наделены долгим сроком службы. Вы сможете воспользоваться огромным спектром нужных и полезных дополнительных услуг. В каталоге вы найдете печи в сетке, камне, а также отопительные. Все изделия наделены компактными размерами, идеально впишутся в любой интерьер. При разработке были использованы уникальные, высокие технологии.
XesodeDox
21 Aug 25 at 9:42 am
Thanks for the good writeup. It in truth was once a leisure account it.
Glance complex to far introduced agreeable from you! By the way, how could we be in contact?
keonhacai
21 Aug 25 at 9:42 am
When some one searches for his essential thing, so he/she wants to be available that in detail, therefore that thing
is maintained over here.
kormarines.com
21 Aug 25 at 9:42 am
Вывод из запоя в Реутове — это экстренная комплексная помощь при алкогольной интоксикации, направленная на быстрое и безопасное выведение токсинов из организма, восстановление водно-электролитного баланса и купирование опасных симптомов абстинентного синдрома. В наркологической клинике «Феникс-Мед» вы можете заказать выезд квалифицированного врача на дом или пройти лечение в стационаре, доверив своё здоровье команде опытных специалистов.
Исследовать вопрос подробнее – http://vyvod-iz-zapoya-reutov4.ru/
Frankjah
21 Aug 25 at 9:43 am
https://kemono.im/udeyaoucpih/tuluza-kupit-gashish-boshki-marikhuanu
Nathanfal
21 Aug 25 at 9:45 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Полная информация здесь – https://spearhand.uk/solar-panels-101-a-beginners-guide-to-solar-energy
Jerrynox
21 Aug 25 at 9:46 am
Hiya! I know this is kinda off topic however I’d figured I’d
ask. Would you be interested in exchanging
links or maybe guest writing a blog post or vice-versa?
My site discusses a lot of the same subjects as yours and I think we could greatly benefit from each other.
If you are interested feel free to shoot me an email.
I look forward to hearing from you! Excellent blog by the way!
saowin
21 Aug 25 at 9:47 am