SlideShare a Scribd company logo
1 of 57
What is this DI and AOP stuff anyway...
Friday, June 7, 13
About Me
Currently BBC Sport (Freelancer)
Lived in Japan for 15 years - love sushi
Love frameworks - not just PHP ones
Involved in Lithium and BEAR.Sunday projects
Richard McIntyre - @mackstar
Friday, June 7, 13
Dependency Injection
Friday, June 7, 13
Most Basic Example - Problem
class Mailer
{
private $transport;
public function __construct()
{
$this->transport = 'sendmail';
}
// ...
}
Friday, June 7, 13
Expensive
new Zend_Config_Ini($path, ENV);
Friday, June 7, 13
Easily becomes an inheritance mess
Sport_Lib_Builder_GenericStatsAbstract
Sport_Lib_Builder_GenericStats_Cricket_Table
Sport_Lib_Builder_GenericStats_Cricket_NarrowTable
Sport_Lib_Builder_GenericStats_CricketAbstract
Sport_Lib_API_GenericStats_Cricket
Sport_Lib_API_GenericStatsAbstract
Sport_Lib_Service_SportsData_Cricket
Sport_Lib_Service_SportsData
Sport_Lib_ServiceAbstract
Friday, June 7, 13
DI for a 5 year old
When you go and get things out of the refrigerator for yourself, you can
cause problems. You might leave the door open, you might get something
Mommy or Daddy doesn't want you to have. You might even be looking
for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink
with lunch," and then we will make sure you have something when you
sit down to eat.
Friday, June 7, 13
Something like this...
Application needs Foo, which needs Bar, which needs Bim, so:
Application creates Bim
Application creates Bar and gives it Bim
Application creates Foo and gives it Bar
Application calls Foo
Foo calls Bar
Bar does something
Friday, June 7, 13
The Service Container
Dependency Injection Round 1
Friday, June 7, 13
class Mailer
{
private $transport;
public function __construct($transport)
{
$this->transport = $transport;
}
// ...
}
Symfony2 Example
Friday, June 7, 13
class Mailer
{
private $transport;
public function __construct($transport)
{
$this->transport = $transport;
}
// ...
}
use SymfonyComponentDependencyInjectionContainerBuilder;
$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');
Symfony2 Example
Friday, June 7, 13
class Mailer
{
private $transport;
public function __construct($transport)
{
$this->transport = $transport;
}
// ...
}
use SymfonyComponentDependencyInjectionContainerBuilder;
$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');
use SymfonyComponentDependencyInjectionContainerBuilder;
$container = new ContainerBuilder();
$container
->register('mailer', 'Mailer')
->addArgument('sendmail');
Symfony2 Example
Friday, June 7, 13
class NewsletterManager
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
// ...
}
Friday, June 7, 13
class NewsletterManager
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
// ...
}
use SymfonyComponentDependencyInjectionContainerBuilder;
use SymfonyComponentDependencyInjectionReference;
$container = new ContainerBuilder();
$container->setParameter('mailer.transport', 'sendmail');
$container
->register('mailer', 'Mailer')
->addArgument('%mailer.transport%');
$container
->register('newsletter_manager', 'NewsletterManager')
->addArgument(new Reference('mailer'));
Friday, June 7, 13
use SymfonyComponentDependencyInjectionContainerBuilder;
$container = new ContainerBuilder();
$newsletterManager = $container->get('newsletter_manager');
Friday, June 7, 13
Inversion Of Control
Pattern
The control of the dependencies is inversed from one
being called to the one calling.
Friday, June 7, 13
Container
Newsletter Manager
Mailer
transport = sendmail
Friday, June 7, 13
Container
Newsletter Manager
Mailer
# src/Acme/HelloBundle/Resources/config/
services.yml
parameters:
# ...
mailer.transport: sendmail
services:
mailer:
class: Mailer
arguments: [%mailer.transport%]
newsletter_manager:
class: NewsletterManager
calls:
- [ setMailer, [ @mailer ] ]
transport = sendmail
Friday, June 7, 13
Decoupled Code
Friday, June 7, 13
Tips
Test first in isolation
Don’t need to wire together to test (Eg Environment etc)
integration tests are expensive.
When you do wire together with test/mock classes as needed
Duck Type your code / Use interfaces
Friday, June 7, 13
Friday, June 7, 13
$container = new Pimple();
// define some parameters
$container['cookie_name'] = 'SESSION_ID';
$container['session_storage_class'] = 'SessionStorage';
Friday, June 7, 13
$container = new Pimple();
// define some parameters
$container['cookie_name'] = 'SESSION_ID';
$container['session_storage_class'] = 'SessionStorage';
// define some objects
$container['session_storage'] = function ($c) {
return new $c['session_storage_class']($c['cookie_name']);
};
$container['session'] = function ($c) {
return new Session($c['session_storage']);
};
Friday, June 7, 13
Clever DI with Bindings
Friday, June 7, 13
Laravel 4 example
class MyConcreteClass implements MyInterface
{
Friday, June 7, 13
Laravel 4 example
class MyConcreteClass implements MyInterface
{
class MyClass
{
public function __construct(MyInterface $my_injection)
{
$this->my_injection = $my_injection;
}
}
App::bind('MyInterface', 'MyConcreteClass');
Friday, June 7, 13
Cleverer DI with Injection
Points & Bindings
Friday, June 7, 13
Google Guice
Guice alleviates the need for factories and the use of ‘new’ in
your ‘Java’a code
Think of Guice's @Inject as the new new. You will still need
to write factories in some cases, but your code will not
depend directly on them. Your code will be easier to change,
unit test and reuse in other contexts.
Ray.DI
Friday, June 7, 13
interface MailerInterface {}
PHP Google Guice Clone
Ray.DI
Friday, June 7, 13
class Mailer implements MailerInterface
{
private $transport;
/**
* @Inject
* @Named("transport_type")
*/
public function __construct($transport)
{
$this->transport = $transport;
}
}
interface MailerInterface {}
PHP Google Guice Clone
Ray.DI
Friday, June 7, 13
class Mailer implements MailerInterface
{
private $transport;
/**
* @Inject
* @Named("transport_type")
*/
public function __construct($transport)
{
$this->transport = $transport;
}
}
interface MailerInterface {}
class NewsletterManager
{
public $mailer;
/**
* @Inject
*/
public function __construct(MailerInterface $mailer)
{
$this->mailer = $mailer;
}
}
PHP Google Guice Clone
Ray.DI
Friday, June 7, 13
class NewsletterModule extends AbstractModule
{
protected function configure()
{
$this->bind()->annotatedWith('transport_type')->toInstance('sendmail');
$this->bind('MailerInterface')->to('Mailer');
}
}
Friday, June 7, 13
class NewsletterModule extends AbstractModule
{
protected function configure()
{
$this->bind()->annotatedWith('transport_type')->toInstance('sendmail');
$this->bind('MailerInterface')->to('Mailer');
}
} $di = Injector::create([new NewsletterModule]);
$newsletterManager = $di->getInstance('NewsletterManager');
Friday, June 7, 13
class NewsletterModule extends AbstractModule
{
protected function configure()
{
$this->bind()->annotatedWith('transport_type')->toInstance('sendmail');
$this->bind('MailerInterface')->to('Mailer');
}
} $di = Injector::create([new NewsletterModule]);
$newsletterManager = $di->getInstance('NewsletterManager');
$works = ($newsletterManager->mailer instanceof MailerInterface);
Friday, June 7, 13
Problems?/Gochas
1. Overly abstracted code
2. Easy to go crazy with it
3. Too many factory classes
4. Easy to loose what data is where
5. Container is like super global variable
Friday, June 7, 13
Many other
implementations
Friday, June 7, 13
Aspect Orientated
Programming
Friday, June 7, 13
The Problem
function addPost() {
$log->writeToLog("Entering addPost");
// Business Logic
$log->writeToLog("Leaving addPost");
}
Friday, June 7, 13
The Problem
function addPost() {
$log->writeToLog("Entering addPost");
// Business Logic
$log->writeToLog("Leaving addPost");
}
function addPost() {
$authentication->validateAuthentication($user);
$authorization->validateAccess($user);
// Business Logic
}
Friday, June 7, 13
Core Class Aspect Class
AOP Framework
Proxy Class
Continue Process
Friday, June 7, 13
Lithium Example -Logging in your model
namespace appmodels;
use lithiumutilcollectionFilters;
use lithiumutilLogger;
Filters::apply('appmodelsPost', 'save', function($self, $params, $chain) {
Logger::write('info', $params['data']['title']);
return $chain->next($self, $params, $chain);
});
Friday, June 7, 13
Dispatcher::applyFilter('run', function($self, $params, $chain) {
$key = md5($params['request']->url);
if($cache = Cache::read('default', $key)) {
return $cache;
}
$result = $chain->next($self, $params, $chain);
Cache::write('default', $key, $result, '+1 day');
return $result;
});
Lithium Example -Caching
Friday, June 7, 13
Friday, June 7, 13
Find
Friday, June 7, 13
Cache
Find
Friday, June 7, 13
Log
Cache
Find
Friday, June 7, 13
Log
Cache
Find
Friday, June 7, 13
Log
Cache
Find
Friday, June 7, 13
Log
Cache
Find
Friday, June 7, 13
Ray.AOP
Guice AOP Clone
Friday, June 7, 13
/**
* NotOnWeekends
*
* @Annotation
* @Target("METHOD")
*/
final class NotOnWeekends
{
}
Create Annotation
Create Real Class - Billing service
Friday, June 7, 13
/**
* NotOnWeekends
*
* @Annotation
* @Target("METHOD")
*/
final class NotOnWeekends
{
}
Create Annotation
class RealBillingService
{
/**
* @NotOnWeekends
*/
chargeOrder(PizzaOrder $order, CreditCard $creditCard)
{
Create Real Class - Billing service
Friday, June 7, 13
class WeekendBlocker implements MethodInterceptor
{
public function invoke(MethodInvocation $invocation)
{
$today = getdate();
if ($today['weekday'][0] === 'S') {
throw new RuntimeException(
$invocation->getMethod()->getName() . " not allowed on weekends!"
);
}
return $invocation->proceed();
}
}
Interception Logic
Friday, June 7, 13
$bind = new Bind;
$matcher = new Matcher(new Reader);
$interceptors = [new WeekendBlocker];
$pointcut = new Pointcut(
$matcher->any(),
$matcher->annotatedWith('RayAopSampleAnnotationNotOnWeekends'),
$interceptors
);
$bind->bind('RayAopSampleAnnotationRealBillingService', [$pointcut]);
$billing = new Weaver(new RealBillingService, $bind);
try {
echo $billing->chargeOrder();
} catch (RuntimeException $e) {
echo $e->getMessage() . "n";
exit(1);
}
Binding on Annotation
Friday, June 7, 13
$bind = new Bind;
$bind->bindInterceptors('chargeOrder', [new WeekendBlocker]);
$billingService = new Weaver(new RealBillingService, $bind);
try {
echo $billingService->chargeOrder();
} catch (RuntimeException $e) {
echo $e->getMessage() . "n";
exit(1);
}
Explicit Method Binding
Friday, June 7, 13
Gochas
Friday, June 7, 13
BEAR.Sunday
Friday, June 7, 13

More Related Content

What's hot

ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf Conference
 
PyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for FoursquarePyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for FoursquareMarcel Caraciolo
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScriptMathieu Breton
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkuiKhou Suylong
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experimentwgamboa
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09Bastian Feder
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsIgnacio Martín
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 

What's hot (20)

ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
PyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for FoursquarePyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for Foursquare
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
 
Prototype
PrototypePrototype
Prototype
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the Beast
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Oops in php
Oops in phpOops in php
Oops in php
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experiment
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 

Viewers also liked

Primitive life photos
Primitive life photosPrimitive life photos
Primitive life photoskwiley0019
 
Microsoft word thi bd đh hoa-485
Microsoft word   thi bd đh hoa-485Microsoft word   thi bd đh hoa-485
Microsoft word thi bd đh hoa-485vjt_chjen
 
Cmt 3321 intercom presentation 3 week 14
Cmt 3321 intercom presentation 3 week 14Cmt 3321 intercom presentation 3 week 14
Cmt 3321 intercom presentation 3 week 14amitpac7
 
Hoahoctuoitre1
Hoahoctuoitre1Hoahoctuoitre1
Hoahoctuoitre1vjt_chjen
 
world beneath the waves
world beneath the wavesworld beneath the waves
world beneath the wavestaylorlynn7
 
Howard Guardian
Howard GuardianHoward Guardian
Howard Guardianace19855
 
The molecular times
The molecular timesThe molecular times
The molecular timesjonyfive5
 
Change Management
Change ManagementChange Management
Change Managementprasadumesh
 
2c; photosynthesis
2c; photosynthesis2c; photosynthesis
2c; photosynthesiskwiley0019
 
An amazing man
An amazing manAn amazing man
An amazing manAAR VEE
 
Hello,my nameis.lawlor
Hello,my nameis.lawlorHello,my nameis.lawlor
Hello,my nameis.lawlortnlawlor
 
апкс 2011 04_verilog
апкс 2011 04_verilogапкс 2011 04_verilog
апкс 2011 04_verilogIrina Hahanova
 

Viewers also liked (20)

Primitive life photos
Primitive life photosPrimitive life photos
Primitive life photos
 
Clean out the lungs
Clean out the lungsClean out the lungs
Clean out the lungs
 
Cacsodovoco
CacsodovocoCacsodovoco
Cacsodovoco
 
Microsoft word thi bd đh hoa-485
Microsoft word   thi bd đh hoa-485Microsoft word   thi bd đh hoa-485
Microsoft word thi bd đh hoa-485
 
Soil Management, Site Selection. Soil Fertility
Soil Management, Site Selection. Soil FertilitySoil Management, Site Selection. Soil Fertility
Soil Management, Site Selection. Soil Fertility
 
Cmt 3321 intercom presentation 3 week 14
Cmt 3321 intercom presentation 3 week 14Cmt 3321 intercom presentation 3 week 14
Cmt 3321 intercom presentation 3 week 14
 
Hoahoctuoitre1
Hoahoctuoitre1Hoahoctuoitre1
Hoahoctuoitre1
 
world beneath the waves
world beneath the wavesworld beneath the waves
world beneath the waves
 
Howard Guardian
Howard GuardianHoward Guardian
Howard Guardian
 
The molecular times
The molecular timesThe molecular times
The molecular times
 
Yntercaran
YntercaranYntercaran
Yntercaran
 
Change Management
Change ManagementChange Management
Change Management
 
Samuel slide
Samuel slideSamuel slide
Samuel slide
 
2c; photosynthesis
2c; photosynthesis2c; photosynthesis
2c; photosynthesis
 
2
22
2
 
An amazing man
An amazing manAn amazing man
An amazing man
 
Global classroom project 2012 2013
Global classroom project 2012 2013Global classroom project 2012 2013
Global classroom project 2012 2013
 
Hello,my nameis.lawlor
Hello,my nameis.lawlorHello,my nameis.lawlor
Hello,my nameis.lawlor
 
апкс 2011 04_verilog
апкс 2011 04_verilogапкс 2011 04_verilog
апкс 2011 04_verilog
 
001
001001
001
 

Similar to DI and AOP explained

Magento Attributes - Fresh View
Magento Attributes - Fresh ViewMagento Attributes - Fresh View
Magento Attributes - Fresh ViewAlex Gotgelf
 
Drupal 8 configuration system for coders and site builders - Drupalaton 2013
Drupal 8 configuration system for coders and site builders - Drupalaton 2013Drupal 8 configuration system for coders and site builders - Drupalaton 2013
Drupal 8 configuration system for coders and site builders - Drupalaton 2013swentel
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkJeremy Kendall
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...Oursky
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...Jane Chung
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.jsJay Phelps
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof MenżykPROIDEA
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suckRoss Bruniges
 
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and MobileOpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and MobileDierk König
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magentovarien
 
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagentoImagine
 
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Krzysztof Menżyk
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScriptJohn Hann
 
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...swentel
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AnglePablo Godel
 
Ember and containers
Ember and containersEmber and containers
Ember and containersMatthew Beale
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 

Similar to DI and AOP explained (20)

Magento Attributes - Fresh View
Magento Attributes - Fresh ViewMagento Attributes - Fresh View
Magento Attributes - Fresh View
 
Drupal 8 configuration system for coders and site builders - Drupalaton 2013
Drupal 8 configuration system for coders and site builders - Drupalaton 2013Drupal 8 configuration system for coders and site builders - Drupalaton 2013
Drupal 8 configuration system for coders and site builders - Drupalaton 2013
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.js
 
Be pragmatic, be SOLID
Be pragmatic, be SOLIDBe pragmatic, be SOLID
Be pragmatic, be SOLID
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and MobileOpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
 
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
 
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScript
 
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New Angle
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 

More from Richard McIntyre

More from Richard McIntyre (9)

Why Message Driven?
Why Message Driven?Why Message Driven?
Why Message Driven?
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Spout
SpoutSpout
Spout
 
Spout
SpoutSpout
Spout
 
Semantic BDD with ShouldIT?
Semantic BDD with ShouldIT?Semantic BDD with ShouldIT?
Semantic BDD with ShouldIT?
 
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.SundaySpout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Using Backbone with CakePHP
Using Backbone with CakePHPUsing Backbone with CakePHP
Using Backbone with CakePHP
 
Future of PHP
Future of PHPFuture of PHP
Future of PHP
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

DI and AOP explained

  • 1. What is this DI and AOP stuff anyway... Friday, June 7, 13
  • 2. About Me Currently BBC Sport (Freelancer) Lived in Japan for 15 years - love sushi Love frameworks - not just PHP ones Involved in Lithium and BEAR.Sunday projects Richard McIntyre - @mackstar Friday, June 7, 13
  • 4. Most Basic Example - Problem class Mailer { private $transport; public function __construct() { $this->transport = 'sendmail'; } // ... } Friday, June 7, 13
  • 6. Easily becomes an inheritance mess Sport_Lib_Builder_GenericStatsAbstract Sport_Lib_Builder_GenericStats_Cricket_Table Sport_Lib_Builder_GenericStats_Cricket_NarrowTable Sport_Lib_Builder_GenericStats_CricketAbstract Sport_Lib_API_GenericStats_Cricket Sport_Lib_API_GenericStatsAbstract Sport_Lib_Service_SportsData_Cricket Sport_Lib_Service_SportsData Sport_Lib_ServiceAbstract Friday, June 7, 13
  • 7. DI for a 5 year old When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired. What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat. Friday, June 7, 13
  • 8. Something like this... Application needs Foo, which needs Bar, which needs Bim, so: Application creates Bim Application creates Bar and gives it Bim Application creates Foo and gives it Bar Application calls Foo Foo calls Bar Bar does something Friday, June 7, 13
  • 9. The Service Container Dependency Injection Round 1 Friday, June 7, 13
  • 10. class Mailer { private $transport; public function __construct($transport) { $this->transport = $transport; } // ... } Symfony2 Example Friday, June 7, 13
  • 11. class Mailer { private $transport; public function __construct($transport) { $this->transport = $transport; } // ... } use SymfonyComponentDependencyInjectionContainerBuilder; $container = new ContainerBuilder(); $container->register('mailer', 'Mailer'); Symfony2 Example Friday, June 7, 13
  • 12. class Mailer { private $transport; public function __construct($transport) { $this->transport = $transport; } // ... } use SymfonyComponentDependencyInjectionContainerBuilder; $container = new ContainerBuilder(); $container->register('mailer', 'Mailer'); use SymfonyComponentDependencyInjectionContainerBuilder; $container = new ContainerBuilder(); $container ->register('mailer', 'Mailer') ->addArgument('sendmail'); Symfony2 Example Friday, June 7, 13
  • 13. class NewsletterManager { private $mailer; public function __construct(Mailer $mailer) { $this->mailer = $mailer; } // ... } Friday, June 7, 13
  • 14. class NewsletterManager { private $mailer; public function __construct(Mailer $mailer) { $this->mailer = $mailer; } // ... } use SymfonyComponentDependencyInjectionContainerBuilder; use SymfonyComponentDependencyInjectionReference; $container = new ContainerBuilder(); $container->setParameter('mailer.transport', 'sendmail'); $container ->register('mailer', 'Mailer') ->addArgument('%mailer.transport%'); $container ->register('newsletter_manager', 'NewsletterManager') ->addArgument(new Reference('mailer')); Friday, June 7, 13
  • 15. use SymfonyComponentDependencyInjectionContainerBuilder; $container = new ContainerBuilder(); $newsletterManager = $container->get('newsletter_manager'); Friday, June 7, 13
  • 16. Inversion Of Control Pattern The control of the dependencies is inversed from one being called to the one calling. Friday, June 7, 13
  • 17. Container Newsletter Manager Mailer transport = sendmail Friday, June 7, 13
  • 18. Container Newsletter Manager Mailer # src/Acme/HelloBundle/Resources/config/ services.yml parameters: # ... mailer.transport: sendmail services: mailer: class: Mailer arguments: [%mailer.transport%] newsletter_manager: class: NewsletterManager calls: - [ setMailer, [ @mailer ] ] transport = sendmail Friday, June 7, 13
  • 20. Tips Test first in isolation Don’t need to wire together to test (Eg Environment etc) integration tests are expensive. When you do wire together with test/mock classes as needed Duck Type your code / Use interfaces Friday, June 7, 13
  • 22. $container = new Pimple(); // define some parameters $container['cookie_name'] = 'SESSION_ID'; $container['session_storage_class'] = 'SessionStorage'; Friday, June 7, 13
  • 23. $container = new Pimple(); // define some parameters $container['cookie_name'] = 'SESSION_ID'; $container['session_storage_class'] = 'SessionStorage'; // define some objects $container['session_storage'] = function ($c) { return new $c['session_storage_class']($c['cookie_name']); }; $container['session'] = function ($c) { return new Session($c['session_storage']); }; Friday, June 7, 13
  • 24. Clever DI with Bindings Friday, June 7, 13
  • 25. Laravel 4 example class MyConcreteClass implements MyInterface { Friday, June 7, 13
  • 26. Laravel 4 example class MyConcreteClass implements MyInterface { class MyClass { public function __construct(MyInterface $my_injection) { $this->my_injection = $my_injection; } } App::bind('MyInterface', 'MyConcreteClass'); Friday, June 7, 13
  • 27. Cleverer DI with Injection Points & Bindings Friday, June 7, 13
  • 28. Google Guice Guice alleviates the need for factories and the use of ‘new’ in your ‘Java’a code Think of Guice's @Inject as the new new. You will still need to write factories in some cases, but your code will not depend directly on them. Your code will be easier to change, unit test and reuse in other contexts. Ray.DI Friday, June 7, 13
  • 29. interface MailerInterface {} PHP Google Guice Clone Ray.DI Friday, June 7, 13
  • 30. class Mailer implements MailerInterface { private $transport; /** * @Inject * @Named("transport_type") */ public function __construct($transport) { $this->transport = $transport; } } interface MailerInterface {} PHP Google Guice Clone Ray.DI Friday, June 7, 13
  • 31. class Mailer implements MailerInterface { private $transport; /** * @Inject * @Named("transport_type") */ public function __construct($transport) { $this->transport = $transport; } } interface MailerInterface {} class NewsletterManager { public $mailer; /** * @Inject */ public function __construct(MailerInterface $mailer) { $this->mailer = $mailer; } } PHP Google Guice Clone Ray.DI Friday, June 7, 13
  • 32. class NewsletterModule extends AbstractModule { protected function configure() { $this->bind()->annotatedWith('transport_type')->toInstance('sendmail'); $this->bind('MailerInterface')->to('Mailer'); } } Friday, June 7, 13
  • 33. class NewsletterModule extends AbstractModule { protected function configure() { $this->bind()->annotatedWith('transport_type')->toInstance('sendmail'); $this->bind('MailerInterface')->to('Mailer'); } } $di = Injector::create([new NewsletterModule]); $newsletterManager = $di->getInstance('NewsletterManager'); Friday, June 7, 13
  • 34. class NewsletterModule extends AbstractModule { protected function configure() { $this->bind()->annotatedWith('transport_type')->toInstance('sendmail'); $this->bind('MailerInterface')->to('Mailer'); } } $di = Injector::create([new NewsletterModule]); $newsletterManager = $di->getInstance('NewsletterManager'); $works = ($newsletterManager->mailer instanceof MailerInterface); Friday, June 7, 13
  • 35. Problems?/Gochas 1. Overly abstracted code 2. Easy to go crazy with it 3. Too many factory classes 4. Easy to loose what data is where 5. Container is like super global variable Friday, June 7, 13
  • 38. The Problem function addPost() { $log->writeToLog("Entering addPost"); // Business Logic $log->writeToLog("Leaving addPost"); } Friday, June 7, 13
  • 39. The Problem function addPost() { $log->writeToLog("Entering addPost"); // Business Logic $log->writeToLog("Leaving addPost"); } function addPost() { $authentication->validateAuthentication($user); $authorization->validateAccess($user); // Business Logic } Friday, June 7, 13
  • 40. Core Class Aspect Class AOP Framework Proxy Class Continue Process Friday, June 7, 13
  • 41. Lithium Example -Logging in your model namespace appmodels; use lithiumutilcollectionFilters; use lithiumutilLogger; Filters::apply('appmodelsPost', 'save', function($self, $params, $chain) { Logger::write('info', $params['data']['title']); return $chain->next($self, $params, $chain); }); Friday, June 7, 13
  • 42. Dispatcher::applyFilter('run', function($self, $params, $chain) { $key = md5($params['request']->url); if($cache = Cache::read('default', $key)) { return $cache; } $result = $chain->next($self, $params, $chain); Cache::write('default', $key, $result, '+1 day'); return $result; }); Lithium Example -Caching Friday, June 7, 13
  • 51. /** * NotOnWeekends * * @Annotation * @Target("METHOD") */ final class NotOnWeekends { } Create Annotation Create Real Class - Billing service Friday, June 7, 13
  • 52. /** * NotOnWeekends * * @Annotation * @Target("METHOD") */ final class NotOnWeekends { } Create Annotation class RealBillingService { /** * @NotOnWeekends */ chargeOrder(PizzaOrder $order, CreditCard $creditCard) { Create Real Class - Billing service Friday, June 7, 13
  • 53. class WeekendBlocker implements MethodInterceptor { public function invoke(MethodInvocation $invocation) { $today = getdate(); if ($today['weekday'][0] === 'S') { throw new RuntimeException( $invocation->getMethod()->getName() . " not allowed on weekends!" ); } return $invocation->proceed(); } } Interception Logic Friday, June 7, 13
  • 54. $bind = new Bind; $matcher = new Matcher(new Reader); $interceptors = [new WeekendBlocker]; $pointcut = new Pointcut( $matcher->any(), $matcher->annotatedWith('RayAopSampleAnnotationNotOnWeekends'), $interceptors ); $bind->bind('RayAopSampleAnnotationRealBillingService', [$pointcut]); $billing = new Weaver(new RealBillingService, $bind); try { echo $billing->chargeOrder(); } catch (RuntimeException $e) { echo $e->getMessage() . "n"; exit(1); } Binding on Annotation Friday, June 7, 13
  • 55. $bind = new Bind; $bind->bindInterceptors('chargeOrder', [new WeekendBlocker]); $billingService = new Weaver(new RealBillingService, $bind); try { echo $billingService->chargeOrder(); } catch (RuntimeException $e) { echo $e->getMessage() . "n"; exit(1); } Explicit Method Binding Friday, June 7, 13