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!
Charleston Car Accident Lawyer: Your Advocate After a Crash
Car accidents can change your life in an instant—leaving you
with physical injuries, emotional trauma, and overwhelming financial burdens.
If you’ve been injured in a car wreck in Charleston, South Carolina, you don’t have to face the aftermath alone.
A skilled Charleston car accident lawyer
can help you fight for the compensation you deserve and guide you through every step of the legal process.
Why Hire a Charleston Car Accident Attorney?
Whether it was a minor fender-bender or a catastrophic collision, dealing with insurance companies can be exhausting.
They may try to minimize your claim or deny it altogether.
A knowledgeable personal injury attorney in Charleston will:
Investigate the accident scene
Gather evidence such as traffic cam footage and witness statements
Handle all communication with insurance adjusters
Calculate damages for medical bills, lost wages, pain and
suffering, and more
Represent you in court if a fair settlement cannot be reached
I have been surfing online more than 4 hours today,
yet I never found any interesting article
like yours. It is pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the web will be much more useful than ever before.
What Makes Charleston Unique for Car Accident Claims?
Charleston’s historic roads and growing population lead to a unique mix of traffic challenges.
From the Ravenel Bridge to busy intersections downtown, collisions happen every day.
South Carolina law allows injured victims to pursue compensation—but strict deadlines apply.
This is why hiring a local car accident lawyer with experience in Charleston’s courts is critical.
I couldn’t refrain from commenting. Well written!
Common Injuries from Car Accidents
Auto accidents can cause both visible and invisible injuries,
such as:
Whiplash and neck trauma
Concussions or traumatic brain injuries (TBI)
Broken bones
Back and spinal cord injuries
Emotional distress or PTSD
Even if your injuries seem minor, it’s important to seek medical
attention and consult a legal professional. A Charleston car accident attorney will work to ensure every aspect of your recovery is accounted for.
I’ll immediately take hold of your rss feed as I can not in finding
your email subscription link or e-newsletter
service. Do you’ve any? Kindly permit me recognize in order that I may
just subscribe. Thanks.
Contact a Trusted Charleston Car Accident Lawyer Today
If you or a loved one has been involved in a car accident in Charleston, don’t wait.
Reach out to a qualified personal injury attorney today to schedule a free consultation. Many car accident lawyers work on a contingency fee basis—meaning you
pay nothing unless they win your case.
Let a local legal team take the pressure off your shoulders and
fight for the justice you deserve.
Charleston Personal Injury Lawyer
14 Oct 25 at 6:43 pm
купить диплом в пскове [url=http://rudik-diplom9.ru/]купить диплом в пскове[/url] .
Diplomi_jfei
14 Oct 25 at 6:44 pm
электрокарнизы для штор купить в москве [url=https://elektrokarnizy797.ru]https://elektrokarnizy797.ru[/url] .
elektrokarnizi_xbMl
14 Oct 25 at 6:45 pm
We’re a gaggle of volunteers and opening a brand
new scheme in our community. Your web site provided us with helpful info
to work on. You’ve done an impressive activity and our whole community will likely be thankful to you.
situs scam
14 Oct 25 at 6:46 pm
купить диплом в кстово [url=http://www.rudik-diplom15.ru]http://www.rudik-diplom15.ru[/url] .
Diplomi_owPi
14 Oct 25 at 6:47 pm
перепланировка нежилого здания [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка нежилого здания[/url] .
pereplanirovka nejilogo pomesheniya_wbKl
14 Oct 25 at 6:49 pm
Estou completamente apaixonado por PlayPIX Casino, proporciona uma aventura pulsante. O catalogo e exuberante e multifacetado, com slots de design inovador. Com uma oferta inicial para impulsionar. O suporte ao cliente e excepcional, acessivel a qualquer momento. O processo e simples e elegante, as vezes bonus mais variados seriam incriveis. No fim, PlayPIX Casino e essencial para jogadores para entusiastas de jogos modernos ! Acrescentando que o design e moderno e vibrante, adiciona um toque de conforto. Outro destaque o programa VIP com niveis exclusivos, assegura transacoes confiaveis.
Descobrir mais|
BlazeRhythmQ6zef
14 Oct 25 at 6:49 pm
абонемент в фитнес клуб абонемент в фитнес клуб
fitnes-klub-523
14 Oct 25 at 6:50 pm
потолочкин отзывы клиентов самара [url=natyazhnye-potolki-samara-2.ru]natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_nqPi
14 Oct 25 at 6:51 pm
Why viewers still make use of to read news papers when in this technological
globe the whole thing is accessible on web?
Highcliff Gainetra
14 Oct 25 at 6:53 pm
потолочкин отзывы клиентов самара [url=www.stretch-ceilings-samara-1.ru/]www.stretch-ceilings-samara-1.ru/[/url] .
natyajnie potolki samara_mvsl
14 Oct 25 at 6:55 pm
потолочкин натяжные потолки самара отзывы [url=http://www.natyazhnye-potolki-samara-2.ru]http://www.natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_lrPi
14 Oct 25 at 6:57 pm
согласование перепланировки нежилого помещения в москве [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_mcKl
14 Oct 25 at 6:57 pm
купить диплом в ангарске [url=https://rudik-diplom9.ru/]купить диплом в ангарске[/url] .
Diplomi_bgei
14 Oct 25 at 6:58 pm
https://forum.awd.ru/viewtopic.php?f=69&t=110073&start=300#p11319299
Nathanhip
14 Oct 25 at 6:58 pm
карнизы с электроприводом купить [url=https://www.elektrokarnizy797.ru]карнизы с электроприводом купить[/url] .
elektrokarnizi_dfMl
14 Oct 25 at 6:59 pm
согласование перепланировки нежилого помещения в москве [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]http://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_dnKl
14 Oct 25 at 6:59 pm
Thanks for the marvelous posting! I really enjoyed reading it, you are a great author.
I will be sure to bookmark your blog and will eventually come back very
soon. I want to encourage you to continue your great posts, have a nice weekend!
powerful business examples
14 Oct 25 at 7:04 pm
купить диплом механика [url=www.rudik-diplom15.ru]купить диплом механика[/url] .
Diplomi_mjPi
14 Oct 25 at 7:05 pm
https://my.archdaily.com/us/@free-spins-no-deposit-india
pjvefgc
14 Oct 25 at 7:06 pm
электрокарнизы [url=elektrokarnizy797.ru]электрокарнизы[/url] .
elektrokarnizi_goMl
14 Oct 25 at 7:07 pm
Wow that was strange. I just wrote an really long comment but after I clicked submit my comment didn’t
appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say fantastic blog!
bokep SMA
14 Oct 25 at 7:08 pm
Сегодня мы отправимся на виртуальную экскурсию в уникальные уголки природы России.
Зацепил материал про Изучение ООПТ России: парки, заповедники, водоемы.
Вот, делюсь ссылкой:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
14 Oct 25 at 7:08 pm
I do not even know how I ended up here, but I thought this post was great.
I do not know who you are but definitely you’re going to a
famous blogger if you aren’t already 😉 Cheers!
pepek
14 Oct 25 at 7:09 pm
потолки [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_bvor
14 Oct 25 at 7:09 pm
потолочник натяжные потолки самара [url=http://www.stretch-ceilings-samara.ru]http://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_tukl
14 Oct 25 at 7:10 pm
online sportwetten ohne lugas
Also visit my web-site – Wetten öSterreich
Wetten öSterreich
14 Oct 25 at 7:10 pm
перепланировка нежилого помещения в многоквартирном доме [url=pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка нежилого помещения в многоквартирном доме[/url] .
pereplanirovka nejilogo pomesheniya_bgKl
14 Oct 25 at 7:11 pm
потолочкин натяжные потолки отзывы клиентов самара [url=https://natyazhnye-potolki-samara-1.ru/]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_zyor
14 Oct 25 at 7:12 pm
$MTAUR coin stands out with its audited security focus. Extending vesting for bonuses is a no-brainer. Maze battles against creatures? Count me in. minotaurus token
WilliamPargy
14 Oct 25 at 7:12 pm
potolochkin ru [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_hwkl
14 Oct 25 at 7:13 pm
Правильный подбор лекарственных средств позволяет не только уменьшить проявления синдрома отмены, но и стабилизировать эмоциональное состояние пациента, снижая риск срывов. Реабилитационные программы включают физиотерапию, спортивные занятия и коррекцию образа жизни, что способствует полноценному восстановлению организма.
Ознакомиться с деталями – [url=https://lechenie-narkomanii-tver0.ru/]принудительное лечение наркомании тверь[/url]
MatthewNoG
14 Oct 25 at 7:13 pm
Attractive section of content. I just stumbled
upon your web site and in accession capital to assert that I get
in fact enjoyed account your blog posts. Any way I’ll be subscribing
to your augment and even I achievement you access
consistently fast.
useful source
14 Oct 25 at 7:15 pm
Наркологическая клиника в Твери представляет собой современное медицинское учреждение, специализирующееся на диагностике и лечении алкогольной, наркотической и других видов зависимости. В клинике «Гелиос» применяются инновационные методы терапии, направленные на полное восстановление физического и психологического состояния пациентов.
Выяснить больше – https://narkologicheskaya-klinika-tver0.ru/narkolog-tver-anonimno/
Briangaw
14 Oct 25 at 7:16 pm
диплом техникума купить киев [url=https://www.frei-diplom11.ru]диплом техникума купить киев[/url] .
Diplomi_wwsa
14 Oct 25 at 7:18 pm
Hey there! Do you use Twitter? I’d like to follow you if that would
be ok. I’m definitely enjoying your blog and look
forward to new updates.
DynarisFlex 7 1 Ai
14 Oct 25 at 7:20 pm
самара натяжные потолки [url=https://natyazhnye-potolki-samara-2.ru]самара натяжные потолки[/url] .
natyajnie potolki samara_tqPi
14 Oct 25 at 7:20 pm
электрокарниз двухрядный цена [url=www.elektrokarnizy797.ru/]www.elektrokarnizy797.ru/[/url] .
elektrokarnizi_nyMl
14 Oct 25 at 7:21 pm
согласование перепланировки в нежилом помещении [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .
pereplanirovka nejilogo pomesheniya_tbKl
14 Oct 25 at 7:22 pm
sportwetten online wetten mit paysafecard (vegasdombankietowy.pl) bonus ohne einzahlung
vegasdombankietowy.pl
14 Oct 25 at 7:23 pm
купить диплом машиниста [url=http://rudik-diplom14.ru/]купить диплом машиниста[/url] .
Diplomi_alea
14 Oct 25 at 7:27 pm
Для купирования абстинентного синдрома и нормализации функций организма применяются препараты, которые оказывают детоксицирующее, нейропротекторное и общеукрепляющее действие. Врач подбирает лекарства индивидуально с учетом состояния пациента и наличия сопутствующих заболеваний.
Получить больше информации – [url=https://narkologicheskaya-klinika-vladimir0.ru/]наркологические клиники алкоголизм владимир[/url]
Jaimenef
14 Oct 25 at 7:28 pm
цены на натяжные потолки в самаре [url=www.natyazhnye-potolki-samara-1.ru/]www.natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_asor
14 Oct 25 at 7:28 pm
Good day! This post could not be written any better! Reading through
this post reminds me of my previous room mate! He always kept chatting about this.
I will forward this article to him. Fairly
certain he will have a good read. Many thanks for sharing!
toto
14 Oct 25 at 7:29 pm
Hello my loved one! I want to say that this post is awesome, great written and include approximately all vital infos.
I’d like to look extra posts like this .
Click here
14 Oct 25 at 7:29 pm
перепланировка нежилых помещений [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru/]перепланировка нежилых помещений[/url] .
pereplanirovka nejilogo pomesheniya_sdKl
14 Oct 25 at 7:29 pm
самара натяжные потолки [url=https://natyazhnye-potolki-samara-2.ru]самара натяжные потолки[/url] .
natyajnie potolki samara_ogPi
14 Oct 25 at 7:31 pm
женский фитнес клуб сеть фитнес клубов
fitnes-klub-754
14 Oct 25 at 7:32 pm
https://vremya.press/10-samyh-bjudzhetnyh-gornolyzhnyh-kurortov-rossii/
Nathanhip
14 Oct 25 at 7:33 pm
https://ibb.co.com/6Qct2Sg
equgcwo
14 Oct 25 at 7:34 pm