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=www.transformatornye-podstancii-kupit.ru/]www.transformatornye-podstancii-kupit.ru/[/url] .
transformatornie podstancii kypit_sboi
21 Aug 25 at 9:34 pm
Greetings I am so grateful I found your blog, I really found you by accident, while I was
researching on Digg for something else, Regardless I am here now and would just like to say many
thanks for a marvelous post and a all round thrilling blog (I also love the theme/design),
I don’t have time to read through it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back
to read a lot more, Please do keep up the superb job.
royal x casino app
21 Aug 25 at 9:34 pm
Good article! We are linking to this great article on our site.
Keep up the good writing.
whiteboardcrm.com lừa đảo công an truy quét cấm người chơi tham gia
21 Aug 25 at 9:35 pm
ставки прогнозы [url=stavki-prognozy-2.ru]stavki-prognozy-2.ru[/url] .
stavki prognozy_rrmn
21 Aug 25 at 9:40 pm
Drugs information leaflet. Drug Class.
can i buy cheap plan b online
All about pills. Read information here.
can i buy cheap plan b online
21 Aug 25 at 9:41 pm
stavkiprognozy [url=stavki-prognozy-2.ru]stavki-prognozy-2.ru[/url] .
stavki prognozy_slmn
21 Aug 25 at 9:45 pm
https://a-herb.ru/
Graigvorgo
21 Aug 25 at 9:46 pm
психиатрическая клиника
psikhiatr-moskva002.ru
принудительное лечение в психиатрической больнице
psikhiatrmskNeT
21 Aug 25 at 9:47 pm
Every weekend i used to visit this web site, because i want enjoyment,
as this this site conations in fact good funny stuff too.
BlueQubit
21 Aug 25 at 9:47 pm
https://52a43253271a88ae46e75f8970.doorkeeper.jp/
RichardSok
21 Aug 25 at 9:52 pm
Hi there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords
but I’m not seeing very good success. If you know of any please share.
Thanks!
best bitcoin casinos
21 Aug 25 at 9:52 pm
Very good article! We will be linking to this particularly great article on our site.
Keep up the good writing.
Here is my website … Azure Managed VM
Azure Managed VM
21 Aug 25 at 9:55 pm
Howdy! I know this is sort of off-topic but I needed to
ask. Does running a well-established blog like yours take a massive amount work?
I’m brand new to writing a blog but I do write in my journal
every day. I’d like to start a blog so I will be able to share my experience and feelings online.
Please let me know if you have any kind of recommendations or tips for brand new aspiring
blog owners. Appreciate it!
koszulka sportowa czy polo?
21 Aug 25 at 9:55 pm
It’s fantastic that you are getting thoughts from this article as well as from our
dialogue made here.
bokep online
21 Aug 25 at 9:56 pm
Very good post! We will be linking to this particularly great
content on our site. Keep up the great writing.
Quantum Investox
21 Aug 25 at 9:57 pm
Excellent pieces. Keep posting such kind of information on your site.
Im really impressed by your blog.
Hello there, You have performed an excellent
job. I will definitely digg it and in my view suggest to my friends.
I am confident they’ll be benefited from this web site.
roofers services
21 Aug 25 at 9:58 pm
купить диплом магистра [url=http://www.educ-ua4.ru]купить диплом магистра[/url] .
Diplomi_cxPl
21 Aug 25 at 9:58 pm
психолог онлайн помощь в отношениях
Charliesoall
21 Aug 25 at 9:58 pm
If you wish for to get a good deal from this paragraph then you have
to apply such techniques to your won weblog.
Here is my web page; nonton film
nonton film
21 Aug 25 at 10:11 pm
Excellent write-up. I definitely love this website. Keep it up!
استعلام گواهی کسر از حقوق آموزش و پرورش
21 Aug 25 at 10:13 pm
https://www.themeqx.com/forums/users/deefecuicoob/
RichardSok
21 Aug 25 at 10:13 pm
I like it when folks get together and share thoughts.
Great site, continue the good work!
My page :: 안전놀이터
안전놀이터
21 Aug 25 at 10:14 pm
This page truly has all the information I wanted about this subject
and didn’t know who to ask.
Najważniejsze kryteria doboru flip-flopów – żegnaj niewygodę!
21 Aug 25 at 10:14 pm
Всех приветствую! Хотите узнать больше о продвижении? Узнайте подробнее – https://villagessmiles.com/smiles-unleashed-7th-annual-free-dental-care-day-2023/
WilliamLig
21 Aug 25 at 10:15 pm
Stavki Prognozy [url=stavki-prognozy-2.ru]stavki-prognozy-2.ru[/url] .
stavki prognozy_utmn
21 Aug 25 at 10:16 pm
It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.
The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
[url=https://kra40-at.ru]kra34[/url]
The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.
Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
[url=https://kra-37at.ru]kra31 cc[/url]
The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.
The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.
The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.
“Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
kra37 cc
https://kra—37–at.ru
Frankplary
21 Aug 25 at 10:17 pm
получить консультацию психиатра
psikhiatr-moskva001.ru
врач психиатр на дом в москве
psihmskNeT
21 Aug 25 at 10:18 pm
Каждый врач клиники обладает глубокими знаниями фармакологии, психофармакологии и психотерапии. Они регулярно посещают профессиональные конференции, семинары и мастер-классы, чтобы быть в курсе новейших достижений в области лечения зависимостей. Такой подход позволяет нашим специалистам применять наиболее эффективные и современные методы терапии.
Подробнее тут – https://narco-vivod.ru/vivod-iz-zapoya-v-kruglosutochno-v-krasnodare/
CharlesKef
21 Aug 25 at 10:18 pm
Right here is the right webpage for anyone who hopes to understand this
topic. You know so much its almost hard to argue with you (not that I personally would want to…HaHa).
You certainly put a new spin on a subject that has
been written about for ages. Great stuff, just wonderful!
jak wszyscy patrzą?
21 Aug 25 at 10:18 pm
I was curious if you ever thought of changing the layout of
your blog? Its very well written; I love what youve got
to say. But maybe you could a little more
in the way of content so people could connect with it
better. Youve got an awful lot of text for only having 1 or two images.
Maybe you could space it out better?
bsme.at
21 Aug 25 at 10:24 pm
Hey I am so happy I found your website, I really found you by error, while I was searching
on Askjeeve for something else, Nonetheless I am here now and would just like to
say thanks a lot for a marvelous post and a all round interesting blog (I
also love the theme/design), I don’t have time to browse it
all at the moment but I have bookmarked it and also added in your RSS feeds,
so when I have time I will be back to read much more, Please do keep up the superb job.
keo nha cai
21 Aug 25 at 10:29 pm
stavkiprognozy [url=https://stavki-prognozy-2.ru/]stavki-prognozy-2.ru[/url] .
stavki prognozy_sumn
21 Aug 25 at 10:30 pm
It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.
The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
[url=https://kra–38–cc.ru]kra33 cc[/url]
The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.
Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
[url=https://kra-35at.ru]kra37[/url]
The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.
The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.
The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.
“Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
kra34 cc
https://kra-39cc.ru
Frankplary
21 Aug 25 at 10:30 pm
https://bio.site/uhnabocuhoh
GroverPycle
21 Aug 25 at 10:34 pm
I was curious if you ever considered changing the layout
of your blog? Its very well written; I love what youve got
to say. But maybe you could a little more in the way of content so people could connect
with it better. Youve got an awful lot of text for only
having 1 or two images. Maybe you could space it out
better?
klasyka
21 Aug 25 at 10:44 pm
Hello! This post could not be written any better! Reading through this post
reminds me of my good old room mate! He always kept talking about this.
I will forward this page to him. Fairly certain he will have
a good read. Thanks for sharing!
سن فرهنگیان برای کنکور ۱۴۰۴
21 Aug 25 at 10:46 pm
Wow, marvelous blog structure! How lengthy have you been blogging for?
you make blogging look easy. The full glance of your web
site is fantastic, as well as the content!
https://www.pinterest.com/pin/906560600031184894/
21 Aug 25 at 10:48 pm
Мы готовы предложить документы ВУЗов, которые расположены на территории всей Российской Федерации. Приобрести диплом о высшем образовании:
[url=http://ngkh.flybb.ru/viewtopic.php?f=2&t=363&sid=7bf2afb2555d2badc83d2a559ec26411/]купить аттестат 11 класс в омске[/url]
Diplomi_jxPn
21 Aug 25 at 10:49 pm
A motivating discussion is worth comment. There’s no doubt
that that you should write more on this topic,
it may not be a taboo matter but generally people don’t talk about such
issues. To the next! All the best!!
دانشگاه پارس
21 Aug 25 at 10:51 pm
where can i get amoxicillin: TrustedMeds Direct – amoxicillin brand name
JerryLinee
21 Aug 25 at 10:53 pm
vps host server host vps
vps-hosting-656
21 Aug 25 at 10:53 pm
https://www.themeqx.com/forums/users/edjudlpiec/
GroverPycle
21 Aug 25 at 10:55 pm
What i do not understood is in reality how you are not really
much more smartly-liked than you might be right now. You are so intelligent.
You understand therefore significantly in the case of this
subject, made me personally believe it from numerous various angles.
Its like men and women are not fascinated until
it is something to do with Woman gaga! Your individual stuffs
excellent. Always handle it up!
my site: Azure Cloud Instance
Azure Cloud Instance
21 Aug 25 at 11:01 pm
Самые популярные онлайн казино для игры 1942 Sky Warrior собраны в одном месте.
WilliamNex
21 Aug 25 at 11:02 pm
What we’re covering
• Zelensky in Washington: Ukrainian President Volodymyr Zelensky has arrived in Washington, DC, where he will be joined by key European leaders when he meets with Donald Trump this afternoon. Trump says Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra-2at.com]kraken1[/url]
• Potential security guarantees: At last week’s summit with Trump, President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kra13.net]kra15 cc[/url]
• Change in tactics: Trump is now focused on securing a peace deal without pursuing a ceasefire due to his progress with Putin, Witkoff said. In seeking this deal, Trump has backed away from his threat of new sanctions on Moscow, despite calls to impose more economic pressure.
kra10 at
https://kra20-cc.com
BryanMok
21 Aug 25 at 11:03 pm
Нужен массаж? https://doctu.ru – профессиональные мастера, широкий выбор техник: классический, оздоровительный, лимфодренажный, детский. Доступные цены и уютная атмосфера.
doctu-123
21 Aug 25 at 11:08 pm
You are so awesome! I don’t suppose I’ve truly read a single thing like that before.
So nice to discover another person with a few unique thoughts
on this topic. Seriously.. thank you for starting this up.
This web site is one thing that is required on the web, someone with some
originality!
pedofil
21 Aug 25 at 11:11 pm
What we’re covering
• Zelensky in Washington: Ukrainian President Volodymyr Zelensky has arrived in Washington, DC, where he will be joined by key European leaders when he meets with Donald Trump this afternoon. Trump says Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra16-cc.com]kra20 cc[/url]
• Potential security guarantees: At last week’s summit with Trump, President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kpa19.at]kra11 at[/url]
• Change in tactics: Trump is now focused on securing a peace deal without pursuing a ceasefire due to his progress with Putin, Witkoff said. In seeking this deal, Trump has backed away from his threat of new sanctions on Moscow, despite calls to impose more economic pressure.
kra10 cc
https://kra16-at.com
Robertgew
21 Aug 25 at 11:11 pm
Мы готовы предложить документы институтов, которые находятся на территории всей РФ. Заказать диплом любого университета:
[url=http://foutadjallon.com/index.php/Купить_Аттестат./]купить настоящий аттестат за 11 классов[/url]
Diplomi_dgPn
21 Aug 25 at 11:14 pm
Обучающие курсы онлайн складчина новые навыки для работы и жизни. IT, дизайн, менеджмент, языки, маркетинг. Гибкий график, практика и сертификаты по итогам.
skladchik-941
21 Aug 25 at 11:14 pm