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=https://blog-o-marketinge1.ru/]стратегия продвижения блог[/url] .
blog o marketinge_tvsa
9 Sep 25 at 3:30 am
http://110km.ru/
EdwardMox
9 Sep 25 at 3:32 am
mostbet qeydiyyat olmadan giriş [url=https://mostbet4144.ru]https://mostbet4144.ru[/url]
mostbet_bxKa
9 Sep 25 at 3:36 am
лечение запоя
vivod-iz-zapoya-krasnodar015.ru
лечение запоя
izzapoyakrasnodarNeT
9 Sep 25 at 3:36 am
блог seo агентства [url=https://blog-o-marketinge1.ru/]blog-o-marketinge1.ru[/url] .
blog o marketinge_fdsa
9 Sep 25 at 3:36 am
seo онлайн [url=https://kursy-seo-3.ru]https://kursy-seo-3.ru[/url] .
kyrsi seo_djon
9 Sep 25 at 3:37 am
It’s an amazing article in favor of all the internet viewers; they will get advantage from it I am sure.
Paragonix Earn
9 Sep 25 at 3:38 am
Когда организм на пределе, важна срочная помощь в Самаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Подробнее можно узнать тут – https://vyvod-iz-zapoya-v-stacionare-samara.ru/
Everetttam
9 Sep 25 at 3:40 am
стратегия продвижения блог [url=www.blog-o-marketinge1.ru/]стратегия продвижения блог[/url] .
blog o marketinge_rwsa
9 Sep 25 at 3:40 am
mostbet qanunidirmi [url=https://mostbet4140.ru/]mostbet qanunidirmi[/url]
mostbet_uoKr
9 Sep 25 at 3:41 am
mostbet aviator qeydiyyat [url=https://mostbet4144.ru/]https://mostbet4144.ru/[/url]
mostbet_yfKa
9 Sep 25 at 3:42 am
I don’t even know the way I ended up right here, but I thought this publish was great.
I don’t realize who you’re however definitely you are going to a well-known blogger when you
are not already. Cheers!
赌场
9 Sep 25 at 3:43 am
продвижение обучение [url=kursy-seo-2.ru]kursy-seo-2.ru[/url] .
kyrsi seo_ooEr
9 Sep 25 at 3:50 am
блог интернет-маркетинга [url=https://blog-o-marketinge1.ru/]блог интернет-маркетинга[/url] .
blog o marketinge_yssa
9 Sep 25 at 3:52 am
блог про продвижение сайтов [url=http://statyi-o-marketinge2.ru]блог про продвижение сайтов[/url] .
stati o marketinge_byKr
9 Sep 25 at 3:53 am
mostbet az giriş [url=https://mostbet4141.ru/]https://mostbet4141.ru/[/url]
mostbet_mfPn
9 Sep 25 at 3:54 am
Oh dear, lacking solid maths іn Junior College, eѵеn prestigious institution kids
mіght falter at next-level equations, ѕo build thɑt now leh.
Anglo-Chinese Junior College stands ɑs a beacon of well balanced education,
blending extensive academics ᴡith ɑ supporting Christian values that motivates moral integrity аnd individual development.
Ƭhe college’ѕ modern centers аnd knowledgeable faculty assistance impressive
performance іn ƅoth arts and sciences, wіth students regularly attaining top
accolades. Ƭhrough its emphasis on sports аnd carrying out arts,
students develop discipline, sociability, аnd an enthusiasm fⲟr excellence Ьeyond tһe classroom.
International partnerships ɑnd exchange chances enhance tһe discovering experience, promoting worldwide awareness
аnd cultural appreciation. Alumni grow іn diverse fields, testimony tо thе college’ѕ function іn forming principled
leaders ready tߋ contribute positively tο society.
Victoria Junior College ignites imagination аnd cultivates visionary
management, empowering trainees tο create positive ϲhange through a curriculum that stimulates enthusiasms аnd motivates vibrant thinking іn a attractive seaside school setting.
Ƭhe school’s detailed facilities, including humanities discussion гooms,
science rеsearch study suites, ɑnd arts performance locations, support enriched programs іn arts, liberal arts, ɑnd sciences tһɑt promote interdisciplinary insights and
scholastic mastery. Strategic alliances ᴡith secondary schools tһrough incorporated programs
mɑke sure a smooth educational journey, providing sped uup discovering paths аnd specialized electives that deal with
individual strengths and interests. Service-learning efforts аnd worldwide outreach tasks, ѕuch ɑs international volunteer
expeditions ɑnd management forums, develop caring dispositions, resilience,
аnd а dedication tߋ community well-bеing. Graduates
lead ԝith steady conviction аnd attain extraordinary success іn universities and professions, embodying Victoria Junior College’ѕ tradition оf supporting imaginative,
principled, and transformative people.
Hey hey, steady pom рi pi, maths is among from the leading subjects аt Junior
College, building foundation tо A-Level calculus.
Ιn additіοn from institution facilities, focus ᥙpon mathematics in οrder tօ stop common pitfalls including sloppy errors ɑt assessments.
Hey hey, calm pom ⲣi pі, mathematics proves paгt in the hіghest
subjects ⅾuring Junior College, building groundwork to A-Level advanced math.
Βesides beyօnd institution facilities, concentrate ᴡith mathematics fοr prevent frequent pitfalls
ѕuch as inattentive errors at exams.
Don’t taқe lightly lah, combine a excellent Junior
College alongside maths excellence tߋ ensure high A Levels scores ρlus
effortless ϲhanges.
Mums ɑnd Dads, fear thе difference hor,
math groundwork proves essential іn Junior College fⲟr understanding
figures, essential for current tech-driven economy.
Оh man, no matter іf establishment is һigh-end, mathematics acts ⅼike the decisive topic іn cultivates
confidence іn calculations.
Βe kiasu and join tuition іf needеԀ; А-levels arе yоur ticket tο financial
independence sooner.
Оh dear, minus strong mathematics ԁuring Junior College, even prestigious
school children mіght stumble in next-level algebra,
therefore develop tһis promptly leh.
My web site … site
site
9 Sep 25 at 3:54 am
mostbet uz oynalgan sayt [url=www.mostbet4173.ru]www.mostbet4173.ru[/url]
mostbet_uoEt
9 Sep 25 at 3:56 am
dark markets dark web market links nexus darknet url [url=https://darknetmarketgate.com/ ]dark market onion [/url]
DwayneAricE
9 Sep 25 at 4:01 am
В Люберцах капельница от запоя может спасти здоровье — в Stop Alko работают опытные наркологи, которые точно знают, как снять интоксикацию без вреда.
Узнать больше – [url=https://kapelnica-ot-zapoya-lyubercy13.ru/]капельница от запоя анонимно подольск[/url]
EdwardSlatt
9 Sep 25 at 4:08 am
купить диплом с занесением в реестр чита [url=www.arus-diplom33.ru]www.arus-diplom33.ru[/url] .
Diplomi_ebSa
9 Sep 25 at 4:13 am
mostbet for iphone [url=http://mostbet4171.ru]mostbet for iphone[/url]
mostbet_weEt
9 Sep 25 at 4:14 am
I always spent my half an hour to read this weblog’s content every day along
with a cup of coffee.
VornethPro
9 Sep 25 at 4:15 am
mostbet poker otağı [url=http://mostbet4143.ru]mostbet poker otağı[/url]
mostbet_urkt
9 Sep 25 at 4:16 am
школа seo [url=kursy-seo-1.ru]kursy-seo-1.ru[/url] .
kyrsi seo_dlmt
9 Sep 25 at 4:16 am
https://rationaltheme.com/wp-content/pgs/?1xbet_promo_code_for_registration_21.html
NathanNah
9 Sep 25 at 4:19 am
Анонимная помощь при запое — врачи «Alco.Rehab» (Москва) приедут к вам в течение часа.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-moskva12.ru/]помощь вывод из запоя москва[/url]
LonnieUnfor
9 Sep 25 at 4:20 am
I loved as much as you’ll receive carried out right here.
The sketch is attractive, your authored subject matter stylish.
nonetheless, you command get got an impatience over that you wish be delivering the following.
unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you
shield this hike.
Meteor Profit
9 Sep 25 at 4:21 am
AutoRent — прокат автомобилей в Минске. Ищете прокат автомобилей Минск? На autorent.by вы можете выбрать эконом, комфорт, бизнес и SUV, оформить онлайн-бронирование и получить авто в день обращения. Честные тарифы, ухоженный автопарк и круглосуточная поддержка. Подача в аэропорт Минск, самовывоз из города. Аренда на сутки и длительный период; доступны детские кресла и дополнительное оборудование.
ukexehob
9 Sep 25 at 4:21 am
материалы по seo [url=www.blog-o-marketinge1.ru]материалы по seo[/url] .
blog o marketinge_zxsa
9 Sep 25 at 4:25 am
школа seo [url=www.kursy-seo-1.ru]www.kursy-seo-1.ru[/url] .
kyrsi seo_rukt
9 Sep 25 at 4:25 am
Hey there! I’m at work browsing your blog from my new apple iphone!
Just wanted to say I love reading your blog and look forward to all your posts!
Carry on the outstanding work!
레비트라 구매
9 Sep 25 at 4:26 am
https://metallobaza31.ru
Chesterkerge
9 Sep 25 at 4:26 am
http://receptbook.ru/wps/archives/3270
ltdmyru
9 Sep 25 at 4:27 am
Open deals galore ɑt Kaizenaire.com, the leading website fⲟr Singapore’s promotions.
Promotions ɑre the lifeline ⲟf Singapore’ѕ shopping heaven,attracting deal-loving Singaporeans fгom alⅼ profession.
Singaporeans commonly cycle νia the PCN network for breathtaking experiences, and remember tⲟ stay updated on Singapore’ѕ
most recent promotions аnd shopping deals.
ComfortDelGro оffers taxi and public transportation services, appreciated ƅy Singaporeans for thеir trusted rides and substantial network аcross the city.
McDonald’ѕ offers junk food faves ⅼike hamburgers ɑnd french fries mah, preferred Ƅү Singaporeans fօr tһeir fast meals and local menu spins ѕia.
ABR Holdings operates Swensen’ѕ and vaгious othuer eateries, enjoyed fⲟr diverse eating chains tһroughout Singapore.
D᧐n’t lag lor, гemain updated with Kaizenaire.com siа.
Ꮇy web page; pinoy in singapore recruitment agencies rejecting singaporean job applications
pinoy in singapore recruitment agencies rejecting singaporean job applications
9 Sep 25 at 4:29 am
mostbet şikayətlər [url=www.mostbet4141.ru]www.mostbet4141.ru[/url]
mostbet_wjPn
9 Sep 25 at 4:29 am
материалы по маркетингу [url=http://blog-o-marketinge1.ru/]материалы по маркетингу[/url] .
blog o marketinge_yusa
9 Sep 25 at 4:31 am
https://evergreenrxusas.shop/# EverGreenRx USA
Robertwhego
9 Sep 25 at 4:33 am
dark market onion nexus market url dark web markets [url=https://privatedarknetmarket.com/ ]dark web drug marketplace [/url]
Robertalima
9 Sep 25 at 4:35 am
mostbet suallar və cavablar [url=http://mostbet4145.ru/]mostbet suallar və cavablar[/url]
mostbet_ybot
9 Sep 25 at 4:36 am
диплом колледжа купить с занесением в реестр [url=www.arus-diplom33.ru/]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_ddSa
9 Sep 25 at 4:36 am
обучение seo [url=http://kursy-seo-4.ru/]обучение seo[/url] .
kyrsi seo_akPl
9 Sep 25 at 4:39 am
EverGreenRx USA: cialis coupon online – EverGreenRx USA
Jamespycle
9 Sep 25 at 4:40 am
Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis.
It’s always helpful to read through content from
other authors and practice something from other sites.
clean-label metabolic supplements
9 Sep 25 at 4:45 am
блог о рекламе и аналитике [url=http://www.statyi-o-marketinge2.ru]http://www.statyi-o-marketinge2.ru[/url] .
stati o marketinge_hbKr
9 Sep 25 at 4:46 am
Good post. I learn something totally new and challenging on websites I stumbleupon everyday.
It will always be interesting to read through content
from other writers and practice something from their web sites.
Massey Roofing & Contracting
9 Sep 25 at 4:46 am
mostbet az virtual oyunlar [url=https://www.mostbet4143.ru]mostbet az virtual oyunlar[/url]
mostbet_klkt
9 Sep 25 at 4:48 am
seo интенсив [url=http://kursy-seo-3.ru]http://kursy-seo-3.ru[/url] .
kyrsi seo_qson
9 Sep 25 at 4:50 am
блог про продвижение сайтов [url=https://www.statyi-o-marketinge2.ru]блог про продвижение сайтов[/url] .
stati o marketinge_ggKr
9 Sep 25 at 4:52 am
интернет маркетинг статьи [url=blog-o-marketinge1.ru]интернет маркетинг статьи[/url] .
blog o marketinge_twsa
9 Sep 25 at 4:57 am