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://avtomobilist.kyiv.ua всё об автомобилях: новые модели, цены, рынок подержанных авто, тюнинг и автотехнологии. Полезные материалы для автовладельцев.
Ronaldhoard
19 Aug 25 at 9:53 am
Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий!
Узнать из первых рук – https://www.ankaramerdiven.com/hello-world
MyronTrasE
19 Aug 25 at 9:54 am
https://krakencasinotr.com/
Pierrequade
19 Aug 25 at 9:54 am
Онлайн авто-журнал https://mirauto.kyiv.ua с актуальными новостями, аналитикой и обзорами. Тесты автомобилей, тюнинг, технологии и советы по эксплуатации.
JamesNUT
19 Aug 25 at 9:55 am
диплом с внесением в реестр купить [url=http://arus-diplom35.ru]диплом с внесением в реестр купить[/url] .
Priobresti diplom instityta!_msot
19 Aug 25 at 9:56 am
Great web site you’ve got here.. It’s difficult to find good quality writing like yours these days.
I seriously appreciate people like you! Take care!!
با تراز ۵۵۰۰ انسانی چی قبول میشم
19 Aug 25 at 9:57 am
What we’re covering
• Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said 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://kra36at.com]kra34 at[/url]
• Potential security guarantees: At last week’s summit with Trump, Russian 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://kra-37cc.net]kra35 СЃСЃ[/url]
• On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
kra37
https://kra38cc.com
JorgeKesia
19 Aug 25 at 9:57 am
https://pxlmo.com/Magguytenn1cezxw
WilliamTop
19 Aug 25 at 9:58 am
What we’re covering
• Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said 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://kra33cc.net]kra32 СЃСЃ[/url]
• Potential security guarantees: At last week’s summit with Trump, Russian 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://kra36-at.cc]kra30 СЃСЃ[/url]
• On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
kra38 cc
https://kraken35at.com
Francisrob
19 Aug 25 at 9:59 am
Авто портал https://avtomobilist.kyiv.ua всё об автомобилях: новые модели, цены, рынок подержанных авто, тюнинг и автотехнологии. Полезные материалы для автовладельцев.
Ronaldhoard
19 Aug 25 at 10:00 am
We stumbled over here by a different page and thought I might check things out.
I like what I see so i am just following you. Look forward to looking over your web page yet again.
Gunst Bitmark
19 Aug 25 at 10:00 am
Онлайн авто-журнал https://mirauto.kyiv.ua с актуальными новостями, аналитикой и обзорами. Тесты автомобилей, тюнинг, технологии и советы по эксплуатации.
JamesNUT
19 Aug 25 at 10:02 am
Because the admin of this web page is working, no question very shortly it will be renowned,
due to its quality contents.
MonitrexPRO
19 Aug 25 at 10:06 am
Мужской портал https://hooligans.org.ua новости, лайфхаки, обзоры техники, спорт, здоровье и авто. Советы для уверенной и гармоничной жизни.
Robertinody
19 Aug 25 at 10:08 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Более того — здесь – https://tecla.com.ar/impresora-hp-tintas-latex
JamesTup
19 Aug 25 at 10:08 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Обратиться к источнику – https://www.badmintonclubtotes.fr/2024/08/26/forum-des-associations-5
EdwinWep
19 Aug 25 at 10:08 am
аттестат за 11 класс 2013 купить [url=http://arus-diplom22.ru]аттестат за 11 класс 2013 купить[/url] .
Diplomi_vdsl
19 Aug 25 at 10:10 am
Looking for betandreas aviator? Betandreas-official.com is a huge selection of online games. Here you will find a welcome bonus! On our portal you can learn more about BetAndreas: how to top up your balance and withdraw money, how to download and register a mobile application, as well as what games and slots there are. Get full instructions on how to enter the site. We have the best casino games in Bangladesh!
xatufgom
19 Aug 25 at 10:10 am
купить аттестат 11 классов в москве [url=arus-diplom25.ru]купить аттестат 11 классов в москве[/url] .
Diplomi_ocot
19 Aug 25 at 10:10 am
Мужской портал https://hooligans.org.ua новости, лайфхаки, обзоры техники, спорт, здоровье и авто. Советы для уверенной и гармоничной жизни.
Robertinody
19 Aug 25 at 10:15 am
This information is worth everyone’s attention. When can I find out more?
23winfishing
19 Aug 25 at 10:15 am
купить аттестат за 11 класс омск [url=www.arus-diplom23.ru]www.arus-diplom23.ru[/url] .
Diplomi_vjol
19 Aug 25 at 10:15 am
https://www.metooo.io/u/689e41fc01467f15827828ff
WilliamTop
19 Aug 25 at 10:19 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Это стоит прочитать полностью – https://sreetravels.online/nature-holiday-quotes
Juliusquied
19 Aug 25 at 10:20 am
купить диплом в уфе с реестром [url=www.arus-diplom35.ru]www.arus-diplom35.ru[/url] .
Zakazat diplom yniversiteta!_otot
19 Aug 25 at 10:20 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Погрузиться в научную дискуссию – https://www.africopanigeria.com/standard-image-post
Juliusquied
19 Aug 25 at 10:23 am
https://tadalify.shop/# cialis or levitra
Danielchumn
19 Aug 25 at 10:23 am
купить аттестаты за 11 класс в томске [url=www.arus-diplom23.ru/]www.arus-diplom23.ru/[/url] .
Diplomi_oool
19 Aug 25 at 10:23 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Секреты успеха внутри – http://www.brambillacarlocenter.com/news/prova-news
MyronTrasE
19 Aug 25 at 10:24 am
где купить диплом с занесением реестр [url=arus-diplom35.ru]где купить диплом с занесением реестр[/url] .
Kypit diplom lubogo VYZa!_kqot
19 Aug 25 at 10:26 am
When someone writes an paragraph he/she maintains the
thought of a user in his/her mind that how a user can know it.
Thus that’s why this post is perfect. Thanks!
roof repair services
19 Aug 25 at 10:27 am
I have been surfing on-line greater than three hours
as of late, yet I by no means found any interesting article like yours.
It’s pretty value enough for me. In my opinion, if all site owners and bloggers made excellent content material as you probably
did, the internet can be much more useful than ever before.
Hand-painted murals Houston
19 Aug 25 at 10:27 am
First off I would like to say terrific blog!
I had a quick question that I’d like to ask if you don’t
mind. I was curious to find out how you center yourself and clear your mind
prior to writing. I’ve had a difficult time clearing my thoughts in getting my ideas out.
I do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to be wasted
simply just trying to figure out how to begin. Any suggestions or hints?
Cheers!
با تراز 4000 انسانی کجا قبول میشم نی نی سایت
19 Aug 25 at 10:27 am
Turkce blackjack siteleri
Pierrequade
19 Aug 25 at 10:28 am
First of all I would like to say wonderful blog! I had a quick question that I’d like to ask if you don’t mind.
I was interested to know how you center yourself and clear your mind prior to writing.
I’ve had trouble clearing my thoughts in getting my thoughts out.
I truly do enjoy writing but it just seems like the
first 10 to 15 minutes are usually lost simply just
trying to figure out how to begin. Any suggestions or tips?
Cheers!
اطلاعیه اعلام نتایج پذیرفته شدگان نهایی آزمون اختصاصی پذیرش دانشجو ۱۴۰۴
19 Aug 25 at 10:28 am
https://rant.li/eggpydaiefe/denpasar-bali-kupit-gashish-boshki-marikhuanu
Danielevemy
19 Aug 25 at 10:30 am
Very descriptive blog, I enjoyed that bit.
Will there be a part 2?
togel88 link
19 Aug 25 at 10:33 am
провайдеры интернета казань
kazan-domashnij-internet004.ru
интернет провайдер казань
internetelini
19 Aug 25 at 10:34 am
как купить официальный аттестат 11 класс [url=http://arus-diplom22.ru/]как купить официальный аттестат 11 класс[/url] .
Diplomi_ogsl
19 Aug 25 at 10:35 am
купить аттестат за 11 класс уфа [url=http://arus-diplom25.ru/]купить аттестат за 11 класс уфа[/url] .
Diplomi_ogot
19 Aug 25 at 10:36 am
Hey! This post couldn’t be written any better!
Reading through this post reminds me of my previous room mate!
He always kept talking about this. I will forward
this article to him. Pretty sure he will have a good read.
Many thanks for sharing!
Quantum Anwar
19 Aug 25 at 10:36 am
Good day! I just would like to offer you a huge thumbs up for
your excellent information you’ve got here on this post.
I will be returning to your web site for more soon.
abc investissement
19 Aug 25 at 10:39 am
сантехника gessi [url=https://www.gessi-santehnika-5.ru]сантехника gessi[/url] .
gessi santehnika_jsoa
19 Aug 25 at 10:39 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Выяснить больше – https://adverttv.ru/?paged=33
Kevincef
19 Aug 25 at 10:40 am
https://odysee.com/@bhoplezlitak
WilliamTop
19 Aug 25 at 10:40 am
Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
Открыть полностью – https://spotifybrasil.com.br/yoga-poses-for-back-pain
LoganAlics
19 Aug 25 at 10:41 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Только для своих – https://kansara.org/happy-birthday-k
LoganAlics
19 Aug 25 at 10:44 am
You really make it seem so easy with your presentation but I find
this topic to be actually something that I think I would never understand.
It seems too complex and extremely broad for me. I’m looking forward for your next
post, I will try to get the hang of it!
Website
19 Aug 25 at 10:44 am
I enjoy reading through a post that can make men and women think.
Also, many thanks for permitting me to comment!
macauslot88 link
19 Aug 25 at 10:49 am
Medicament information. Effects of Drug Abuse.
buy fluvoxamine without dr prescription
Everything information about meds. Get now.
buy fluvoxamine without dr prescription
19 Aug 25 at 10:51 am