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=http://www.kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru]продвижение сайта[/url] .
kompanii zanimaushiesya prodvijeniem saitov_mboi
4 Sep 25 at 2:18 am
заказать продвижение сайта в москве [url=http://internet-agentstvo-prodvizhenie-sajtov-seo.ru]заказать продвижение сайта в москве[/url] .
internet agentstvo prodvijenie saitov seo_jpot
4 Sep 25 at 2:21 am
фабрика по пошиву одежды [url=www.nitkapro.ru]www.nitkapro.ru[/url] .
shveinoe proizvodstvo_rpea
4 Sep 25 at 2:23 am
Some mirtazapine missed dose sold with amazing discounts by a specialist site mirtazapine 30mg tablet
NtctFlulk
4 Sep 25 at 2:24 am
купить аттестат за 11 класс [url=https://educ-ua5.ru]купить аттестат за 11 класс[/url] .
Diplomi_cqKl
4 Sep 25 at 2:24 am
Hi there, I wish for to subscribe for this weblog to get latest updates, thus
where can i do it please assist.
تکنولوژیست جراحی
4 Sep 25 at 2:25 am
J’apprecie enormement Betzino Casino, on dirait une experience de jeu electrisante. La gamme de jeux est tout simplement phenomenale, avec des machines a sous modernes comme Sweet Bonanza et Book of Dead. Le service client est exceptionnel, avec un suivi de qualite. Les transactions, y compris en cryptomonnaies comme Bitcoin, sont bien protegees, bien que plus de tours gratuits seraient un atout. Dans l’ensemble, Betzino Casino vaut pleinement le detour pour les joueurs en quete d’adrenaline ! De plus le design est visuellement attrayant avec des personnages animes, facilite chaque session de jeu.
betzino maintenance|
Marvinmay3zef
4 Sep 25 at 2:27 am
интернет агентство продвижение сайтов сео [url=www.internet-agentstvo-prodvizhenie-sajtov-seo.ru/]www.internet-agentstvo-prodvizhenie-sajtov-seo.ru/[/url] .
internet agentstvo prodvijenie saitov seo_ppot
4 Sep 25 at 2:28 am
Viagra sans ordonnance livraison 48h: viagra generique efficace – viagra femme
AnthonyFup
4 Sep 25 at 2:30 am
продвижение в google [url=poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru]poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru[/url] .
poiskovoe prodvijenie saita v internete moskva_blMa
4 Sep 25 at 2:31 am
Hi! I’ve been following your website for some
time now and finally got the bravery to go ahead and give you a shout
out from Humble Tx! Just wanted to mention keep up the fantastic work!
sarang188
4 Sep 25 at 2:32 am
tapered roller bearing
GregoryIdons
4 Sep 25 at 2:34 am
В Химках многие уже обращались за помощью в Stop Alko — здесь умеют мягко и безопасно вывести из запоя, сохранив здоровье пациента.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-himki13.ru/]вывод из запоя цена в подольске[/url]
StewartNam
4 Sep 25 at 2:34 am
интернет агентство продвижение сайтов сео [url=https://www.kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru]https://www.kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru[/url] .
kompanii zanimaushiesya prodvijeniem saitov_gqoi
4 Sep 25 at 2:36 am
компании занимающиеся продвижением сайтов [url=https://internet-prodvizhenie-moskva.ru]компании занимающиеся продвижением сайтов[/url] .
internet prodvijenie moskva_stOr
4 Sep 25 at 2:38 am
Ӏts like you reaɗ my mind! Yoս appеar to know a lоt ab᧐ut this, like you wrote
thhe book in it oг something. Ӏ think that you cߋuld ɗo ᴡith ɑ few pics to drive tһe message home a
bit, Ƅut other than that, this iss ɡreat blog.
An excellent read. I’ll certainly ƅe back.
Heere is mʏ blog – sec 3 maths tuition rates
sec 3 maths tuition rates
4 Sep 25 at 2:39 am
профессиональное продвижение сайтов [url=www.internet-agentstvo-prodvizhenie-sajtov-seo.ru/]профессиональное продвижение сайтов[/url] .
internet agentstvo prodvijenie saitov seo_xrot
4 Sep 25 at 2:41 am
I’m amazed, I must say. Seldom do I come across a blog that’s both equally
educative and interesting, and without a doubt, you’ve hit the nail on the head.
The issue is something that not enough folks are speaking intelligently
about. I’m very happy that I stumbled across this during
my search for something relating to this.
카드깡업체
4 Sep 25 at 2:42 am
Je suis totalement seduit par Casino Action, ca procure une experience de jeu exaltante. La selection de jeux est impressionnante avec plus de 1000 titres, comprenant des jackpots progressifs comme Millionaires’ Club. Le support est ultra-reactif et disponible 24/7, offrant des reponses claires et precises. Le processus de retrait est simple et fiable, occasionnellement plus de tours gratuits seraient un atout. Pour conclure, Casino Action vaut pleinement le detour pour ceux qui aiment parier ! En bonus la navigation est rapide sur mobile via iOS/Android, ce qui amplifie le plaisir de jouer.
casino action -bonus|
Francismary8zef
4 Sep 25 at 2:46 am
купить срочно диплом о высшем образовании вуза [url=https://educ-ua5.ru]купить срочно диплом о высшем образовании вуза[/url] .
Diplomi_ybKl
4 Sep 25 at 2:46 am
seo аудит веб сайта [url=https://poiskovoe-prodvizhenie-moskva-professionalnoe.ru]seo аудит веб сайта[/url] .
poiskovoe prodvijenie moskva professionalnoe prodvijenie saitov_mxkn
4 Sep 25 at 2:48 am
โพสต์นี้ ให้ข้อมูลดี ครับ
ผม ได้อ่านบทความที่เกี่ยวข้องกับ เนื้อหาในแนวเดียวกัน
สามารถอ่านได้ที่ สล็อตออนไลน์
เหมาะกับคนที่สนใจเรื่องนี้
มีการเรียบเรียงที่อ่านแล้วลื่นไหล
ขอบคุณที่แชร์ เนื้อหาที่น่าสนใจ
นี้
และหวังว่าจะมีข้อมูลใหม่ๆ มาแบ่งปันอีก
สล็อตออนไลน์
4 Sep 25 at 2:50 am
продвинуть сайт в москве [url=www.internet-agentstvo-prodvizhenie-sajtov-seo.ru]www.internet-agentstvo-prodvizhenie-sajtov-seo.ru[/url] .
internet agentstvo prodvijenie saitov seo_hjot
4 Sep 25 at 2:50 am
купить диплом в кировограде [url=http://educ-ua5.ru/]http://educ-ua5.ru/[/url] .
Diplomi_ccKl
4 Sep 25 at 2:52 am
Very nice post. I just stumbled upon your weblog and wished to say that
I have truly enjoyed browsing your blog posts.
In any case I will be subscribing to your feed and
I hope you write again soon!
تفاوت روانشناسی بالینی و عمومی نی نی سایت
4 Sep 25 at 2:53 am
продвижения сайта в google [url=http://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/]http://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/[/url] .
kompanii zanimaushiesya prodvijeniem saitov_tdoi
4 Sep 25 at 2:53 am
поисковое продвижение сайта в интернете москва [url=http://internet-agentstvo-prodvizhenie-sajtov-seo.ru]поисковое продвижение сайта в интернете москва[/url] .
internet agentstvo prodvijenie saitov seo_elot
4 Sep 25 at 2:56 am
продвижения сайта в google [url=https://www.poiskovoe-prodvizhenie-moskva-professionalnoe.ru]продвижения сайта в google[/url] .
poiskovoe prodvijenie moskva professionalnoe prodvijenie saitov_fakn
4 Sep 25 at 2:58 am
интернет продвижение москва [url=https://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/]https://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/[/url] .
kompanii zanimaushiesya prodvijeniem saitov_hqoi
4 Sep 25 at 3:00 am
швейное предприятие [url=https://nitkapro.ru]https://nitkapro.ru[/url] .
shveinoe proizvodstvo_urea
4 Sep 25 at 3:02 am
Sweet blog! I found it while searching on Yahoo News.
Do you have any suggestions on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Cheers
زهرا شمسایی
4 Sep 25 at 3:03 am
Educating yourself about micro-deposit scams can help you identify these
transactions.
kivs11.de/der-vorteil-von-bausteinen/
4 Sep 25 at 3:03 am
частный seo оптимизатор [url=http://internet-agentstvo-prodvizhenie-sajtov-seo.ru]частный seo оптимизатор[/url] .
internet agentstvo prodvijenie saitov seo_nzot
4 Sep 25 at 3:04 am
продвижения сайта в google [url=https://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/]https://kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru/[/url] .
kompanii zanimaushiesya prodvijeniem saitov_cfoi
4 Sep 25 at 3:04 am
What’s ᥙp t᧐ еvery one, it’s truly a fastidious for me to pay ɑ visit tһis site, іt incⅼudes helpful
Іnformation.
Ηere іs my web blog; https://www.letmejerk.com
https://www.letmejerk.com
4 Sep 25 at 3:04 am
фабрика по пошиву [url=www.nitkapro.ru]www.nitkapro.ru[/url] .
shveinoe proizvodstvo_hlea
4 Sep 25 at 3:06 am
https://eduardoeyoh909.cavandoragh.org/behind-the-scenes-18720-hours-of-work-that-power-the-national-countertop-rankings
Every homeowner dreams of having a beautiful countertop that adds value their kitchen or bathroom.
Did you know that in the latest ranking, only just a fraction companies earned a spot in the Top Countertop Contractors Ranking out of over ten thousand evaluated? That’s because at we only recognize excellence.
Our ranking is transparent, kept current, and built on more than 20 criteria. These include ratings from Google, Yelp, and other platforms, affordability, customer service, and results. On top of that, we conduct 5,000+ phone calls and 2,000 estimate requests through our mystery shopper program.
The result is a trusted guide that benefits both homeowners and installation companies. Homeowners get a safe way to choose contractors, while listed companies gain prestige, online authority, and even direct client leads.
The Top 500 Awards spotlight categories like Best Old Contractors, Emerging Leaders, and Most Affordable Contractors. Winning one of these honors means a company has achieved rare credibility in the industry.
If you’re looking for a countertop contractor—or your company wants to be listed among the best—this site is where credibility meets opportunity.
JuniorShido
4 Sep 25 at 3:07 am
продвижение сайтов в москве [url=www.poiskovoe-prodvizhenie-moskva-professionalnoe.ru/]продвижение сайтов в москве[/url] .
poiskovoe prodvijenie moskva professionalnoe prodvijenie saitov_tjkn
4 Sep 25 at 3:07 am
Thanks for some other informative site. Where else could I get that type of info written in such an ideal method?
I’ve a venture that I am just now running on, and I have been on the look
out for such information.
My homepage … 스포츠 배팅 분석 토토피아
스포츠 배팅 분석 토토피아
4 Sep 25 at 3:08 am
where can i buy ball bearings
GregoryIdons
4 Sep 25 at 3:08 am
раскрутка сайта москва [url=www.poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru]www.poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru[/url] .
poiskovoe prodvijenie saita v internete moskva_mxMa
4 Sep 25 at 3:09 am
https://500px.com/p/xbetpromocode61?view=photos
CharlesDar
4 Sep 25 at 3:15 am
массовое швейное производство [url=http://nitkapro.ru]http://nitkapro.ru[/url] .
shveinoe proizvodstvo_hlea
4 Sep 25 at 3:16 am
seo network [url=https://poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru/]https://poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru/[/url] .
poiskovoe prodvijenie saita v internete moskva_bxMa
4 Sep 25 at 3:17 am
технического аудита сайта [url=kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru]kompanii-zanimayushchiesya-prodvizheniem-sajtov.ru[/url] .
kompanii zanimaushiesya prodvijeniem saitov_yroi
4 Sep 25 at 3:19 am
When someone writes an article he/she keeps the plan of a
user in his/her mind that how a user can understand it. So that’s
why this article is great. Thanks!
Feel free to surf to my web-site خرید بک لینک
خرید بک لینک
4 Sep 25 at 3:20 am
швейное производство [url=www.nitkapro.ru]www.nitkapro.ru[/url] .
shveinoe proizvodstvo_koea
4 Sep 25 at 3:24 am
It’s actually a nice and helpful piece of information. I am happy that you just
shared this helpful info with us. Please stay us informed like this.
Thank you for sharing.
totoslot777
4 Sep 25 at 3:26 am
купить диплом колледжа недорого [url=https://educ-ua4.ru/]https://educ-ua4.ru/[/url] .
Diplomi_ncPl
4 Sep 25 at 3:26 am
сколько стоит купить диплом [url=www.educ-ua5.ru/]сколько стоит купить диплом[/url] .
Diplomi_weKl
4 Sep 25 at 3:27 am