dependency injection in php

53
Dependency Injection in PHP PHPCon Poland Szczyrk 25/10/13 by @cakper flickr.com/limowreck666/223731385/

Upload: kacper-gunia

Post on 08-Sep-2014

31 views

Category:

Technology


5 download

DESCRIPTION

Slides from my talk during PHPCon Poland. Szczyrk 25/10/2013

TRANSCRIPT

Page 1: Dependency Injection in PHP

Dependency Injection in PHP

PHPCon Poland Szczyrk 25/10/13

!by @cakper

flickr.com/limowreck666/223731385/

Page 2: Dependency Injection in PHP

Kacper Gunia // @cakper

Software Engineer @SensioLabsUK

Symfony Certified Developer

#Symfony-PL // SymfonyLab.pl

Silesian PHP User Group // SPUG.pl

Page 3: Dependency Injection in PHP

Inversion of Control

Dependency Injection

Events

Aspect Oriented Programming

flickr.com/goetter/4559773791/

Page 4: Dependency Injection in PHP

Diving into Dependency Injection

flickr.com/haniamir/651043585/

Page 5: Dependency Injection in PHP

Dependency Injection!!class  DvdPlayer  {          public  function  playDisc(Disc  $disc)          {                  echo  'Now  playing:  '.$disc-­‐>getMovieTitle();  !                $tv  =  new  Tv('Samsung  40"');                  $tv-­‐>sendToOutput($disc-­‐>getResource());          }  }

Page 6: Dependency Injection in PHP

Dependency Injectionclass  DvdPlayer  {          private  $tv;  !        public  function  __construct()          {                  $this-­‐>tv  =  new  Tv('Samsung  40"');;          }  !        public  function  playDisc(Disc  $disc)          {                  echo  'Now  playing:  '  .  $disc-­‐>getMovieTitle();                  $this-­‐>tv-­‐>sendToOutput($disc-­‐>getResource());          }  }

Page 7: Dependency Injection in PHP

Dependency Injectionclass  DvdPlayer  {          private  $tv;  !        public  function  __construct(Tv  $tv)          {                  $this-­‐>tv  =  $tv;          }  //  (...)  }  !$tv  =  new  Tv('Samsung  40"');  $dvdPlayer  =  new  DvdPlayer($tv);

Page 8: Dependency Injection in PHP

Dependency Injectionclass  DvdPlayer  {          private  $device;  !        public  function  __construct(HdmiDevice  $device)          {                  $this-­‐>device  =  $device;          }  //  (...)  }  !$projector  =  new  Projector('Epson  EB');  $dvdPlayer  =  new  DvdPlayer($tv);

Page 9: Dependency Injection in PHP

Nailed it!

Page 10: Dependency Injection in PHP

“Dependency Injection is where components are given

their dependencies through their constructors, methods, or

directly into fields.”

!

“(...) it is a 25-dollar term for a 5-cent concept”

source: picocontainer.codehaus.org jamesshore.com

Page 11: Dependency Injection in PHP

Types of Injection

Constructor

Setter

Property

Reflection

flickr.com/jensfinke/4417602702/

Page 12: Dependency Injection in PHP

Constructor Injection

class  Tv  implements  HdmiDevice{}  class  DvdPlayer  {          private  $device;  !        public  function  __construct(HdmiDevice  $device)          {                  $this-­‐>device  =  $device;          }  }  !$tv  =  new  Tv('Samsung  40"');  $dvdPlayer  =  new  DvdPlayer($tv);

Page 13: Dependency Injection in PHP

Setter Injection

class  BlurayDisc  implements  Disc{}  class  DvdPlayer  {          private  $disc;  !        public  function  setDisc(Disc  $disc)          {                  $this-­‐>disc  =  $disc;          }  }  !$disc  =  new  BlurayDisc('Pulp  Fiction');  $dvdPlayer  =  new  DvdPlayer();  $dvdPlayer-­‐>setDisc($disc);

Page 14: Dependency Injection in PHP

Property Injection

class  DvdPlayer  {          public  $remote;  }  !$dvdPlayer  =  new  DvdPlayer();  $dvdPlayer-­‐>remote  =  new  Remote();

Page 15: Dependency Injection in PHP

Reflection Injection

class  DvdPlayer  {          private  $powerSupply;  }  !$dvdPlayer  =  new  DvdPlayer();  $reflector  =  new  ReflectionClass($dvdPlayer);  $powerSupply  =  $reflector-­‐>getProperty('powerSupply');  $powerSupply-­‐>setAccessible(true);  !$powerSupply-­‐>setValue($dvdPlayer,  new  PowerSupply());

Page 16: Dependency Injection in PHP

Pros & Cons

flickr.com/paperpariah/3589690234/

Page 17: Dependency Injection in PHP

Decoupling

Advantage #1

flickr.com/roonster/3387705446/

Page 18: Dependency Injection in PHP

Dependency Inversion Principle

Advantage #2

flickr.com/antonsiniorg/1876733029/

Page 19: Dependency Injection in PHP

Reusability

Advantage #3

flickr.com/ejpphoto/2314610838/

Page 20: Dependency Injection in PHP

Clean code

Advantage #4

flickr.com/38659937@N06/4020413080/

Page 21: Dependency Injection in PHP

Easier testing

Advantage #5

flickr.com/nattu/895220635/

Page 22: Dependency Injection in PHP

Instance management

Advantage #6

flickr.com/34094515@N00/3817086937/

Page 23: Dependency Injection in PHP

IDE support

Advantage #7

flickr.com/gavin_fordham/9407339641/

Page 24: Dependency Injection in PHP

Complex initialisation

Disadvantage

flickr.com/toniblay/52445415/

Page 25: Dependency Injection in PHP

Factory

Simple Solution

flickr.com/lenscrack/5577431429/

Page 26: Dependency Injection in PHP

Dependency Injection Container

Proper Solution

flickr.com/thomashawk/24089964/

Page 27: Dependency Injection in PHP

“Dependency Injection Container is simply a PHP

object that manages the instantiation of other objects”

!

We call them “Services”

source: symfony.com

Page 28: Dependency Injection in PHP

Our DvdPlayer

!!$tv  =  new  Tv('Samsung  40"');  $dvdPlayer  =  new  DvdPlayer($tv);  !$disc  =  new  Disc('Pulp  Fiction');  $dvdPlayer-­‐>playDisc($disc);

Page 29: Dependency Injection in PHP

Simple Container class

class  Container  {          public  function  getTv()          {                  return  new  Tv('Samsung  40"');          }  !        public  function  getDvdPlayer()          {                  return  new  DvdPlayer($this-­‐>getTv());          }  }

Page 30: Dependency Injection in PHP

Container use

!!$container  =  new  Container();  !$dvdPlayer  =  $container-­‐>getDvdPlayer();  !$disc  =  new  Disc('Pulp  Fiction');  $dvdPlayer-­‐>playDisc($disc);

Page 31: Dependency Injection in PHP

DIC ImplementationsTwitteePimplePHP-DI Zend\DiIlluminate\ContainerOrno\DiLeague\DiSymfony\DependencyInjection 

flickr.com/smb_flickr/313116995/

Page 32: Dependency Injection in PHP

DI & DIC Patterns

flickr.com/thelearningcurvedotca/8645721482/

Page 33: Dependency Injection in PHP

Expect Interfaces, not Implementations

Pattern #1

flickr.com/deapeajay/2969264395/

Page 34: Dependency Injection in PHP

Don’t check null values

Pattern #2

flickr.com/g-ratphotos/3328593629/

Page 35: Dependency Injection in PHP

class  DvdPlayer  {          public  $disc;  !        public  function  play()          {                  if  (!is_null($this-­‐>disc))  {                          $this-­‐>sendToOutput($this-­‐>disc-­‐>getResource());                  }          }  !        public  function  play()          {                  if  ($this-­‐>disc  instanceof  Disc)  {                          $this-­‐>sendToOutput($this-­‐>disc-­‐>getResource());                  }          }  }

Page 36: Dependency Injection in PHP

Avoid ‘Service Locator’

Pattern #3

flickr.com/mateus27_24-25/2224073271/

Page 37: Dependency Injection in PHP

class  DvdPlayer  {          private  $locator;  !        public  function  __construct()          {                  $this-­‐>locator  =  ServiceLocator::getInstance();          }  !!        public  function  playDisc(Disc  $disc)          {                  $this-­‐>locator                            -­‐>getTv()                            -­‐>sendToOutput($disc-­‐>getResource());          }  }

Page 38: Dependency Injection in PHP

Don’t inject whole container

Pattern #4

flickr.com/ucumari/580865728/

Page 39: Dependency Injection in PHP

In DIC store Services and Properties,

but not Entities

Pattern #5

flickr.com/madlyinlovewithlife/8674850717/

Page 40: Dependency Injection in PHP

Don’t be afraid to create plenty of small Classes

Pattern #6

flickr.com/geoki/2691420977/

Page 41: Dependency Injection in PHP

Symfony DIC in action

Page 42: Dependency Injection in PHP

Services

new  Tv('Samsung  40”’)  !services:      tv:          class:            Tv          arguments:    [“Samsung  40"”]  

Page 43: Dependency Injection in PHP

Parameters

new  Tv('Samsung  40”’)  !parameters:      tv_name:    Samsung  40"  

Page 44: Dependency Injection in PHP

Parameters & Services

new  Tv('Samsung  40”’)  !parameters:      tv_name:    Samsung  40"  !services:      tv:          class:            Tv          arguments:    [“%tv_name%”]  !$container-­‐>get('tv');

Page 45: Dependency Injection in PHP

Compiled Container

!!!!protected  function  getTvService()  {          return  $this-­‐>services['tv']  =  new  \Tv('Samsung');  }  

Page 46: Dependency Injection in PHP

Static Factory

services:          tv                  class:                    Tv                    factory_class:    TvFactory                  factory_method:  get

Page 47: Dependency Injection in PHP

Factory

services:          tv_factory:                  class:                      TvFactory          tv                  class:                      Tv                    factory_service:  tv_factory                  factory_method:    get

Page 48: Dependency Injection in PHP

Optional Dependencies

class  DvdPlayer  {      function  __construct(HdmiDevice  $device  =  null){}  }  !services:      tv:          class:            Tv          arguments:    [%tv_name%]      dvd_player:              class:        DvdPlayer              arguments  ["@?tv"]  

Page 49: Dependency Injection in PHP

Lazy-loaded Services

services:      tv:          class:            Tv          arguments:    [“%tv_name%”]       lazy:         true

Page 50: Dependency Injection in PHP

Private Services

services:      drm_decryptor:          class:            DrmDecryptor       public:       false      dvd_player:              class:        DvdPlayer              arguments  [“@drm_decryptor”]

Page 51: Dependency Injection in PHP

Scopes

services:      tv:          class:            Tv          arguments:    [“%tv_name%”]       scope:       prototype

Page 52: Dependency Injection in PHP

PHPStorm support

sxc.hu/photo/228094/

Adrien Brault

Page 53: Dependency Injection in PHP

Questions? !

Thank you! :) !

joind.in/9760

flickr.com/eole/3809742516/