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!
купить диплом в реестр [url=https://arus-diplom34.ru]купить диплом в реестр[/url] .
Diplomi_kter
11 Sep 25 at 4:54 pm
Acho simplesmente insano OshCasino, da uma energia de cassino que e um terremoto. Os titulos do cassino sao um espetaculo vulcanico, oferecendo sessoes de cassino ao vivo que sao uma chama. A equipe do cassino entrega um atendimento que e uma labareda, acessivel por chat ou e-mail. Os pagamentos do cassino sao lisos e blindados, as vezes mais recompensas no cassino seriam um diferencial vulcanico. No fim das contas, OshCasino garante uma diversao de cassino que e um vulcao para os cacadores de slots modernos de cassino! Vale falar tambem a plataforma do cassino detona com um visual que e puro magma, o que deixa cada sessao de cassino ainda mais incendiaria.
osh.|
zestylizard7zef
11 Sep 25 at 4:54 pm
Unquestionably believe that which you stated.
Your favorite reason seemed to be on the web
the easiest thing to be aware of. I say to you, I
certainly get irked while people think about worries that they plainly don’t know about.
You managed to hit the nail upon the top and also defined out the
whole thing without having side-effects , people can take a signal.
Will likely be back to get more. Thanks
Geltipatmex
11 Sep 25 at 4:56 pm
разработка проекта перепланировки [url=https://www.proekt-pereplanirovki-kvartiry8.ru]разработка проекта перепланировки[/url] .
proekt pereplanirovki kvartiri_vyMl
11 Sep 25 at 4:56 pm
прогноз курса доллара на месяц
JoshuaSew
11 Sep 25 at 4:56 pm
авиатор 1win играть [url=http://www.aviator-igra-2.ru]авиатор 1win играть[/url] .
aviator igra_lsol
11 Sep 25 at 4:57 pm
Да, многие клиники выезжают в Ленинградскую область — в радиусе 50–100 км от Санкт-Петербурга. Время прибытия согласуется при обращении.
Получить больше информации – [url=https://narko-zakodirovan.ru/]вывод из запоя на дому круглосуточно санкт-петербург[/url]
Kevingon
11 Sep 25 at 4:57 pm
Heya just wanted to give you a brief heads up and let you know
a few of the images aren’t loading correctly. I’m not sure why
but I think its a linking issue. I’ve tried it
in two different internet browsers and both show the same outcome.
local sewer line repair
11 Sep 25 at 4:59 pm
Идеален для пациентов со средней степенью интоксикации, не требующих круглосуточного мониторинга. Данная схема позволяет:
Подробнее – https://nadezhnyj-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-kapelnicza-spb
WilliamPoinc
11 Sep 25 at 5:00 pm
перепланировка квартиры стоимость [url=http://proekt-pereplanirovki-kvartiry8.ru/]перепланировка квартиры стоимость[/url] .
proekt pereplanirovki kvartiri_krMl
11 Sep 25 at 5:01 pm
круглосуточный вывод из запоя
vivodzapojtulaNeT
11 Sep 25 at 5:02 pm
https://webyourself.eu/forums/thread/39839/Forex-sa-Pilipinas-ano-talaga-ang-mahalaga-bago-pumili-ng
Danielwef
11 Sep 25 at 5:02 pm
aviator money game [url=https://www.aviator-igra-2.ru]https://www.aviator-igra-2.ru[/url] .
aviator igra_wtol
11 Sep 25 at 5:03 pm
я стобой солидарен!
РўРћРџ ПРОДАЖР24/7 – РџР РОБРЕСТРMEF ALFA BOSHK1
Заказ пришёл, все ровно)
Richardmog
11 Sep 25 at 5:03 pm
Always relevant here: https://penzo.cz
KevinTum
11 Sep 25 at 5:03 pm
Catch the latest from us: https://chhapai.com
Terryswori
11 Sep 25 at 5:04 pm
Наши специалисты всегда относятся к пациентам с уважением и вниманием, создавая атмосферу доверия и поддержки. Они проводят всестороннее обследование, выявляют причины зависимости и разрабатывают индивидуальные стратегии лечения. Профессионализм и компетентность врачей являются основой успешного восстановления наших пациентов.
Выяснить больше – http://срочно-вывод-из-запоя.рф/
FrankJEK
11 Sep 25 at 5:05 pm
Ich finde absolut uberwaltigend Platin Casino, es bietet ein Casino-Abenteuer, das wie ein Schatz funkelt. Die Casino-Optionen sind vielfaltig und glanzvoll, mit Live-Casino-Sessions, die wie ein Diamant leuchten. Der Casino-Kundenservice ist wie ein glanzender Edelstein, antwortet blitzschnell wie ein geschliffener Diamant. Casino-Gewinne kommen wie ein Blitz, dennoch mehr Casino-Belohnungen waren ein glitzernder Gewinn. Am Ende ist Platin Casino ein Casino, das man nicht verpassen darf fur Spieler, die auf luxuriose Casino-Kicks stehen! Und au?erdem das Casino-Design ist ein optischer Schatz, was jede Casino-Session noch glanzvoller macht.
platin casino juegos|
sparklynewt6zef
11 Sep 25 at 5:05 pm
Everything new is nearby: https://jnp.chitkara.edu.in
Travispig
11 Sep 25 at 5:06 pm
I’m really inspired along with your writing abilities as smartly as
with the layout to your weblog. Is that this a paid subject or did
you modify it yourself? Anyway keep up the nice high quality writing, it’s uncommon to look a nice weblog like this one nowadays..
Valentinstag Sprüche
11 Sep 25 at 5:08 pm
darknet site best darknet markets dark market link [url=https://darkmarketgate.com/ ]nexus shop [/url]
Donaldfup
11 Sep 25 at 5:10 pm
Индивидуальный подход к каждому пациенту. Каждый случай уникален, поэтому мы разрабатываем персонализированные программы, учитывающие особенности каждого человека.
Выяснить больше – [url=https://narko-zakodirovat.ru/]вывод из запоя клиника в твери[/url]
Larryhip
11 Sep 25 at 5:11 pm
Сайт finance-post.ru — это блог финансиста, ориентированный на личные финансы, бюджетирование и инвестиции. На нём публикуются практические материалы, советы и обзоры
finance-post-234
11 Sep 25 at 5:11 pm
авиатор игра 1вин [url=aviator-igra-2.ru]авиатор игра 1вин[/url] .
aviator igra_fyol
11 Sep 25 at 5:13 pm
Нужна, где заказать санитарную книжку в Перми официально и без бюрократии? На [url=https://klinika-zdorovya-no1.ru]https://klinika-zdorovya-no1.ru[/url] можно сделать медкнижку нового образца по цене от 1700 ? или продлить имеющуюся — за 1000 ?. Документы подлинные и законные, курьер доставит готовую книжку к вам домой. Всё удобно: передать нужные данные онлайн, внести оплату и ждать доставку — без посещения поликлиники и задержек. Все подробности — медицинская книжка Пермь, без ожидания, скидка на продление.
Spravkiggx
11 Sep 25 at 5:15 pm
darknet drug market darknet drug links nexusdarknet site link [url=https://darkmarketlegion.com/ ]bitcoin dark web [/url]
Robertalima
11 Sep 25 at 5:17 pm
1win crash [url=www.aviator-igra-2.ru]www.aviator-igra-2.ru[/url] .
aviator igra_flol
11 Sep 25 at 5:17 pm
darknet marketplace dark web sites darkmarket list [url=https://darkmarketsgate.com/ ]darknet drug links [/url]
Jamespem
11 Sep 25 at 5:17 pm
darknet drug market nexus official link nexus site official link [url=https://darknetmarketseasy.com/ ]dark market url [/url]
BrianWeX
11 Sep 25 at 5:18 pm
Bonanza Donut игра
EdwardTix
11 Sep 25 at 5:19 pm
Heya i’m for the first time here. I came across this board and I to find It truly helpful
& it helped me out much. I am hoping to provide something
again and aid others such as you aided me.
Also visit my web blog … alcohol rehab springfield va
alcohol rehab springfield va
11 Sep 25 at 5:19 pm
проектирование перепланировки в квартире [url=proekt-pereplanirovki-kvartiry8.ru]proekt-pereplanirovki-kvartiry8.ru[/url] .
proekt pereplanirovki kvartiri_wbMl
11 Sep 25 at 5:20 pm
квартиры в Витебске http://artclinic.com.br/2025/09/05/chto-uchityvat-pri-arende-zhilja-v-dome-s-zakrytoj/
http://artclinic.com.br/2025/09/05/chto-uchityvat-pri-arende-zhilja-v-dome-s-zakrytoj/
11 Sep 25 at 5:22 pm
проект перепланировки цена [url=http://proekt-pereplanirovki-kvartiry8.ru]http://proekt-pereplanirovki-kvartiry8.ru[/url] .
proekt pereplanirovki kvartiri_pzMl
11 Sep 25 at 5:24 pm
купить диплом вуза с реестром [url=www.arus-diplom34.ru]купить диплом вуза с реестром[/url] .
Diplomi_rrer
11 Sep 25 at 5:24 pm
https://www.youtube.com/@candetoxblend/about
Afrontar un control médico ya no tiene que ser un problema. Existe un suplemento de última generación que funciona en el momento crítico.
El secreto está en su fórmula canadiense, que sobrecarga el cuerpo con proteínas, provocando que la orina neutralice los rastros químicos. Esto asegura parámetros adecuados en menos de lo que imaginas, con ventana segura para rendir tu test.
Lo mejor: no necesitas semanas de detox, diseñado para candidatos en entrevistas laborales.
Miles de personas en Chile confirman su rapidez. Los entregas son confidenciales, lo que refuerza la tranquilidad.
Si tu meta es asegurar tu futuro laboral, esta fórmula es la elección inteligente.
JuniorShido
11 Sep 25 at 5:25 pm
оформление перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry8.ru/]оформление перепланировки квартиры в москве[/url] .
proekt pereplanirovki kvartiri_spMl
11 Sep 25 at 5:26 pm
У меня тоже была задержка.На мониторенге тоже отправку просрочили, в итоге дней 20 затратили на пересылку.Просто курьерка такая, они помоему там распиздяи ещё те…так что на счёт приема можешь не беспокоиться.там даже если мусора захотят что то найти то будет трудно разобраться что да где)вот допустим недавно заказал и курьерка ваще не то вбила))так что не переживай!Чемикалы всё ровно делают, сложновато будет найти даже если посыль откроют!
https://qepzuff.ru
Частенько брал сдесь мини-опт по совместкам в 2013-2014году !
Richardmog
11 Sep 25 at 5:27 pm
http://intimacareuk.com/# IntimaCare UK
Carrollalery
11 Sep 25 at 5:28 pm
Excellent site you have here but I was curious about if you knew
of any message boards that cover the same topics discussed here?
I’d really love to be a part of community where I can get suggestions from other knowledgeable people that share the same
interest. If you have any suggestions, please let me know.
Thanks!
Take a look at my blog addiction treatment in hudson county
addiction treatment in hudson county
11 Sep 25 at 5:33 pm
Adoro o clima alucinante de MegaPosta Casino, oferece uma aventura de cassino que detona tudo. Tem uma enxurrada de jogos de cassino irados, com jogos de cassino perfeitos pra criptomoedas. Os agentes do cassino sao rapidos como um estalo, dando solucoes na hora e com precisao. Os saques no cassino sao velozes como uma tempestade, porem mais recompensas no cassino seriam um diferencial insano. Em resumo, MegaPosta Casino oferece uma experiencia de cassino que e puro fogo para os viciados em emocoes de cassino! De bonus o design do cassino e uma explosao visual braba, o que deixa cada sessao de cassino ainda mais alucinante.
megaposta cassino|
whackypenguin6zef
11 Sep 25 at 5:35 pm
Nice blog! Is your theme custom made or did you download it from somewhere?
A design like yours with a few simple tweeks would really make my blog jump out.
Please let me know where you got your design. Kudos
ลาวพัฒนา
11 Sep 25 at 5:35 pm
согласование перепланировки квартиры в москве цена [url=http://proekt-pereplanirovki-kvartiry8.ru]http://proekt-pereplanirovki-kvartiry8.ru[/url] .
proekt pereplanirovki kvartiri_soMl
11 Sep 25 at 5:36 pm
https://www.divephotoguide.com/user/martinluter
Geraldhic
11 Sep 25 at 5:37 pm
aviator играть на деньги [url=www.aviator-igra-2.ru]www.aviator-igra-2.ru[/url] .
aviator igra_bdol
11 Sep 25 at 5:38 pm
I’m curious to find out what blog platform you have been working with?
I’m having some small security issues with my latest blog and I would like to
find something more safeguarded. Do you have any solutions?
raffi777
11 Sep 25 at 5:40 pm
Acho simplesmente insano OshCasino, da uma energia de cassino que e um terremoto. O catalogo de jogos do cassino e uma explosao total, incluindo jogos de mesa de cassino cheios de fogo. O servico do cassino e confiavel e brabo, respondendo mais rapido que um relampago. Os pagamentos do cassino sao lisos e blindados, mesmo assim mais recompensas no cassino seriam um diferencial vulcanico. Resumindo, OshCasino oferece uma experiencia de cassino que e puro fogo para quem curte apostar com estilo no cassino! Alem disso a interface do cassino e fluida e cheia de energia ardente, da um toque de calor brabo ao cassino.
osh validation compte|
zestylizard7zef
11 Sep 25 at 5:40 pm
My coder is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the expenses.
But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a
year and am concerned about switching to another platform.
I have heard excellent things about blogengine.net.
Is there a way I can transfer all my wordpress
posts into it? Any kind of help would be really appreciated!
link alternatif mpo8080
11 Sep 25 at 5:41 pm
кракен darknet kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
11 Sep 25 at 5:43 pm
разработка проекта перепланировки квартиры [url=http://www.proekt-pereplanirovki-kvartiry8.ru]разработка проекта перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_jlMl
11 Sep 25 at 5:43 pm