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!
https://www.rwaq.org/users/alexanep8g2t-20250817204918
Michealsniff
19 Aug 25 at 3:24 am
SildenaPeak: viagra tablets for sale uk – SildenaPeak
ElijahKic
19 Aug 25 at 3:24 am
buying cheap ventolin for sale
how can i get cheap ventolin prices
19 Aug 25 at 3:29 am
Currently it sounds like BlogEngine is the preferred blogging platform out there right now.
(from what I’ve read) Is that what you’re using on your blog?
Aurea Fundline
19 Aug 25 at 3:34 am
Fast-acting ED solution with discreet packaging: Online sources for Kamagra in the United States – Safe access to generic ED medication
PeterTEEFS
19 Aug 25 at 3:37 am
горшок с автополивом купить [url=http://kashpo-s-avtopolivom-kazan.ru]горшок с автополивом купить[/url] .
gorshok s avtopolivom_wkmr
19 Aug 25 at 3:43 am
https://say.la/read-blog/125823
Ronaldbum
19 Aug 25 at 3:44 am
https://www.montessorijobsuk.co.uk/author/jeobhebi/
Michealsniff
19 Aug 25 at 3:45 am
аттестат 11 классов купить в нижнем тагиле [url=https://arus-diplom24.ru]аттестат 11 классов купить в нижнем тагиле[/url] .
Diplomi_zesa
19 Aug 25 at 3:47 am
Write more, thats all I have to say. Literally, it seems as
though you relied on the video to make your point.
You clearly know what youre talking about, why waste your intelligence
on just posting videos to your weblog when you could be giving
us something enlightening to read?
kungfu-videos.com
19 Aug 25 at 3:48 am
Yes! Finally something about Frame Flomax Neo.
Frame Flomax Neo
19 Aug 25 at 3:48 am
Inspiring story there. What occurred after? Take care!
6ff.black
19 Aug 25 at 3:50 am
как купить аттестат за 11 класс в казахстане [url=http://www.arus-diplom23.ru]как купить аттестат за 11 класс в казахстане[/url] .
Diplomi_jmol
19 Aug 25 at 3:50 am
купить проведенный диплом одно [url=http://www.arus-diplom35.ru]купить проведенный диплом одно[/url] .
Vigodno zakazat diplom lubogo yniversiteta!_icot
19 Aug 25 at 3:52 am
Программа лечения строится на комплексном подходе, который учитывает не только физические, но и психоэмоциональные потребности пациента. Благодаря круглосуточной доступности наркологической помощи, лечение начинается в самые ранние часы кризиса, что значительно повышает шансы на успешную реабилитацию.
Выяснить больше – [url=https://vyvod-iz-zapoya-tula000.ru/]вывод из запоя капельница тула[/url]
MichaelDup
19 Aug 25 at 3:57 am
Whats up very nice site!! Man .. Beautiful ..
Superb .. I’ll bookmark your web site and take the feeds additionally?
I am satisfied to search out numerous helpful information right here in the put up, we need work out extra techniques on this regard, thank you for sharing.
. . . . .
au88t3.us.com
19 Aug 25 at 4:02 am
Aw, this was an incredibly nice post. Taking a few minutes and
actual effort to generate a top notch article… but
what can I say… I put things off a lot and
don’t manage to get anything done.
plateforme bourse
19 Aug 25 at 4:04 am
https://www.themeqx.com/forums/users/yfuahpyodady/
Michealsniff
19 Aug 25 at 4:06 am
Запой, интоксикация? Вызовите нарколога на дом в Иркутске для быстрой и анонимной помощи. На дому: осмотр, подбор лечения, капельница для вывода токсинов и улучшение самочувствия. «ТрезвоМед» – круглосуточная наркологическая помощь на дому с гарантией анонимности. Не справляетесь с зависимостью сами? Вызовите нарколога на дом. Васильев подчеркивает: «Оперативная помощь – ключ к выздоровлению при отравлении алкоголем».
Подробнее – [url=https://narcolog-na-dom-v-irkutske0.ru/]нарколог на дом в иркутске[/url]
Andrewbrula
19 Aug 25 at 4:06 am
Купить диплом на заказ можно через сайт компании. [url=http://kronverskiy.ru/posting.php?mode=post&f=28/]kronverskiy.ru/posting.php?mode=post&f=28[/url]
Sazrkde
19 Aug 25 at 4:07 am
купить аттестат за 11 класс в омске [url=https://arus-diplom24.ru]купить аттестат за 11 класс в омске[/url] .
Diplomi_bwsa
19 Aug 25 at 4:09 am
Access your student email at our platform and unlock exclusive student
benefits. Get educational discounts, premium tools,
and more—without enrollment.
free edu mail
19 Aug 25 at 4:09 am
Незамедлительно после вызова нарколог прибывает на дом для проведения тщательного осмотра. На данном этапе специалист собирает анамнез, измеряет жизненно важные показатели — пульс, артериальное давление, температуру — и оценивает степень интоксикации. Эти данные являются основой для составления индивидуального плана лечения.
Выяснить больше – [url=https://vyvod-iz-zapoya-vladimir000.ru/]вывод. из. запоя. владимир.[/url]
Mathewscose
19 Aug 25 at 4:16 am
I visit each day some web pages and information sites to read articles
or reviews, except this weblog provides feature based writing.
شیر بت
19 Aug 25 at 4:17 am
how to get viagra prescription in australia: how to get female viagra pill – SildenaPeak
PeterTEEFS
19 Aug 25 at 4:21 am
http://webanketa.com/forms/6mrk6chk64qkge3370skedv1/
Michealsniff
19 Aug 25 at 4:26 am
https://wanderlog.com/view/ksakvdsbmb/купить-кокаин-марихуану-мефедрон-копенгаген/shared
Ronaldbum
19 Aug 25 at 4:29 am
как купить официальный аттестат 11 класс [url=www.arus-diplom24.ru]как купить официальный аттестат 11 класс[/url] .
Diplomi_bgsa
19 Aug 25 at 4:33 am
SildenaPeak [url=https://sildenapeak.shop/#]viagra united states[/url] what is sildenafil
RobertCat
19 Aug 25 at 4:39 am
В клинике используются запатентованные наборы для капельниц, включающие витамины группы B, мембранопротекторы и низкомолекулярные антиоксиданты. Автоматизированные насосы обеспечивают равномерный ввод растворов, минимизируя риск осложнений.
Подробнее – [url=https://lechenie-narkomanii-ekaterinburg0.ru/]принудительное лечение наркомании в екатеринбурге[/url]
HarryJedia
19 Aug 25 at 4:41 am
Prostavive seems like a reliable supplement for men who want to support their
prostate health naturally. I like that it’s made with ingredients aimed at improving
urinary flow, reducing nighttime bathroom trips, and
boosting overall comfort. Many users say they feel more confident and notice real improvements after taking Prostavive,
which makes it worth checking out.
Prostavive
19 Aug 25 at 4:45 am
https://kopirych.by/uslugi-po-lazernoj-rezke-i-gravirovke/rezka-kozhi-bumagi-i-dr.html
Scottbek
19 Aug 25 at 4:45 am
https://wanderlog.com/view/avgltwmgzx/купить-экстази-кокаин-амфетамин-ингольштадт/shared
Michealsniff
19 Aug 25 at 4:46 am
For latest news you have to visit world-wide-web and on internet I found this web page as a best web
page for latest updates.
Zeker Bitlijn
19 Aug 25 at 4:50 am
кракен ссылка
RichardPep
19 Aug 25 at 4:51 am
где купить чистый аттестат за 11 класс [url=https://www.arus-diplom24.ru]где купить чистый аттестат за 11 класс[/url] .
Diplomi_lasa
19 Aug 25 at 4:55 am
Использование автоматизированных систем дозирования обеспечивает точное введение медикаментов, минимизируя риск передозировки и побочных эффектов. Постоянный мониторинг жизненно важных показателей позволяет врачу оперативно корректировать терапевтическую схему, адаптируя её к изменяющемуся состоянию пациента и обеспечивая максимальную безопасность лечения.
Подробнее – https://vyvod-iz-zapoya-tula00.ru/vyvod-iz-zapoya-czena-tula/
CharlesMaync
19 Aug 25 at 4:55 am
Medication information sheet. Cautions.
cost of generic phenytoin without rx
Some about drugs. Read now.
cost of generic phenytoin without rx
19 Aug 25 at 5:00 am
купить аттестат 11 классов в красноярске [url=www.arus-diplom24.ru/]www.arus-diplom24.ru/[/url] .
Diplomi_jxsa
19 Aug 25 at 5:02 am
Запой – это неконтролируемое употребление алкоголя, которое приводит к серьезным последствиям. Алкогольное отравление организма приводит к серьезным проблемам со здоровьем. Выходить из запоя самостоятельно – рискованно и неэффективно. Мы предлагаем помощь при запое на дому, в привычных для вас условиях. Круглосуточная помощь при запое с выездом на дом за 30-60 минут. Длительный запой разрушает организм и может быть смертельным. Чем раньше вы обратитесь за помощью, тем больше шансов на выздоровление.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-krasnoyarsk0.ru/]http://vyvod-iz-zapoya-krasnoyarsk0.ru/[/url]
Andrewsheve
19 Aug 25 at 5:02 am
What we’re covering
• Zelensky in Washington: Ukrainian President Volodymyr Zelensky has arrived in Washington, DC, where he will be joined by key European leaders when he meets with Donald Trump this afternoon. Trump says Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra20at.org]kra8 cc[/url]
• Potential security guarantees: At last week’s summit with Trump, President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kra17-cc.com]kra10 cc[/url]
• Change in tactics: Trump is now focused on securing a peace deal without pursuing a ceasefire due to his progress with Putin, Witkoff said. In seeking this deal, Trump has backed away from his threat of new sanctions on Moscow, despite calls to impose more economic pressure.
kra10 cc
https://kraken7.net
BryanMok
19 Aug 25 at 5:03 am
What we’re covering
• Zelensky in Washington: Ukrainian President Volodymyr Zelensky has arrived in Washington, DC, where he will be joined by key European leaders when he meets with Donald Trump this afternoon. Trump says Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kraken14—at.net]kra7[/url]
• Potential security guarantees: At last week’s summit with Trump, President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kraken18-at.com]kra10 at[/url]
• Change in tactics: Trump is now focused on securing a peace deal without pursuing a ceasefire due to his progress with Putin, Witkoff said. In seeking this deal, Trump has backed away from his threat of new sanctions on Moscow, despite calls to impose more economic pressure.
kra10
https://kra-4at.com
Robertgew
19 Aug 25 at 5:04 am
Hello it’s me, I am also visiting this web site regularly, this web site is truly pleasant and the viewers are genuinely sharing fastidious thoughts.
آموزش ارز دیجیتال در تهران آموزش ترید در تهرا
19 Aug 25 at 5:06 am
In fact when someone doesn’t understand afterward its up to other users that they will
help, so here it happens.
exterior door replacement
19 Aug 25 at 5:07 am
https://allmynursejobs.com/author/edingloedeil5/
Michealsniff
19 Aug 25 at 5:07 am
Howdy! This article couldn’t be written much better!
Looking at this article reminds me of my previous roommate!
He constantly kept talking about this. I’ll forward this article to him.
Fairly certain he will have a good read. Many thanks
for sharing!
88fc trang chủ
19 Aug 25 at 5:09 am
http://webanketa.com/forms/6mrk8dhn6cqp8dk66ctk0e34/
Ronaldbum
19 Aug 25 at 5:14 am
аттестат за 11 класс купить ижевск [url=http://www.arus-diplom22.ru]аттестат за 11 класс купить ижевск[/url] .
Diplomi_vvsl
19 Aug 25 at 5:15 am
купить аттестат за 10 11 класс школы [url=http://www.arus-diplom25.ru]купить аттестат за 10 11 класс школы[/url] .
Diplomi_jnot
19 Aug 25 at 5:15 am
Сегодня доступ в интернет стал важной составляющей повседневной жизни‚ и поиск надежного интернет-провайдера в Екатеринбурге имеет большое значение. Сравнение провайдеров по качеству связи‚ отзывам пользователей помогает выбрать лучший вариант.На рынке услуг связи представлено многочисленные провайдеры в Екатеринбурге. Важно учитывать разнообразие тарифов и предложения конкурентов . Многие пользователи отмечают высокие скорости интернета и надежность Wi-Fi соединений у таких компаний‚ как Ростелеком‚ МТС и Beeline.Отзывы клиентов обычно показывают какая техподдержка интернет-провайдеров наиболее эффективна. Наличие круглосуточной техподдержки говорит о надежности провайдера. интернет провайдер Екатеринбург При выборе стоит обратить внимание на цены на интернет-услуги и качество предоставляемых сервисов. Рекомендуется ознакомиться с рейтингами и отзывами‚ чтобы осуществить разумный выбор при подключении интернета.
internetelini
19 Aug 25 at 5:16 am