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!
Если вы или ваш близкий нуждаетесь в профессиональной помощи при запое, клиника «Детокс» в Краснодаре предлагает услугу вызова нарколога на дом. Врач приедет в течение 1–2 часов, проведёт необходимое обследование и назначит лечение. Услуга доступна круглосуточно и анонимно.
Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnodar29.ru/]нарколог на дом круглосуточно цены[/url]
AllanHib
21 Oct 25 at 7:05 pm
топ 10 digital агентств [url=https://luchshie-digital-agencstva.ru/]luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_etoi
21 Oct 25 at 7:05 pm
DRINKIO приятно удивил профессионализмом и качеством обслуживания. Заказ доставили точно в срок, всё аккуратно упаковано. Курьеры вежливые, видно, что работают с ответственностью. Ассортимент большой, цены разумные. Особенно радует круглосуточная работа — всегда можно оформить заказ. Отличная доставка алкоголя на дом в Москве 24/7 – https://drinkio105.ru/
Arthurtok
21 Oct 25 at 7:06 pm
сео оптимизация москва [url=https://reiting-seo-agentstv-moskvy.ru/]https://reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_qhMl
21 Oct 25 at 7:08 pm
seo продвижение в москве [url=https://seo-prodvizhenie-reiting-kompanij.ru]seo продвижение в москве[/url] .
seo prodvijenie reiting kompanii_gast
21 Oct 25 at 7:09 pm
компания seo [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_mrKt
21 Oct 25 at 7:10 pm
продвижение сайта в топ москва [url=https://reiting-seo-agentstv-moskvy.ru]https://reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_soMl
21 Oct 25 at 7:11 pm
лучшие seo агентства [url=https://luchshie-digital-agencstva.ru]лучшие seo агентства[/url] .
lychshie digital agentstva_gzoi
21 Oct 25 at 7:11 pm
yourpathofsuccess – It’s a good read when you need to reflect and regroup your goals.
Maxie Chehab
21 Oct 25 at 7:12 pm
seo агенция [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_lasa
21 Oct 25 at 7:12 pm
Hello there! I simply would like to offer you a huge thumbs up for the excellent info you have
got here on this post. I’ll be coming back to your site for more soon.
MMM file opener
21 Oct 25 at 7:16 pm
What’s up, I want to subscribe for this blog to get hottest updates, so where can i do it please help.
AYUTOGEL
21 Oct 25 at 7:16 pm
Где купить Меф в Паратунке?Нашел сайт https://cs-turbo.ru
– адекватные отзывы и цены. Есть доставка. Кто-то уже пользовался их товаром? Интересует качество?
Stevenref
21 Oct 25 at 7:18 pm
продвижение сайтов топ агентство [url=http://seo-prodvizhenie-reiting.ru]http://seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_rkEa
21 Oct 25 at 7:18 pm
продвижение сайтов поисковых системах москва [url=www.reiting-seo-agentstv-moskvy.ru/]www.reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_fzMl
21 Oct 25 at 7:19 pm
Oi oi, tοp establishments іnclude challenges, sharpening reasoning fօr investigative оr
expert positions.
Oh, smart tⲟ hurry connections lah, cеrtain primaries associate tօ leading secs, smoothing tһe ѡay to JC and university
success.
Parents, worry аbout tһe difference hor,
math foundation гemains essential during primary school in understanding figures, crucial іn modern online economy.
Alas, lacking strong math ɗuring primary school, no matter prestigious
school kids mаy stumble іn һigh school algebra, tһus develop
tһat now leh.
Alas, mіnus robust mathematics during primary school, even leading institution kids mіght
stumble witһ next-level calculations, thuѕ build
it immeɗiately leh.
Ⲟh no, primary arithmetic teaches practical implementations ѕuch ɑs
money management, ѕ᧐ ensure your youngster ɡets this properly from young age.
Alas, primary mathematics educates everyday ᥙses including budgeting,
thus guarantee your kid grasps thаt right ƅeginning young age.
Punggol Green Primary School supplies ɑn inspiring environment supporting academic аnd individual advancement.
Committed teachers assist build strong foundations.
Paya Lebar Methodist Girls’ School (Primary) empowers girls ԝith faith and quality.
The school nurtures management skills.
Ιt’s perfect fоr Methodist families.
Review mү web site – Raffles Girls’ School
Raffles Girls’ School
21 Oct 25 at 7:19 pm
продвижение в топ [url=https://www.reiting-seo-agentstv.ru]продвижение в топ[/url] .
reiting seo agentstv_llsa
21 Oct 25 at 7:22 pm
seo продвижение рейтинг компаний [url=https://www.reiting-seo-kompanii.ru]seo продвижение рейтинг компаний[/url] .
reiting seo kompanii_ffsn
21 Oct 25 at 7:22 pm
топ seo продвижение заказать [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_ivKt
21 Oct 25 at 7:24 pm
рейтинг seo агентств [url=https://reiting-seo-kompanii.ru]рейтинг seo агентств[/url] .
reiting seo kompanii_tfsn
21 Oct 25 at 7:25 pm
seo оптимизация москва [url=https://www.reiting-seo-agentstv-moskvy.ru]https://www.reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_ifMl
21 Oct 25 at 7:26 pm
seo professional services [url=https://top-10-seo-prodvizhenie.ru/]top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_dqKa
21 Oct 25 at 7:26 pm
услуги по раскрутке сайта [url=https://reiting-runeta-seo.ru/]reiting-runeta-seo.ru[/url] .
reiting ryneta seo_hlma
21 Oct 25 at 7:26 pm
В Екатеринбурге служба Stop-Alko круглосуточно помогает вывести из запоя на дому — быстро, анонимно и без постановки на учёт.
Получить больше информации – http://vyvod-iz-zapoya-ekaterinburg26.ru
Williamner
21 Oct 25 at 7:27 pm
раскрутка сайта москва [url=http://seo-prodvizhenie-reiting-kompanij.ru]раскрутка сайта москва[/url] .
seo prodvijenie reiting kompanii_wsst
21 Oct 25 at 7:27 pm
seo company service [url=http://reiting-runeta-seo.ru]seo company service[/url] .
reiting ryneta seo_ubma
21 Oct 25 at 7:29 pm
топ digital агентств москвы [url=www.luchshie-digital-agencstva.ru]www.luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_xeoi
21 Oct 25 at 7:30 pm
The Minotaurus token presale is heating up, with over 1.4M USDT raised already. Love how it integrates DeFi tools for both newbies and vets, making entry easy. $MTAUR might just outpace meme coins in utility.
minotaurus coin
WilliamPargy
21 Oct 25 at 7:31 pm
продвижение сайтов сео топ [url=http://reiting-seo-agentstv.ru]продвижение сайтов сео топ[/url] .
reiting seo agentstv_whsa
21 Oct 25 at 7:33 pm
Ꭺvoid downplay hor, renowned institutions deliver musical аnd theater, improving creativity fօr communication jobs.
Aiyah, steady lah, tߋp institutions focus оn environmental awareness, for green jobs іn eco Singapore.
Eh eh, composed pom рi pі, math proves part frim tһe top subjects in primary school,
building groundwork for A-Level advanced math.
Hey hey, calm pom ρі рi, mathematics remains οne of the leading disciplines ɑt primary
school, establishing foundation іn A-Level higher calculations.
Listen up, Singapore parents, math remaіns ⅼikely tһe extremely іmportant primary subject, encouraging
creativity fоr issue-resolving tօ creative jobs.
Hey hey, steady pom ρi рi, math proves part in the t᧐p disciplines in primary school, laying foundation tߋ А-Level advanced math.
Oi oi, Singapore parents, mathematics proves ⅼikely the highly importаnt primary subject,
promoting innovation fⲟr issue-resolving іn creative
professions.
Sengkang Green Primary School օffers a motivating neighborhood supporting уoung learners.
The school fosters development ɑnd ⅼong-lasting skills.
Sі Ling Primary School usеѕ nurturing programs in tһe north.
The school builds scholastic ɑnd social skills.
Parents select іt f᧐r community feel.
Alѕo visit my page Kaizenaire math tuition singapore
Kaizenaire math tuition singapore
21 Oct 25 at 7:33 pm
The Minotaurus presale DAO empowers. Token’s vesting prevents chaos. Adventures immersive.
minotaurus token
WilliamPargy
21 Oct 25 at 7:34 pm
firma seo [url=https://seo-prodvizhenie-reiting.ru/]firma seo[/url] .
seo prodvijenie reiting_thEa
21 Oct 25 at 7:35 pm
seo optimization agency [url=http://reiting-seo-kompanii.ru]http://reiting-seo-kompanii.ru[/url] .
reiting seo kompanii_lbsn
21 Oct 25 at 7:36 pm
top seo company [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_gnKt
21 Oct 25 at 7:36 pm
https://writexo.com/share/7d867f41fa28
KevenErach
21 Oct 25 at 7:37 pm
Sou viciado em PlayPIX Casino, oferece um prazer carnavalesco. O catalogo e rico e diversificado, suportando jogos compativeis com criptomoedas. Fortalece seu saldo inicial. O servico esta disponivel 24/7, oferecendo respostas claras. As transacoes sao confiaveis, embora recompensas adicionais seriam festivas. Em resumo, PlayPIX Casino vale uma visita epica para quem aposta com cripto ! Vale notar o design e moderno e vibrante, adiciona um toque de conforto. Muito atrativo os torneios regulares para competicao, que impulsiona o engajamento.
Descobrir a web|
SambaRiserX9zef
21 Oct 25 at 7:38 pm
Sou viciado em BETesporte Casino, e uma plataforma que pulsa com emocao atletica. Ha uma multidao de jogos emocionantes, com sessoes ao vivo imersivas. Com uma oferta inicial para impulsionar. A assistencia e eficiente e profissional, garantindo atendimento de alto nivel. Os ganhos chegam sem demora, contudo mais apostas gratis seriam incriveis. Em sintese, BETesporte Casino garante diversao a cada rodada para jogadores em busca de emocao ! Adicionalmente a interface e fluida e energetica, instiga a prolongar o jogo. Um diferencial importante os torneios regulares para rivalidade, proporciona vantagens personalizadas.
Descobrir a web|
FutebolFogoM4zef
21 Oct 25 at 7:39 pm
раскрутка сайта москва [url=reiting-seo-agentstv-moskvy.ru]раскрутка сайта москва[/url] .
reiting seo agentstv moskvi_mwMl
21 Oct 25 at 7:40 pm
В больничных условиях «Частного Медика 24» врачи контролируют давление, сердце и функции жизненно важных органов при выводе из запоя.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]быстрый вывод из запоя в стационаре[/url]
JamesNic
21 Oct 25 at 7:40 pm
Клиника «Детокс» в Краснодаре предлагает услугу вызова нарколога на дом. Врачи приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Услуга доступна круглосуточно и анонимно.
Узнать больше – [url=https://narkolog-na-dom-krasnodar29.ru/]платный нарколог на дом в краснодаре[/url]
AllanHib
21 Oct 25 at 7:41 pm
сео интернет [url=https://reiting-runeta-seo.ru/]сео интернет[/url] .
reiting ryneta seo_gvma
21 Oct 25 at 7:41 pm
Клиника «Похмельная служба» в Нижнем Новгороде предлагает капельницу от запоя с выездом на дом. Наши специалисты обеспечат вам комфортное и безопасное лечение в привычной обстановке.
Разобраться лучше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]скорая вывод из запоя[/url]
Norbertavoig
21 Oct 25 at 7:44 pm
агентство поискового продвижения [url=https://reiting-seo-agentstv-moskvy.ru/]агентство поискового продвижения[/url] .
reiting seo agentstv moskvi_dyMl
21 Oct 25 at 7:45 pm
заказать сео продвижение сайта москва [url=https://seo-prodvizhenie-reiting-kompanij.ru]заказать сео продвижение сайта москва[/url] .
seo prodvijenie reiting kompanii_vmst
21 Oct 25 at 7:46 pm
digital агентства москвы [url=http://www.luchshie-digital-agencstva.ru]http://www.luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_psoi
21 Oct 25 at 7:47 pm
Aw, this was a really nice post. Taking a few minutes and actual effort to
make a good article… but what can I say… I procrastinate a whole lot and never manage to get anything done.
detention pond dirt dump truck service
21 Oct 25 at 7:48 pm
The Supreme Court agreed Monday to decide if the federal government may bar certain drug users from owning guns or if the law violates the Second Amendment, taking up a second significant guns case of its current term.
[url=https://kra42.net]kra42 сс[/url]
The appeal represents a rare circumstance in which the Trump administration is defending a gun prohibition, which it described in briefing at the Supreme Court as a “narrow” limitation on one of “Americans’ most cherished freedoms.”
[url=https://kra–42–cc.ru]kra42 cc[/url]
The case centers on Ali Danial Hemani, a dual citizen of the United States and Pakistan, who was indicted in 2023 on a single count of violating the guns-and-drugs law after the FBI found a 9mm pistol, 60 grams of marijuana, and 4.7 grams of cocaine at his family home. This prosecution, the government told the high court, rested Hemani’s habitual use of marijuana.
The court will likely hear arguments in the Hemani case next year and hand down a decision by the end of June.
kra42 cc
https://kra-42-cc.net
A federal district court dismissed the charge, noting a landmark decision from the Supreme Court in 2022 that made it easier for Americans to carry handguns in public and also required similar gun prohibitions to have a connection to history.
But just how closely analogous prosecutors must come to a historic law has been a matter of debate. Last year, for instance, the Supreme Court upheld a federal law that bars guns for Americans who are the subject of certain domestic abuse restraining orders, rejecting an argument pressed by gun rights groups that the prohibition violated the Second Amendment.
The conservative 5th US Circuit Court of Appeals upheld that decision, holding in a brief decision that the historical record points only to laws that barred guns for Americans who are actively intoxicated or under the influence of drugs at the time of their arrest. The government, the court ruled, could not target habitual users.
The Trump administration appealed that decision.
PhilipZef
21 Oct 25 at 7:48 pm
Does your website have a contact page? I’m having a tough time locating it but, I’d like to
shoot you an email. I’ve got some recommendations for your blog you might
be interested in hearing. Either way, great site and I
look forward to seeing it develop over time.
hijab habis eksib lanjut ngewe
21 Oct 25 at 7:49 pm
seo продвижение россия [url=https://reiting-seo-agentstv.ru]seo продвижение россия[/url] .
reiting seo agentstv_amsa
21 Oct 25 at 7:49 pm
топ компаний по продвижению сайтов [url=https://www.seo-prodvizhenie-reiting.ru]https://www.seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_gmEa
21 Oct 25 at 7:50 pm