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!
makeevkatop.ru
JacobNit
13 Aug 25 at 10:51 am
dragon money
MichaelTut
13 Aug 25 at 10:51 am
В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
Как достичь результата? – http://pintubahasa.com/group2/2022/02/01/how-to-maintain-a-successful-long-distance-relationship
Jasonrhini
13 Aug 25 at 10:51 am
В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
Практические советы ждут тебя – https://humanityfreedom.info/heilmittel-gegen-krebs-sauerstoffwasser
Jasonrhini
13 Aug 25 at 10:53 am
Wonderful goods from you, man. I have have in mind your stuff prior to and you are simply extremely magnificent.
I actually like what you’ve acquired right
here, certainly like what you are stating and the
best way wherein you are saying it. You make it entertaining and you still care for to stay it sensible.
I cant wait to read much more from you. That is actually a wonderful site.
риск-от-вируси-в-libgen-колко-безопасен-е-library-genesis-и-може-ли-да-хванете-вируси-от-libgen-през-2025
13 Aug 25 at 10:54 am
Good roundup. I grabbed Ice Berry from them and it’s frosty af.
who sells weed clones near me
13 Aug 25 at 10:57 am
1х зеркало [url=1win1168.ru]1win1168.ru[/url]
1win_epma
13 Aug 25 at 10:57 am
My spouse and I stumbled over here coming from a different website and thought I may as
well check things out. I like what I see so i am just following you.
Look forward to checking out your web page repeatedly.
daname bonasa voren sotelir
13 Aug 25 at 11:02 am
https://dimonvideo.ru/0/name/Buguxuwen
https://dimonvideo.ru/0/name/Buguxuwen
13 Aug 25 at 11:02 am
https://24x7fm.com/a-casino-verde-bonus-alapos-vizsgalata-jo/
Robertpef
13 Aug 25 at 11:04 am
https://volnovaxaber.ru
CharlesVaX
13 Aug 25 at 11:05 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Погрузиться в детали – http://tacsapka.com/product/soloturk-serit-rozeti
Alvinbounk
13 Aug 25 at 11:07 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Получить исчерпывающие сведения – https://mega-cul.com/index.php/2024/07/22/bonjour-tout-le-monde
Alvinbounk
13 Aug 25 at 11:10 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Узнать напрямую – https://henryukazu.com/dare-to-succeed-2
Josephsib
13 Aug 25 at 11:10 am
1win официальный сайт [url=www.1win1170.ru]1win официальный сайт[/url]
1win_kg_lqEr
13 Aug 25 at 11:11 am
Can I just say what a relief to find someone that really understands
what they’re discussing on the web. You definitely know how to bring an issue to
light and make it important. More people should look at this and
understand this side of the story. I was surprised
that you’re not more popular given that you surely have the gift.
شرایط ورود به دانشگاه افسری نیروی انتظامی ۱۴۰۴
13 Aug 25 at 11:12 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Не упусти важное! – https://www.burg-posterstein.de/blog-2/?lang=fr
Lanceinduh
13 Aug 25 at 11:12 am
For the reason that the admin of this web page is working, no uncertainty very soon it will be well-known, due to its quality contents.
Наземное исполнение очистных сооружений промышленных стоков
ShaneDrync
13 Aug 25 at 11:13 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Подробная информация доступна по запросу – https://reyhaneco.ir/product/golbarg-girl
MauriceEvila
13 Aug 25 at 11:17 am
https://debaltsevoty.ru
CharlesVaX
13 Aug 25 at 11:26 am
Pretty section of content. I just stumbled upon your site and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.
Блочно-модульны очистные сооружения
LewisGuatt
13 Aug 25 at 11:26 am
enakievoler.ru
JacobNit
13 Aug 25 at 11:26 am
Indian Meds One: Indian Meds One – top online pharmacy india
JamesHeelo
13 Aug 25 at 11:28 am
Приветствую всех форумчан! Хочу поделиться своим опытом использования топливных карт. Возможно, кому-то мой отзыв окажется полезным.
Раньше, как и многие, я тратил уйму времени на сбор чеков, составление отчетов и постоянные подсчеты. Бензин то дорожал, то дешевел, а бухгалтер, мягко говоря, не был в восторге от кипы бумажек, которые я приносил.- [url=https://vybratauto.ru/]топливные карты для юридических лиц[/url]
ShawnSlurf
13 Aug 25 at 11:33 am
Уверен, эта информация будет для вас полезна:
Особенно понравился материал про mersobratva.ru.
Смотрите сами:
[url=https://mersobratva.ru]https://mersobratva.ru[/url]
Буду признателен за ваши отзывы.
rusPoito
13 Aug 25 at 11:33 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Узнать напрямую – https://espigaoalerta.com.br/2024/08/18/domingo-maior-exibe-hoje-18-08-na-globo-kingsman-servico-secreto
JoshuaVat
13 Aug 25 at 11:35 am
I am really grateful to the owner of this website who has shared this fantastic post
at at this time.
My site; solar panel cost
solar panel cost
13 Aug 25 at 11:36 am
Hey there! Do you use Twitter? I’d like to follow you if that would be okay. I’m definitely enjoying your blog and look forward to new updates.
лучшие турецкие ткани
EarnestAbent
13 Aug 25 at 11:41 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Разобраться лучше – https://editssc.com/social-security-card-full-guideline
Lanceinduh
13 Aug 25 at 11:41 am
Indian Meds One: best online pharmacy india – indian pharmacy
JamesHeelo
13 Aug 25 at 11:46 am
I really like reading through a post that can make men and women think.
Also, thanks for allowing for me to comment!
Radiation therapy children
13 Aug 25 at 11:50 am
Thanks for any other great post. The place else could anyone get that kind of information in such a perfect manner of writing? I have a presentation next week, and I am on the look for such info.
турецкие фабрики ткани
EarnestAbent
13 Aug 25 at 11:52 am
https://alpostogiustovarese.it/2025/07/21/verde-casino-login-la-tua-destinazione-principale/
Robertpef
13 Aug 25 at 11:56 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Заходи — там интересно – https://www.drshashankgupta.com/2020/07/17/mother-to-son-kidney-transplant
JesseBeaug
13 Aug 25 at 11:57 am
https://beteiligung.stadtlindau.de/profile/%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%AD%D0%BA%D1%81%D1%82%D0%B0%D0%B7%D0%B8%20%D0%9C%D0%94%D0%9C%D0%90%20%D0%9A%D0%BE%D0%BA%D0%B0%D0%B8%D0%BD%20%D0%A0%D0%B5%D0%B9%D0%BC%D1%81/
Thomasmub
13 Aug 25 at 11:58 am
Today, I went to the beachfront with my kids. 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 placed 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 completely off topic but I had to
tell someone!
roofers company near me
13 Aug 25 at 12:01 pm
Преимущество
Углубиться в тему – http://snyatie-lomki-rnd7.ru
BrianHeady
13 Aug 25 at 12:01 pm
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Узнай первым! – https://abogadosoax.com/?attachment_id=15
JesseBeaug
13 Aug 25 at 12:02 pm
Hi there to every , because I am actually keen of reading this web site’s post to be updated regularly.
It carries pleasant data.
Renew & Restore pressure washing near me
13 Aug 25 at 12:03 pm
В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
Уточнить детали – https://www.solni.pl/2024/05/16/witaj-swiecie
MichaelEpipt
13 Aug 25 at 12:05 pm
1вин бет ставки [url=1win1169.ru]1win1169.ru[/url]
1win_kg_bbpn
13 Aug 25 at 12:06 pm
I don’t know whether it’s just me or if everybody else encountering problems with your website.
It appears like some of the text within your posts
are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them too?
This may be a issue with my internet browser because I’ve had this happen previously.
Kudos
Here is my web site … Zipline Rental Phoenix
Zipline Rental Phoenix
13 Aug 25 at 12:07 pm
экскурсии казань
BennieSiz
13 Aug 25 at 12:09 pm
онлайн ставки на спорт с выводом денег [url=www.1win1168.ru]www.1win1168.ru[/url]
1win_vuma
13 Aug 25 at 12:10 pm
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Погрузиться в детали – https://hikayetna.com/from-stigma-to-support-why-arabic-mental-health-education-is-vital
BrianStymn
13 Aug 25 at 12:11 pm
1win mobile [url=https://www.1win1168.ru]https://www.1win1168.ru[/url]
1win_wyma
13 Aug 25 at 12:12 pm
https://www.metooo.io/u/68988e354027b05a0263dd1b
Thomasmub
13 Aug 25 at 12:17 pm
Indian Meds One: Indian Meds One – top 10 online pharmacy in india
RoccoaritA
13 Aug 25 at 12:17 pm
В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
Нажми и узнай всё – https://millesimeworld.com/blog/gourmet/despensa-natural
MichaelEpipt
13 Aug 25 at 12:18 pm
navarro pharmacy miami: propranolol online pharmacy – MediDirect USA
Justinsoync
13 Aug 25 at 12:18 pm