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!
vitalpharma24: Kamagra 100mg bestellen – vitalpharma24
ThomasCep
30 Oct 25 at 9:14 am
seo онлайн [url=www.kursy-seo-12.ru]seo онлайн[/url] .
kyrsi seo_djor
30 Oct 25 at 9:14 am
РедМетСплав предлагает внушительный каталог высококачественных изделий из редких материалов. Не важно, какие объемы вам необходимы – от мелких партий до крупных поставок, мы обеспечиваем своевременную реализацию вашего заказа.
Каждая единица товара подтверждена требуемыми документами, подтверждающими их соответствие стандартам. Дружелюбная помощь – наша визитная карточка – мы на связи, чтобы ответить на ваши вопросы по мере того как находить ответы под особенности вашего бизнеса.
Доверьте потребности вашего бизнеса специалистам РедМетСплав и убедитесь в широком спектре предлагаемых возможностей
Наша продукция:
Фольга магниевая AM90 – CSA HG.3 Труба магниевая AM90 – CSA HG.3 — идеальный выбор для тех, кто ищет надежные и легкие материалы для своих проектов. Благодаря высокой прочности и стойкости к коррозии, эта труба обеспечивает долговечность и эффективность в эксплуатации. Покупая данную трубку, вы получаете отличное решение для различных технических задач. Удобные размеры и легкость в монтаже делают трубу магниевой AM90 – CSA HG.3 отличным выбором для строительных и производственных нужд. Не упустите возможность улучшить качество работы, купите Труба магниевая AM90 – CSA HG.3 прямо сейчас!
SheilaAlemn
30 Oct 25 at 9:14 am
виртуальный номер навсегда купить
виртуальный номер навсегда купить
30 Oct 25 at 9:14 am
Pretty component of content. I simply stumbled upon your web site and in accession capital
to assert that I acquire in fact loved account your blog posts.
Anyway I’ll be subscribing for your feeds or even I success
you access constantly rapidly.
situs bokep
30 Oct 25 at 9:15 am
berenux.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Nikita Duhamel
30 Oct 25 at 9:15 am
курсы seo [url=http://kursy-seo-12.ru]курсы seo[/url] .
kyrsi seo_lcor
30 Oct 25 at 9:20 am
jpl927.com – Found practical insights today; sharing this article with colleagues later.
Calvin Chamnanphony
30 Oct 25 at 9:21 am
https://vitahomme.shop/# kamagra oral jelly
Davidjealp
30 Oct 25 at 9:22 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Где можно узнать подробнее? – https://aluminiumcompositepanel.com.my/2022/10/04/hello-world
Davidbenly
30 Oct 25 at 9:22 am
Предложение позволяет получить дополнительные деньги
и фриспины за совершение депозитов.
7к зеркало
30 Oct 25 at 9:23 am
uucncn.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Leida Knezevic
30 Oct 25 at 9:23 am
Kamagra livraison rapide en France: acheter Kamagra en ligne – Kamagra pas cher France
RichardImmon
30 Oct 25 at 9:24 am
seo с нуля [url=www.kursy-seo-12.ru/]www.kursy-seo-12.ru/[/url] .
kyrsi seo_nvor
30 Oct 25 at 9:24 am
Hello, after reading this remarkable post
i am too happy to share my experience here with mates.
BYD สงขลา
30 Oct 25 at 9:25 am
Hello are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and create my own. Do you require any
coding knowledge to make your own blog? Any help would
be greatly appreciated!
ankara kürtaj
30 Oct 25 at 9:26 am
Spedra: differenza tra Spedra e Viagra – differenza tra Spedra e Viagra
ClydeExamp
30 Oct 25 at 9:26 am
46466497.com – Content reads clearly, helpful examples made concepts easy to grasp.
Joshua Selmer
30 Oct 25 at 9:27 am
Hi this is somewhat of off topic but I was wanting to know if blogs use
WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding know-how so
I wanted to get guidance from someone with experience.
Any help would be greatly appreciated!
Verum Finviora
30 Oct 25 at 9:27 am
differenza tra Spedra e Viagra: differenza tra Spedra e Viagra – comprare medicinali online legali
ClydeExamp
30 Oct 25 at 9:27 am
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Продолжить чтение – https://alles-familie.at/rosshuette-seefeld-ein-toller-spielplatz-am-berg
Thomasdit
30 Oct 25 at 9:27 am
Статья знакомит с важнейшими моментами, которые сформировали наше общество. От великих изобретений до культурных переворотов — вы узнаете, как прошлое влияет на наше мышление, технологии и образ жизни.
Запросить дополнительные данные – https://atelierivoire.bg/early-bride-sale
Robertfiz
30 Oct 25 at 9:28 am
Vita Homme: Kamagra 100mg prix France – Kamagra sans ordonnance
RobertJuike
30 Oct 25 at 9:30 am
Your mode of explaining everything in this post is in fact nice, all be
able to without difficulty understand it, Thanks a lot.
نمایندگی تعمیر لباسشویی بوش
30 Oct 25 at 9:32 am
diskrete Lieferung per DHL: Kamagra Wirkung und Nebenwirkungen – vitalpharma24
RichardImmon
30 Oct 25 at 9:32 am
acquistare Spedra online: Spedra prezzo basso Italia – comprare medicinali online legali
ClydeExamp
30 Oct 25 at 9:32 am
курсы seo [url=kursy-seo-12.ru]курсы seo[/url] .
kyrsi seo_xpor
30 Oct 25 at 9:33 am
There’s definately a great deal to learn about this issue.
I like all of the points you’ve made.
helpful resources
30 Oct 25 at 9:34 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Подробная информация доступна по запросу – https://dieteticienne-nutritionniste-sartrouville.com/sportndiet
CharlesTiz
30 Oct 25 at 9:35 am
I think that everything published made a great deal of sense.
However, what about this? what if you typed a
catchier title? I mean, I don’t want to tell you how to run your blog, but what if you added a headline to possibly
grab people’s attention? I mean PHP hook, building
hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is a
little boring. You ought to look at Yahoo’s home page and see how they
create article titles to get people to click. You might add a related video or a picture or two to grab people excited about what
you’ve written. In my opinion, it might bring your blog a little bit more interesting.
Fenice Bitvexa
30 Oct 25 at 9:37 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Дополнительно читайте здесь – http://www.guatemalatps.info/?p=61
LarryGef
30 Oct 25 at 9:38 am
купить виртуальный номер
купить виртуальный номер
30 Oct 25 at 9:39 am
обучение seo [url=https://kursy-seo-12.ru/]обучение seo[/url] .
kyrsi seo_ueor
30 Oct 25 at 9:39 am
Kamagra 100mg bestellen: diskrete Lieferung per DHL – Kamagra 100mg bestellen
ThomasCep
30 Oct 25 at 9:41 am
Hello, i read your blog occasionally and i own a similar one and
i was just wondering if you get a lot of spam feedback?
If so how do you reduce it, any plugin or anything you can advise?
I get so much lately it’s driving me crazy so any help is very much appreciated.
Набойченко дебошир
30 Oct 25 at 9:43 am
РедМетСплав предлагает широкий ассортимент высококачественных изделий из ценных материалов. Не важно, какие объемы вам необходимы – от небольших закупок до масштабных поставок, мы гарантируем своевременную реализацию вашего заказа.
Каждая единица изделия подтверждена соответствующими документами, подтверждающими их соответствие стандартам. Дружелюбная помощь – то, чем мы гордимся – мы на связи, чтобы разрешать ваши вопросы а также находить ответы под специфику вашего бизнеса.
Доверьте потребности вашего бизнеса профессионалам РедМетСплав и убедитесь в гибкости нашего предложения
поставляемая продукция:
Проволока титановая D(8Mo-8V-2Fe-3Al) – MIL T-9046H Полоса титановая D(8Mo-8V-2Fe-3Al) – MIL T-9046H является высококачественным материалом, предназначенным для применения в авиационной и военной промышленности. Она обладает превосходными механическими свойствами и высокой коррозионной стойкостью, что делает её идеальным выбором для ответственных конструкций. Эта титановая полоса также отличается легким весом и высокой прочностью, что обеспечивает ее конкурентные преимущества. Не упустите возможность купить Полоса титановая D(8Mo-8V-2Fe-3Al) – MIL T-9046H и улучшить свои проекты с использованием надежного и прочного материала.
SheilaAlemn
30 Oct 25 at 9:44 am
Thanks for the marvelous posting! I certainly enjoyed reading it, you can be a great author.
I will always bookmark your blog and will often come back later
on. I want to encourage that you continue your great work,
have a nice afternoon!
artis indonesia
30 Oct 25 at 9:44 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Смотрите также… – https://mayovest.com/natural-comfortable-latex-mattress
JasonZek
30 Oct 25 at 9:44 am
курсы seo [url=www.kursy-seo-12.ru]курсы seo[/url] .
kyrsi seo_snor
30 Oct 25 at 9:46 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Это стоит прочитать полностью – https://mandysbeautysupply.com/getting-wiggy-with-it
Andredex
30 Oct 25 at 9:46 am
pillole per disfunzione erettile: acquistare Spedra online – Spedra
ClydeExamp
30 Oct 25 at 9:47 am
sapphire hair clinic
hair transplant istanbul
30 Oct 25 at 9:47 am
The trial of Bryan Kohberger – the man who brutally murdered four University of Idaho students inside their off-campus home – ended in July before it ever truly began when he accepted a plea deal that saw him sentenced to four consecutive life terms in prison without the possibility of an appeal or parole.
Kohberger sat impassively throughout the hearing as the loved ones of each of the four students whose lives he so callously ended repeatedly asked him the same question: Why?
[url=http://trip-skan45.cc]трипскан вход[/url]
And when he was finally given the opportunity to answer their questions, he said, “I respectfully decline.”
That decision further fueled the mystery around his motive for murdering Xana Kernodle, Madison Mogen, Ethan Chapin and Kaylee Goncalves.
“There’s no reason for these crimes that could approach anything resembling rationality,” Idaho District Judge Steven Hippler said during Kohberger’s sentencing. “The more we try to extract a reason, the more power and control we give to him.”
But, he added, investigators and researchers may wish to study his actions – if only to learn how to prevent similar crimes from occurring in the future.
http://trip-skan45.cc
трип скан
Indeed, academics and former FBI profilers told CNN the challenge of unravelling the criminal mind of a man like Bryan Kohberger is enticing. And while his trial may be over, in many ways, the story of what can be learned from his crimes may have only just begun.
“We want to squeeze any silver lining that we can out of these tragedies,” said Molly Amman, a retired profiler who spent years leading the FBI’s Behavioral Threat Assessment Center.
“The silver lining is anything we can use to prevent another crime. It starts with learning absolutely, positively everything about the person and the crime that we possibly can.”
CNN
Only Kohberger knows
Even seasoned police officers who arrived at 1122 King Road on November 13, 2022, struggled to process the brutality of the crime scene.
All four victims had been ruthlessly stabbed to death before the attacker vanished through the kitchen’s sliding glass door and into the night.
“The female lying on the left half of the bed … was unrecognizable,” one officer would later write of the attack that killed Kaylee Goncalves. “I was unable to comprehend exactly what I was looking at while trying to discern the nature of the injuries.”
Initial interviews with the two surviving housemates gave investigators a loose timeline and a general description of the killer – an athletic, White male who wore a mask that covered most of his face – but little else.
Police later found a Ka-Bar knife sheath next to Madison’s body that would prove to be critical in capturing her killer.
One of the surviving housemates told police about a month before the attacks, Kaylee saw “a dark figure staring at her from the tree line when she took her dog Murphy out to pee.”
“There has been lighthearted talk and jokes made about a stalker in the past,” the officer noted. “All the girls were slightly nervous about it being a fact, though.”
But after years of investigating the murders, detectives told CNN they were never able to establish a connection between Kohberger and any of the victims, or a motive.
Kohberger is far from the first killer to deny families and survivors the catharsis that comes with confessing, in detail, to his crimes. But that, former FBI profilers tell CNN, is part of what makes the prospect of studying him infuriating and intriguing.
JasonHoG
30 Oct 25 at 9:48 am
школа seo [url=https://kursy-seo-12.ru/]kursy-seo-12.ru[/url] .
kyrsi seo_sror
30 Oct 25 at 9:49 am
Hi there! I know this is kind of off topic but I was wondering if you knew where I could locate
a captcha plugin for my comment form? I’m using the same blog platform as yours
and I’m having trouble finding one? Thanks a lot!
Educational Resource Associates
30 Oct 25 at 9:49 am
kamagra: kamagra – Sildenafil générique
RobertJuike
30 Oct 25 at 9:51 am
FarmaciaViva: comprare medicinali online legali – differenza tra Spedra e Viagra
ClydeExamp
30 Oct 25 at 9:51 am
Hey very interesting blog!
LupexisMax Recensione
30 Oct 25 at 9:52 am
dragon casino
DonaldflerB
30 Oct 25 at 9:53 am
diskrete Lieferung per DHL: Potenzmittel ohne ärztliches Rezept – vital pharma 24
ThomasCep
30 Oct 25 at 9:53 am