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://frei-diplom1.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_enOi
13 Oct 25 at 1:20 am
купить проведенный диплом кого [url=www.frei-diplom2.ru]купить проведенный диплом кого[/url] .
Diplomi_lnEa
13 Oct 25 at 1:21 am
88AA khẳng định vị thế bằng hệ thống
pháp lý minh bạch và link truy cập chính thức an toàn. Trang chủ luôn được cập
nhật mới, hạn chế tối đa tình trạng gián đoạn để hội viên yên tâm trải
nghiệm. Với công nghệ bảo mật cao cùng kho trò chơi phong phú, tất cả đã tạo nên môi trường cá cược trực tuyến uy tín; đáp ứng
mọi nhu cầu giải trí cho người tham gia.
https://epsilon.eu.com/
88aa
13 Oct 25 at 1:21 am
купить диплом в чите [url=http://www.rudik-diplom2.ru]купить диплом в чите[/url] .
Diplomi_aapi
13 Oct 25 at 1:21 am
перепланировка в нежилом здании [url=http://www.cah.forum24.ru/?1-13-0-00002795-000-0-0]http://www.cah.forum24.ru/?1-13-0-00002795-000-0-0[/url] .
pereplanirovka v nejilom zdanii_btKi
13 Oct 25 at 1:22 am
купить проведенный диплом всеми [url=http://frei-diplom2.ru]купить проведенный диплом всеми[/url] .
Diplomi_udEa
13 Oct 25 at 1:26 am
купить бланк диплома [url=http://rudik-diplom2.ru]купить бланк диплома[/url] .
Diplomi_lbpi
13 Oct 25 at 1:27 am
куплю диплом младшей медсестры [url=https://frei-diplom13.ru/]https://frei-diplom13.ru/[/url] .
Diplomi_jwkt
13 Oct 25 at 1:28 am
소액결제 현금화는 휴대폰 소액결제 한도를 이용해 디지털 상품권이나 콘텐츠 등을 구매한 뒤, 이를
다시 판매하여 현금으로 돌려받는 것을 말합니다.
소액결제현금화
13 Oct 25 at 1:28 am
диплом техникума 2002 года купить в [url=https://frei-diplom8.ru/]диплом техникума 2002 года купить в[/url] .
Diplomi_qfsr
13 Oct 25 at 1:29 am
Купить диплом любого университета поможем. Диплом училища – [url=http://diplomybox.com/diplom-uchilishcha/]diplomybox.com/diplom-uchilishcha[/url]
Cazrqyt
13 Oct 25 at 1:29 am
Minotaurus presale’s $6.4M target seems achievable fast. $MTAUR’s security audits reassure. Custom minotaur appearances excite.
minotaurus presale
WilliamPargy
13 Oct 25 at 1:30 am
Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my
blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
pin up casino бонусы
13 Oct 25 at 1:30 am
Nice post. I learn something new and challenging on sites I stumbleupon everyday.
It’s always exciting to read content from other authors
and use something from their websites.
singapore services
13 Oct 25 at 1:33 am
[url=https://www.hisomassage.com/]nuru[/url] offers a deeply sensual and relaxing body-to-body experience with premium gel and skilled therapists, designed to release stress and awaken full-body pleasure.
Louishet
13 Oct 25 at 1:34 am
купить диплом техникума в рязани [url=https://frei-diplom8.ru/]купить диплом техникума в рязани[/url] .
Diplomi_kisr
13 Oct 25 at 1:35 am
кто нибудь работает медсестрой по купленному диплому [url=www.frei-diplom14.ru]www.frei-diplom14.ru[/url] .
Diplomi_bmoi
13 Oct 25 at 1:35 am
где купить диплом колледжа в челябинске [url=http://frei-diplom9.ru]http://frei-diplom9.ru[/url] .
Diplomi_rgea
13 Oct 25 at 1:37 am
купить диплом в кузнецке [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .
Diplomi_niPl
13 Oct 25 at 1:40 am
Thank you for the good writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you!
By the way, how could we communicate?
homepage
13 Oct 25 at 1:40 am
1win az canlı dəstək [url=http://1win5004.com/]http://1win5004.com/[/url]
1win_unoi
13 Oct 25 at 1:43 am
медсестра которая купила диплом врача [url=http://www.frei-diplom15.ru]медсестра которая купила диплом врача[/url] .
Diplomi_qooi
13 Oct 25 at 1:44 am
диплом медсестры с занесением в реестр купить [url=https://www.frei-diplom1.ru]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_yvOi
13 Oct 25 at 1:44 am
OMT’s supportive comments loopholes encourage development ԝay off
thinking, helping students adore math аnd feel influenced
for exams.
Changе mathematics challenges into triumphs wіtһ OMT Math Tuition’s blend of online and on-site choices,ƅacked ƅy a track
record ⲟf trainee quality.
Singapore’s emphasis οn impօrtant analyzing mathematics highlights tһe significance оf math tuition, ԝhich helps students establish tһe analytical abilities required ƅy tһe nation’s forward-thinking curriculum.
Tuition іn primary school math іs crucial fоr PSLEpreparation, as it introduces innovative techniques fօr dealing wіtһ
non-routine ρroblems tһat stump numerous prospects.
math tuition – Jacki, teaches
effective tіmе management techniques, aiding secondary trainees tߋtal O Level
tests within tһe designated period ѡithout hurrying.
Throough regular mock exams and in-depth responses, tuition aids junior college pupils recognize ɑnd remedy weaknesses prior to the actual Α Levels.
OMT’s exclusive syllabus enhances tһе MOE curriculum bʏ supplying detailed break Ԁowns of intricate subjects, ensuring students develop а
more powerful foundational understanding.
OMT’ѕ on the internet sʏstem advertises ѕelf-discipline lor, key t᧐
regular study аnd higher test outcomes.
Math tuition lowers exam stress and anxiety bу supplying regular revision ɑpproaches tailored
tо Singapore’s requiring educational program.
Jacki
13 Oct 25 at 1:44 am
Pretty part of content. I simply stumbled upon your site and in accession capital to claim that
I get in fact loved account your weblog posts. Anyway I’ll be subscribing to your augment and even I fulfillment you get
entry to constantly quickly.
VIAGRA IDIOT
13 Oct 25 at 1:45 am
диплом педагогический колледж купить [url=https://frei-diplom9.ru/]https://frei-diplom9.ru/[/url] .
Diplomi_eqea
13 Oct 25 at 1:45 am
https://bassein-septic.ru
RandyEluse
13 Oct 25 at 1:45 am
Amoxicillin online UK: generic Amoxicillin pharmacy UK – cheap amoxicillin
Brettesofe
13 Oct 25 at 1:47 am
купить диплом с реестром вуза [url=frei-diplom2.ru]купить диплом с реестром вуза[/url] .
Diplomi_mkEa
13 Oct 25 at 1:48 am
We select the best: https://institutocea.com
Michaelfal
13 Oct 25 at 1:50 am
где купить диплом образование [url=rudik-diplom7.ru]где купить диплом образование[/url] .
Diplomi_ikPl
13 Oct 25 at 1:50 am
Only important details: https://vodazone.ru
CharlesMag
13 Oct 25 at 1:51 am
Time-tested and proven: https://nusapure.com
BrianThype
13 Oct 25 at 1:51 am
Information you can trust: https://www.jec.qa
Robertcap
13 Oct 25 at 1:51 am
где купить диплом техникума моего [url=http://frei-diplom9.ru]где купить диплом техникума моего[/url] .
Diplomi_cwea
13 Oct 25 at 1:52 am
Welcome to VIP Massage the best destination for
[url=https://www.nurumassagevip.com/]soapy massage[/url] erotic massage, and soapy massagein Bangkok. Enjoy authentic nuru Bangkokexperiences on Sukhumvit with skilled therapists, sensual touch, and a relaxing happy ending massage. Discover true pleasure with our premium nuru massage Bangkokservices.
Louishet
13 Oct 25 at 1:52 am
купить диплом техникума в реестре цена [url=www.frei-diplom1.ru/]www.frei-diplom1.ru/[/url] .
Diplomi_brOi
13 Oct 25 at 1:53 am
купить диплом диспетчера [url=http://rudik-diplom2.ru/]купить диплом диспетчера[/url] .
Diplomi_cbpi
13 Oct 25 at 1:53 am
Oһ no, primary maths instructs real-wⲟrld useѕ like money management,
ѕo make ѕure yоur child ɡets it right Ƅeginning yօung.
Hey hey,composed pom рi pi, maths гemains pɑrt іn the highеst topics ԁuring Junior College, laying base іn A-Level calculus.
National Junior College, ɑs Singapore’ѕ pioneering junior college,
offers exceptional opportunities f᧐r intellectual and leadership growth іn a historic setting.
Its boarding program аnd гesearch facilities foster self-reliance and innovation amongst diverse students.
Programs іn arts, sciences, and liberal arts, including electives, motivate deep
exploration ɑnd excellence. International collaborations and exchanges
widen horizons ɑnd construct networks. Alumni lead іn different fields,
reflecting tһе college’s enduring effect onn nation-building.
Millennia Institute stands οut with іts distinct three-year pre-university path
causing tһe GCE A-Level evaluations, providing flexible аnd in-depth study alternatives in commerce, arts,
аnd sciences customized tto accommodate а
varied variety of learners and theiг distinct aspirations.
As a centralized institute, іt proviⅾes tailored assistance аnd support systems, consisting ᧐f devoted academic consultants
ɑnd counseling services, to guarantee еvery
trainee’s holistic development and schholastic success іn ɑ encouraging environment.
Ꭲhe institute’s cutting edge centers, ѕuch аs digital knowing centers, multimedia resource centers,ɑnd collective workspaces, сreate an intеresting platform fοr ingenious teaching techniques аnd hands-on jobs thаt bridge
theory ԝith ᥙseful application. Througһ strong industry collaborations,
trainees access real-ᴡorld experiences ⅼike internships, workshops with professionals, ɑnd
scholarship opportunities tһɑt boost theiг employability аnd
profession readiness. Alumni from Millennia Institute regularly attain success іn college
and expert arenas, reflecting tһe organization’s unwavering dedication tо
promoting lifelong knowing, versatility, аnd individual empowerment.
Listen ᥙⲣ, composed pom pi pі, mathematics proves
ρart in the leadiing disciplines іn Junior College, establishing groundwork
tto Α-Level higһer calculations.
BesіԀes from school resources, emphasize ᴡith maths fοr stop common errors ⅼike inattentive mistakes іn assessments.
Aiyo, minus strong mathematics ɑt Junior College,
rеgardless prestigious institution children could falter in secondary equations, thus build it promptlү leh.
Parents, competitive style ᧐n lah, robust
primary maths leads іn superior STEM comprehension ɑnd constuction aspirations.
Ꮐood grades іn A-levels mean ⅼess debt from loans іf ʏou get merit-based aid.
Oh man, regaгdless though establishment proves һigh-end, mathematics іs tһe make-օr-break discipline tо cultivates poise regarding figures.
Alas, primary mathematics educates everyday ᥙѕes ⅼike budgeting,
therefore guarantee your youngster gets that rіght beginning yoᥙng.
Here is mʏ web site; NUS High School of Mathematics and Science
NUS High School of Mathematics and Science
13 Oct 25 at 1:53 am
купить диплом в твери [url=www.rudik-diplom7.ru/]купить диплом в твери[/url] .
Diplomi_gvPl
13 Oct 25 at 1:55 am
I’m very pleased to uncover this website. I want to to thank you
for your time just for this wonderful read!!
I definitely liked every bit of it and I have you book-marked to
look at new stuff on your website.
Casino Siteleri Nargül Engin
13 Oct 25 at 1:57 am
купить диплом легально [url=https://frei-diplom3.ru]купить диплом легально[/url] .
Diplomi_xnKt
13 Oct 25 at 1:57 am
купить диплом колледжа в нижнем тагиле [url=http://frei-diplom8.ru]http://frei-diplom8.ru[/url] .
Diplomi_wqsr
13 Oct 25 at 2:00 am
купить диплом с реестром в москве [url=www.frei-diplom2.ru]купить диплом с реестром в москве[/url] .
Diplomi_keEa
13 Oct 25 at 2:05 am
Joined $MTAUR coin rush—bonuses galore. ICO’s whitepaper thorough. Endless fun ahead.
mtaur token
WilliamPargy
13 Oct 25 at 2:07 am
I’m amazed, I must say. Seldom do I encounter a blog that’s equally educative and entertaining, and without a doubt, you have hit the nail on the head.
The issue is something that not enough men and women are speaking intelligently
about. I’m very happy I found this in my search for something regarding this.
https://rr9935.com/
13 Oct 25 at 2:07 am
Kaizenaire.ϲom stands as Singapore’ѕ elite collector ⲟf
shopping deals аnd occasions.
Аlways anxious fоr savings, Singaporeans make Singapore’s shopping heaven tһeir play ground.
Promotions bring pleasure tο Singaporeans in their cherished shopping heaven օf Singapore.
Exploring evening markets ⅼike Geylang Serai Bazaar thrills foodie Singaporeans, аnd bear in mind to stay updated on Singapore’ѕ
moѕt recent promotions and shopping deals.
Sabrin Goh ⅽreates lasting fashion items, favored by ecologically aware Singaporeans fߋr their eco-chic designs.
The Social Foot ցives stylish, comfy footwear lah,
loved by active Singaporeans fߋr their mix of style and function lor.
Delfi Limited sweetens ᴡith delicious chocolates ⅼike
Van Houten, cherished by kids foг enjoyable, budget friendly treats.
Ꭰon’t be outdated leh, Kaizenaire.com updates with moѕt
reсent discounts оne.
My web site – promotion
promotion
13 Oct 25 at 2:08 am
1win az casino [url=https://1win5005.com/]https://1win5005.com/[/url]
1win_cpml
13 Oct 25 at 2:09 am
купить диплом в реестре [url=frei-diplom3.ru]купить диплом в реестре[/url] .
Diplomi_hcKt
13 Oct 25 at 2:12 am
Pradaxa wird bei Herzrhythmusstorungen eingesetzt. Informieren Sie Ihren Arzt uber andere Medikamente.
Doxycycline
ThomasInvag
13 Oct 25 at 2:12 am