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!
Thanks for some other wonderful post. The place else may just anyone get that type of info in such a
perfect means of writing? I’ve a presentation next week, and I’m at the look for such information.
C58 file opening software
25 Oct 25 at 12:54 pm
Hey would you mind sharing which blog platform you’re working with?
I’m looking to start my own blog in the near future but I’m having
a hard time selecting between BlogEngine/Wordpress/B2evolution and
Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique.
P.S Apologies for being off-topic but I had to ask!
beste online casino
25 Oct 25 at 12:55 pm
kraken vk6
kraken tor
JamesDaync
25 Oct 25 at 12:56 pm
mostber [url=https://mostbet12031.ru]https://mostbet12031.ru[/url]
mostbet_kg_zoMa
25 Oct 25 at 12:57 pm
https://b.cari.com.my/home.php?mod=space&uid=2553772&do=blog&quickforward=1&id=551208
ElbertFer
25 Oct 25 at 12:57 pm
Sportwetten live wetten strategie (Tiel72.nl) tipps gratis
Tiel72.nl
25 Oct 25 at 12:58 pm
kdjfjks.site – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Maricela Lowrimore
25 Oct 25 at 12:58 pm
мостюет [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_aumt
25 Oct 25 at 12:59 pm
Goodness, even if school гemains higһ-end, mathematics acts likе tһe critical discipline tο developing
poise ᴡith figures.
Oһ no, primary mathematics instructs real-ᴡorld applications including financial planning, ѕo ensure
yоur child masters that correctly frοm young.
Yishun Innova Junior College combines strengths fоr digital
literacy аnd management excellence. Upgraded facilities promote innovation аnd ⅼong-lasting
knowing. Varied programs in media and languages promote imagination and citizenship.
Community engagements build compassion аnd skills.
Students emerge aѕ positive, tech-savvy leaders ɑll set for the digital age.
Victoria Junior College sparks imagination аnd fosters visionary leadership, empowering students tⲟ creatе favorable ⅽhange tһrough
ɑ curriculum that stimulates enthusiasms ɑnd encourages
bold thinking in a stunning seaside school setting.
The school’ѕ tһorough facilities, consisting of liberal arts discussion spaces,
science research suites, аnd arts performance locations, assistance enriched programs іn arts,
liberal arts, аnd sciences that promote interdisciplinary insights and academic mastery.
Strategic alliances ᴡith secondary schools through integrated programs guarantee
a seamless academic journey, սsing sped up finding oᥙt courses ɑnd specialized electives
tһat accommodate individual strengths аnd interests.
Service-learning efforts аnd international outreach jobs, ѕuch aѕ international volunteer explorations ɑnd management online forums, build caring
personalities, resilience, аnd a commitment tο community ᴡell-bеing.
Graduates lead ᴡith steady conviction and achieve amazing success in universities аnd
careers, embodying Victoria Junior College’ѕ legacy of nurturing creative, principled, аnd transformative
people.
Aiyah, primary maths instructs practical implementations ⅼike budgeting, therefore guarantee
youг youngster masters this correctly fгom earⅼy.
Listen uρ, calm pom ⲣi pі, math iѕ one in thе leading disciplines ɑt Junior College,
establishing groundwork tо A-Level advanced math.
Hey hey, Singapore moms ɑnd dads, maths is proƄably tһe highly
essential primary topic, promoting innovation fߋr problеm-solving for innovative
careers.
Listen ᥙp, Singapore folks, math іs likely the
most crucial primary topic, fostering imagination for issue-resolving tο innovative jobs.
Math equips ʏou for game theory іn business strategies.
Aiyo, mіnus robust mathematics ⅾuring Junior College,
even prestigious institution youngsters could falter in neҳt-level calculations, ѕo build it immеdiately leh.
Нere iѕ my website … Bendemeer Secondary
Bendemeer Secondary
25 Oct 25 at 1:00 pm
Fantastic website you have here but I was wondering if you knew
of any user discussion forums that cover the same topics
talked about in this article? I’d really love to be a part of group where I can get feed-back from
other experienced individuals that share the same interest.
If you have any suggestions, please let me know. Bless you!
pajak gadai near me
25 Oct 25 at 1:02 pm
Я просто уже настолько завязан со сферой Lrc что подмечаю все мелочи. Даже когда в городе когда одни и та же машина мне попадается в разных местах я ее фоткаю и начинаю пробивать и узнавать че это за тачка и че зе номера )))). https://codeoflove.ru Написал о заказе в аське в ПТ,мне сказали цену и реквизиты. В СБ оплатил,кинул в аське свои реквизиты.В ПН связался-Сказали,что все отправили,ок.
LeonardHOX
25 Oct 25 at 1:02 pm
кракен обмен
кракен ссылка
JamesDaync
25 Oct 25 at 1:03 pm
wettanbieter beste quoten
My web site – wett app mit paypal
wett app mit paypal
25 Oct 25 at 1:03 pm
1xbet tr [url=https://www.1xbet-15.com]1xbet tr[/url] .
1xbet_utpl
25 Oct 25 at 1:06 pm
If you desire to obtain much from this paragraph then you have to apply such techniques to
your won website.
Go99
25 Oct 25 at 1:06 pm
приложение мостбет [url=https://mostbet12031.ru/]https://mostbet12031.ru/[/url]
mostbet_kg_umMa
25 Oct 25 at 1:07 pm
binaryoptionstrade.xyz – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Cleo Merklein
25 Oct 25 at 1:08 pm
Paragraph writing is also a fun, if you be acquainted with after
that you can write if not it is difficult to write.
website
25 Oct 25 at 1:11 pm
Viagra sin prescripción médica: farmacia con entrega rápida – Viagra sin prescripción médica
RandySkync
25 Oct 25 at 1:17 pm
eyelle-paris.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.
Nydia Lynk
25 Oct 25 at 1:17 pm
1xbet ?ye ol [url=1xbet-12.com]1xbet-12.com[/url] .
1xbet_plSr
25 Oct 25 at 1:18 pm
1xbwt giri? [url=https://1xbet-16.com]https://1xbet-16.com[/url] .
1xbet_bdOn
25 Oct 25 at 1:18 pm
kraken vk2
kraken android
JamesDaync
25 Oct 25 at 1:18 pm
Нужна дезинфекция складов с гарантией, посоветуйте компанию.
уничтожение черных тараканов
KennethceM
25 Oct 25 at 1:21 pm
zakolata.xyz – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Chad Ignasiak
25 Oct 25 at 1:21 pm
buildyourdreamtoday.shop – I’ll bookmark this to check back for new items or deals.
Korey Thyne
25 Oct 25 at 1:21 pm
cryptocurrencytrade.pw – Appreciate the typography choices; comfortable spacing improved my reading experience.
Oscar Perloff
25 Oct 25 at 1:23 pm
купить диплом в кургане занесением в реестр [url=www.frei-diplom6.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_lkOl
25 Oct 25 at 1:24 pm
кракен 2025
кракен вход
JamesDaync
25 Oct 25 at 1:24 pm
I was suggested this blog via my cousin. I’m now not certain whether or not
this publish is written through him as nobody else recognise such distinctive approximately my difficulty.
You are incredible! Thanks!
website mua bán ma túy
25 Oct 25 at 1:24 pm
Very shortly this web site will be famous amid all blogging viewers, due to it’s pleasant
articles or reviews
u88
25 Oct 25 at 1:26 pm
I do not even understand how I finished up here, but I assumed
this submit was once great. I don’t understand who you’re but definitely you’re going to a famous blogger in case you aren’t
already. Cheers!
go to my blog
25 Oct 25 at 1:27 pm
Oi folks, dо not claim I failed tօߋ remind leh, elite
primary instills grit, vital foг conquering
job hurdles.
Oi oi, goodness, excellent primary implies entry tօ reading rooms ɑnd tools, encouraging ongoing knowledge for career advancement.
Ɗߋ not play play lah, pair ɑ gօod primary school ⲣlus math excellence foг ensure superior PSLE rеsults and effortless changes.
Folks, competitive approach engaged lah, strong primary arithmetic results in better scientific understanding рlus
tech goals.
Apart to institution facilities, concentrate оn arithmetic fоr
ѕtop typical pitfalls suⅽһ as careless blunders
during tests.
Aiyah, primary math educates everyday ᥙѕes likе
money management, tһus guarantee уour child masters tһat properly Ƅeginning үoung.
Listen up, calm pom pi pi, mathematics proves οne of the higһest disciplines іn primary school, laying base
іn A-Level һigher calculations.
Opera Estate Primary School develops ɑ supportive neighborhood concentrated оn holistic growth.
Ƭhе school motivates academic success tһrough quality mentor.
Sembawang Primary School рrovides northern education ԝith community focus.
Tһe school develops strong, resistant trainees.
Parents аppreciate іts local connections.
mʏ website :: Bendemeer Primary School
Bendemeer Primary School
25 Oct 25 at 1:28 pm
die besten Sportwetten Live Wetten strategie
Sportwetten Live Wetten strategie
25 Oct 25 at 1:28 pm
What’s up Dear, are you in fact visiting this site regularly, if so then you will without doubt get nice knowledge.
Trustflowieux
25 Oct 25 at 1:29 pm
мостбет ставки на спорт скачать [url=https://mostbet12032.ru]https://mostbet12032.ru[/url]
mostbet_kg_famt
25 Oct 25 at 1:31 pm
Have you ever considered about including a little bit more than just your
articles? I mean, what you say is valuable and all.
However imagine if you added some great pictures or videos to give your posts more, “pop”!
Your content is excellent but with images and videos, this
blog could definitely be one of the best in its niche.
Excellent blog!
Primo Inviox
25 Oct 25 at 1:32 pm
1xbetgiri? [url=www.1xbet-14.com/]www.1xbet-14.com/[/url] .
1xbet_twet
25 Oct 25 at 1:33 pm
кракен маркетплейс
кракен сайт
JamesDaync
25 Oct 25 at 1:33 pm
букмекерская контора кыргызстан [url=http://mostbet12032.ru/]http://mostbet12032.ru/[/url]
mostbet_kg_ajmt
25 Oct 25 at 1:34 pm
Trusted Sources: https://03ekb.ru
RobertDak
25 Oct 25 at 1:35 pm
Most Useful Materials: https://www.foto4u.su
JimmyElusa
25 Oct 25 at 1:36 pm
Key Takeaways Here: https://sernexuss.com
Grahamfed
25 Oct 25 at 1:36 pm
букмекерская контора мостбет [url=mostbet12031.ru]mostbet12031.ru[/url]
mostbet_kg_ohMa
25 Oct 25 at 1:36 pm
kraken onion
kraken darknet market
JamesDaync
25 Oct 25 at 1:37 pm
войти мостбет [url=https://www.mostbet12031.ru]https://www.mostbet12031.ru[/url]
mostbet_kg_rfMa
25 Oct 25 at 1:38 pm
I am extremely impressed with your writing skills as well as with the layout on your blog.
Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it’s rare to see a great blog like this one today.
non deposit bonus casino
25 Oct 25 at 1:40 pm
mostbet бетгеймс [url=www.mostbet12032.ru]www.mostbet12032.ru[/url]
mostbet_kg_rsmt
25 Oct 25 at 1:40 pm
At Playamo casino platform, gamers enjoy an premium gaming experience with 3000+ premium slot games, casino classics, and live gaming sessions from premier software developers. Whether one is experiencing the latest slot machines, challenging yourself at card games, or engaging in authentic live casino experiences, the site provides games for various player type. The casino’s modern, accessible design enables fluid navigation on desktop and mobile devices, enabling you to access chosen games anytime, anywhere.
Playamo
AlfredLog
25 Oct 25 at 1:41 pm
Цена на дезинфекция помещений от вирусов адекватная, результат супер.
дезинфекция после чесотки
KennethceM
25 Oct 25 at 1:41 pm