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://linkin.bio/katusopanir
Eugeneimatt
21 Aug 25 at 1:41 pm
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://kraken6.net]kraken15 at[/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://kraken14-at.com]kra8[/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.
kraken18.at
https://kra05.at
Robertgew
21 Aug 25 at 1:42 pm
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Ознакомиться с полной информацией – https://mealpe.app/indias-first-virtual-food-court-solution-for-corporate
JasonSueri
21 Aug 25 at 1:46 pm
сайт услуги косметолога [url=www.kosmetologiya-novosibirsk-1.ru]сайт услуги косметолога[/url] .
kosmetologiya v Novosibirske_siPl
21 Aug 25 at 1:46 pm
где купить аттестат за 11 класс в тюмени [url=http://arus-diplom23.ru]где купить аттестат за 11 класс в тюмени[/url] .
Diplomi_piol
21 Aug 25 at 1:46 pm
промышленные трансформаторные подстанции [url=http://www.transformatornye-podstancii-kupit.ru]http://www.transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_deoi
21 Aug 25 at 1:46 pm
My programmer is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the costs. But
he’s tryiong none the less. I’ve been using Movable-type
on numerous websites for about a year and am worried about switching to another
platform. I have heard great things about blogengine.net. Is there
a way I can import all my wordpress content into it?
Any kind of help would be greatly appreciated!
my page … Massage Berichten
Massage Berichten
21 Aug 25 at 1:49 pm
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://kra7.net]kra11 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://kra20at.cc]kra10[/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.
kra9
https://kraken014-at.com
Williamguamy
21 Aug 25 at 1:51 pm
косметологические услуги [url=http://kosmetologiya-moskva-1.ru/]http://kosmetologiya-moskva-1.ru/[/url] .
kosmetologiya v Moskve_dmet
21 Aug 25 at 1:51 pm
где можно купить диплом [url=www.educ-ua5.ru/]где можно купить диплом[/url] .
Diplomi_qaKl
21 Aug 25 at 1:51 pm
ligand gated channel
Normannus
21 Aug 25 at 1:53 pm
I’m not sure why but this weblog is loading extremely slow for me.
Is anyone else having this problem or is it a problem on my end?
I’ll check back later and see if the problem still exists.
Live Draw China
21 Aug 25 at 1:54 pm
косметолог клиника Москва [url=www.kosmetologiya-moskva-1.ru]косметолог клиника Москва[/url] .
kosmetologiya v Moskve_xget
21 Aug 25 at 1:57 pm
https://www.themeqx.com/forums/users/ifeuagod/
TimothyStync
21 Aug 25 at 1:57 pm
купить диплом в чернигове недорого [url=https://educ-ua5.ru]https://educ-ua5.ru[/url] .
Diplomi_mzKl
21 Aug 25 at 1:57 pm
цены процедур в косметологии [url=https://www.kosmetologiya-novosibirsk-1.ru]цены процедур в косметологии[/url] .
kosmetologiya v Novosibirske_eePl
21 Aug 25 at 2:01 pm
https://muckrack.com/person-27464947
Eugeneimatt
21 Aug 25 at 2:02 pm
You actually make it seem so easy with your presentation but I find this matter
to be actually something which I think I would never understand.
It seems too complex and extremely broad for me.
I’m looking forward for your next post, I’ll try to get the hang of
it!
Web Arena - Sosyal İçerik Platformu
21 Aug 25 at 2:03 pm
Aiyah, composed pom pi pi hor,excellent primary
educates culinary, igniting food business jobs.
Oi oi, reputable primary education cultivates toughness, ѕo yoսr youngster avoids crack սnder PSLE stress ɑnd advances tߋ
leading secondary schools.
Guardians, fearful οf losing style on lah, strong pfimary math guides
іn improved scientific comprehension ɑnd engineering goals.
Ιn ɑddition bеyond institution amenities, focus οn arithmetic in оrder
to stop typical pitfalls ⅼike sloppy blunders in tests.
Oh, mathematics serves аs tһe base stone for primary schooling, aiding
kids іn geometric reasoning to architecture careers.
Οh no, primary math teaches everyday սses
like budgeting, tһus guarantee ʏour child grasps
іt correctly from eaгly.
Don’t taкe lightly lah, combin ɑ excellent primary school рlus math superiority іn oгder tօ assure high PSLE rеsults as ԝell ass effortless transitions.
Greendale Primary School оffers an appealing atmosphere tһat
motivates interest and achievement.
Caring personnel support detailed growth аnd excellence.
Northshore Primary School սses coastal-themed ingenious education.
The school promotes expedition аnd growth.
Ιt’s gгeat for special learning experiences.
Мy web site Peicai Secondary School
Peicai Secondary School
21 Aug 25 at 2:04 pm
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://krak4-at.com]kra4 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://kra5.net]kra16 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.
kra4 cc
https://kr-20.com
OscarCow
21 Aug 25 at 2:06 pm
[url=https://vipusknick.ru/]Канцелярия для офиса и дома[/url] — это важная часть ежедневной жизни, которая помогает поддерживать порядок и повышает эффективность. Регулярное использование канцелярских принадлежностей облегчает процесс работы и учебы. Современные производители предлагают широкий ассортимент: от простых карандашей и ручек до специализированных аксессуаров. Сотрудники компаний ценят наличие удобных папок, маркеров, бумаги и блокнотов. Многие семьи приобретают канцелярию для школьников, студентов и личного использования. Главная особенность канцелярских принадлежностей — это возможность применения в любых ситуациях. Современные покупатели предпочитают заказывать канцелярию через интернет. Покупка онлайн позволяет выбирать из десятков вариантов и получать товары прямо домой. Для бизнеса выгодно приобретать канцелярию оптом. Индивидуальные клиенты подбирают канцтовары исходя из задач и бюджета. Сегодня доступны как бюджетные, так и премиальные решения в сфере канцелярии. Качество продукции напрямую влияет на удобство использования. При выборе канцтоваров важно учитывать эргономику и удобство. С правильной канцелярией процесс работы становится более приятным. Можно с уверенностью сказать, что канцтовары — это база для организации любой деятельности.
https://vipusknick.ru/
vipusknicvah
21 Aug 25 at 2:07 pm
аттестат за 11 класс купить москва [url=http://arus-diplom23.ru/]аттестат за 11 класс купить москва[/url] .
Diplomi_xeol
21 Aug 25 at 2:07 pm
What’s up, I log on to your blog like every week.
Your story-telling style is awesome, keep it up!
بهترین دانشگاه فرهنگیان ایران
21 Aug 25 at 2:09 pm
viagra online from canada generic [url=https://sildenapeak.shop/#]buy sildenafil online india[/url] no prescription viagra
RobertCat
21 Aug 25 at 2:10 pm
услуги косметолога Москва [url=www.kosmetologiya-moskva-1.ru/]услуги косметолога Москва[/url] .
kosmetologiya v Moskve_aaet
21 Aug 25 at 2:11 pm
sildenafil tablet brand name in india: can i buy viagra from canada – SildenaPeak
PeterTEEFS
21 Aug 25 at 2:12 pm
Today, I went to the beach with my children. 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 entirely off topic but I
had to tell someone!
uk8868.com
21 Aug 25 at 2:13 pm
купить аттестаты за 11 класс в спб [url=http://www.arus-diplom25.ru]купить аттестаты за 11 класс в спб[/url] .
Diplomi_dxot
21 Aug 25 at 2:14 pm
купить аттестат за 11 классов в красноярске [url=www.arus-diplom23.ru/]купить аттестат за 11 классов в красноярске[/url] .
Diplomi_bjol
21 Aug 25 at 2:14 pm
Pretty section of content. I just stumbled upon your weblog
and in accession capital to assert that I acquire in fact
enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement
you access consistently quickly.
casino online deutschland
21 Aug 25 at 2:15 pm
косметологическая клиника [url=www.kosmetologiya-novosibirsk-1.ru/]www.kosmetologiya-novosibirsk-1.ru/[/url] .
kosmetologiya v Novosibirske_psPl
21 Aug 25 at 2:17 pm
Right here is the perfect web site for anyone who wishes to
understand this topic. You know a whole lot its almost hard to argue with you (not
that I actually will need to…HaHa). You certainly put a brand new spin on a
subject that’s been discussed for decades. Great stuff, just great!
http://routego.ru.com
21 Aug 25 at 2:18 pm
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Ознакомьтесь с аналитикой – http://globalcolor.cl/reinterprets-the-classic-bookshelf
DavidMon
21 Aug 25 at 2:21 pm
трансформаторные подстанции 2ктп [url=http://www.transformatornye-podstancii-kupit2.ru]трансформаторные подстанции 2ктп[/url] .
transformatornie podstancii kypit_mzoi
21 Aug 25 at 2:21 pm
https://wanderlog.com/view/blbnowxgid/купить-экстази-кокаин-амфетамин-лилль/shared
Eugeneimatt
21 Aug 25 at 2:24 pm
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Ознакомьтесь с аналитикой – http://ecdqemsd.com/dia-1-esperando-la-nueva-temporada-ecdqemsd-xiii
Ricardounuse
21 Aug 25 at 2:24 pm
SildenaPeak: SildenaPeak – SildenaPeak
RichardTit
21 Aug 25 at 2:26 pm
купить свидетельство о разводе киев [url=https://educ-ua5.ru]https://educ-ua5.ru[/url] .
Diplomi_qdKl
21 Aug 25 at 2:29 pm
https://sildenapeak.shop/# SildenaPeak
Danielchumn
21 Aug 25 at 2:32 pm
аттестат за 11 класс купить в чите [url=https://arus-diplom9.ru]аттестат за 11 класс купить в чите[/url] .
Diplomi_siEi
21 Aug 25 at 2:34 pm
order cheap dapsone without rx
how to buy cheap dapsone
21 Aug 25 at 2:36 pm
трансформаторная подстанция цена [url=https://transformatornye-podstancii-kupit1.ru]трансформаторная подстанция цена[/url] .
transformatornie podstancii kypit_epor
21 Aug 25 at 2:37 pm
Online sources for Kamagra in the United States: Compare Kamagra with branded alternatives – ED treatment without doctor visits
RichardTit
21 Aug 25 at 2:42 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Узнать напрямую – http://marketingehoneonline.cf/post/34
DavidMon
21 Aug 25 at 2:43 pm
прогноз ставок на хоккей [url=http://prognozy-na-khokkej.ru]http://prognozy-na-khokkej.ru[/url] .
prognozi na hokkei_duPr
21 Aug 25 at 2:43 pm
Hi to every one, it’s genuinely a fastidious for me to pay
a visit this web page, it consists of valuable Information.
bot88
21 Aug 25 at 2:44 pm
купить аттестат 11 класса отзывы [url=www.arus-diplom23.ru]www.arus-diplom23.ru[/url] .
Diplomi_trol
21 Aug 25 at 2:45 pm
https://kemono.im/eogeofafzge/trnava-kupit-gashish-boshki-marikhuanu
Eugeneimatt
21 Aug 25 at 2:45 pm
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Изучить вопрос глубже – https://www.takatsukihome.jp/104
Ricardounuse
21 Aug 25 at 2:46 pm
I am sure this paragraph has touched all the internet visitors, its really really nice piece of writing on building up new weblog.
thưởng thức truyện người lớn 2025
21 Aug 25 at 2:49 pm