SlideShare a Scribd company logo
Real World Dependency Injection
          Stephan Hochdörfer, bitExpert AG




"Dependency Injection is a key element of agile architecture"
                     Ward Cunningham
Agenda
1.   About me

2.   What is Dependency Injection?

3.   Real World examples

4.   Pros & Cons

5.   Questions
About me
 Stephan Hochdörfer, bitExpert AG

 Department Manager Research Labs

 enjoying PHP since 1999

 S.Hochdoerfer@bitExpert.de

 @shochdoerfer
What is Dependency Injection?



What is Dependency?
What is Dependency Injection?



What is Dependency?

 Application Layer
        
           Data Access layer
        
           Business logic layer
        
           ...

 External components
        
          Framework classes
        
          Webservices
        
          ...
What is Dependency Injection?



Why are Dependencies bad?
What is Dependency Injection?



Why are Dependencies bad?




                            „new“ is evil!
What is Dependency Injection?



Why are Dependencies bad?

 Tightly coupled code

 Hard to re-use components

 Hard to test components, no isolation
What is Dependency Injection?



Simple Dependency



                                Main    Required
                                class    class
What is Dependency Injection?



Complex Dependency


                                           Required
                                            class
                     Main       Required
                     class       class
                                           Required
                                            class
What is Dependency Injection?



Very complex Dependency
                                           Database

                                Required
                                 class
                                            External
  Main             Required
                                            resource
  class             class
                                Required
                                 class




                   Required     Required
                                            Webservice
                    class        class
What is Dependency Injection?



Very complex Dependency
                                           Database

                                Required
                                 class
                                            External
  Main             Required
                                            resource
  class             class
                                Required
                                 class




                   Required     Required
                                            Webservice
                    class        class
What is Dependency Injection?



Very complex Dependency
                                           Database

                                Required
                                 class
                                            External
  Main             Required
                                            resource
  class             class
                                Required
                                 class




                   Required     Required
                                            Webservice
                    class        class
What is Dependency Injection?



How to Manage Dependencies?
What is Dependency Injection?



How to Manage Dependencies?




               You don`t need to. The Framework does it all!
What is Dependency Injection?



How to Manage Dependencies?




          Simple Container      vs.   Full stacked Framework
What is Dependency Injection?



What is Dependency Injection?
What is Dependency Injection?



What is Dependency Injection?




      Consumer
What is Dependency Injection?



What is Dependency Injection?




      Consumer                  Dependencies
What is Dependency Injection?



What is Dependency Injection?




      Consumer                  Dependencies   Container
What is Dependency Injection?



What is Dependency Injection?




      Consumer                  Dependencies   Container
What is Dependency Injection?



Types of Dependency Injection

Type 1: Constructor injection

 <?php

 class MySampleService implements IMySampleService {
   /**
    * @var ISampleDao
    */
   private $oSampleDao;

   public function __construct(ISampleDao $poSampleDao) {
     $this->oSampleDao = $poSamleDao;
   }
 }
 ?>
What is Dependency Injection?



Types of Dependency Injection

Type 2: Setter injection

 <?php

 class MySampleService implements IMySampleService {
   /**
    * @var ISampleDao
    */
   private $oSampleDao;

   public function setSampleDao(ISampleDao $poSampleDao) {
     $this->oSampleDao = $poSamleDao;
   }
 }
 ?>
What is Dependency Injection?



Types of Dependency Injection

Type 3: Interface injection

 <?php

 class MySampleService implements IMySampleService, IApplicationContextAware
 {
   /**
    * @var IApplicationContext
    */
   private $oCtx;

      public function setApplicationContext(IApplicationContext $poCtx) {
        $this->oCtx = $poCtx;
      }
 }
 ?>
What is Dependency Injection?



 Configuration Types

  Type 1: Annotations

  <?php

  class MySampleService implements IMySampleService {
    /**
     * @var ISampleDao
     */
    private $oSampleDao;

       /**
         * @Inject
         */
       public function __construct(ISampleDao $poSampleDao) {
          $this->oSampleDao = $poSamleDao;
       }
  }
  ?>
What is Dependency Injection?



 Configuration Types

  Type 1: Annotations
  <?php

  class MySampleService implements IMySampleService {
    /**
     * @var ISampleDao
     */
    private $oSampleDao;

       /**
         * @Inject
         * @Named('TheSampleDao')
         */
       public function __construct(ISampleDao $poSampleDao) {
          $this->oSampleDao = $poSamleDao;
       }
  }
  ?>
What is Dependency Injection?



Configuration Types

Type 2: External configuration via XML

 <?xml version="1.0" encoding="UTF-8" ?>
 <beans xmlns="http://www.bitexpert.de/schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.bitexpert.de/schema/
 http://www.bitexpert.de/schema/bitFramework-beans.xsd">

     <bean id="SampleDao"       class="SampleDao">
         <constructor-arg       value="app_sample" />
         <constructor-arg       value="iSampleId" />
         <constructor-arg       value="BoSample" />
     </bean>

     <bean id="SampleService" class="MySampleService">
          <constructor-arg ref="SampleDao" />
     </bean>
 </beans>
What is Dependency Injection?



Configuration Types

Type 2: External configuration via YAML

 services:
   SampleDao:
     class: SampleDao
     arguments: ['app_sample', 'iSampleId', 'BoSample']
   SampleService:
     class: SampleService
     arguments: [@SampleDao]
What is Dependency Injection?



Configuration Types

 Type 3: PHP Configuration

 <?php
 class BeanCache extends bF_Beanfactory_Container_PHP_ACache {
     protected function createSampleDao() {
          $oBean = new SampleDao('app_sample', 'iSampleId', 'BoSample');
          return array("oBean" => $oBean, "bSingleton" => "1");
     }

      protected function createMySampleService() {
          $oBean = new MySampleService($this->getBean('SampleDao'));
          return array("oBean" => $oBean, "bSingleton" => "1");
      }
 ?>
What is Dependency Injection?



Cache, Cache, Cache!
 180



 160



 140



 120



 100



  80



  60



  40



  20



  0
           XML no Caching   XML with Caching     PHP            PHP compiled

       Requests per Second meassured via Apache HTTP server benchmarking tool
Real world examples




      "High-level modules should not depend on low-level modules.
                   Both should depend on abstractions."
                             Robert C. Martin
Real World examples



Unittesting made easy

 <?php
 require_once 'PHPUnit/Framework.php';

 class ServiceTest extends PHPUnit_Framework_TestCase {
     public function testSampleService() {
         $oSampleDao = $this->getMock('ISampleDao');

          // run test case
          $oService = new MySampleService($oSampleDao);
          $bReturn = $oService->doWork();

          // check assertions
          $this->assertTrue($bReturn);
      }
 }
 ?>
Real World examples



One class, multiple configurations

                                            Implementation

                         Live                                        Working




<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.bitexpert.de/schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.bitexpert.de/schema/
http://www.bitexpert.de/schema/bitFramework-beans.xsd">

     <bean id="ExportLive" class="MyApp_Service_ExportManager">
          <constructor-arg ref="DAOPageLive" />
     </bean>

     <bean id="ExportWorking" class="MyApp_Service_ExportManager">
          <constructor-arg ref="DAOPageWorking" />
     </bean>

</beans>
Real World examples



One class, multiple configurations II
<?php
class Promio_Action_Account_Auth extends bF_Mvc_Action_AFormAction {
     private $oAccountManager;
     private $iType;

     public function __construct(Promio_Service_IAccountManager $poAccountManager) {
          $this->oAccountManager = $poAccountManager;
     }

     public function setType($piType) {
          $this->iType = (int) $piType;
     }

     protected function processFormSubmission(bF_Bo_ABo $poBOFormBackingObject) {
          $oMaV = new bF_Mvc_ModelAndView($this->getSuccessView(), true);
          try {
                $poBOFormBackingObject->setType($this->iType);
                $this->oAccountManager->save($poBOFormBackingObject);
          }
          catch(bF_Service_ServiceException $oException) {
                $oMaV = new bF_Mvc_ModelAndView($this->getFailureView(), true);
          }
          return $oMaV;
     }
}
?>
Real World examples



Mocking external services


       Consumer                   Connector                  Webservice


                IConnector interface


<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.bitexpert.de/schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.bitexpert.de/schema/
http://www.bitexpert.de/schema/bitFramework-beans.xsd">

    <bean id="Consumer" class="MyApp_Service_Consumer">
         <constructor-arg ref="Connector" />
    </bean>

</beans>
Real World examples



Mocking external services

                                  alternative                    Local
       Consumer
                                  Connector                  filesystem


                IConnector interface


<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.bitexpert.de/schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.bitexpert.de/schema/
http://www.bitexpert.de/schema/bitFramework-beans.xsd">

     <bean id="Consumer" class="MyApp_Service_Consumer">
          <constructor-arg ref="AltConnector" />
     </bean>

</beans>
Real World examples



Clean, readable code
<?php

class Promio_Action_News_Delete extends bF_Mvc_Action_AAction {
     /**
      * @var Promio_Service_INewsManager
      */
     private $oNewsManager;

     public function __construct(Promio_Service_INewsManager $poNewsManager) {
          $this->oNewsManager = $poNewsManager;
     }

     protected function execute(bF_Mvc_Request $poRequest) {
          try {
               $this->oNewsManager->delete((int) $poRequest->getVar('iNewsId'));
          }
          catch(bF_Service_ServiceException $oException) {
          }

         $oMaV = new bF_Mvc_ModelAndView($this->getSuccessView(), true);
         return $oMaV;
     }
}
?>
Real World examples



No framework dependency
<?php

class MySampleService implements IMySampleService {
  /**
   * @var ISampleDao
   */
  private $oSampleDao;

  public function __construct(ISampleDao $poSampleDao) {
     $this->oSampleDao = $poSamleDao;
  }

  public function getSample($piSampleId) {
     try {
       return $this->oSampleDao->readByPrimaryKey((int) $piSampleId);
     }
     catch(DaoException $oException) {
     }
  }
}
?>
Pros & Cons



Benefits

 Good for agile development
        
          Reducing amount of code
        
          Helpful for Unit testing

 Loose coupling
        
          Least intrusive mechanism
        
          Switching implementations by changing configuration
        
          Separation of glue code from business logic

 Clean view on the code
        
          Separate configuration from code
        
          Getting rid of boilerpate configuration code
Pros & Cons



Cons

 To many different implementations, no standard today!
       
         Bucket, Crafty, FLOW3, Imind_Context, PicoContainer,
         Pimple, Phemto, Stubbles, Symfony 2.0, Sphicy, Solar,
         Substrate, XJConf, Yadif, Zend_Di (Proposal), Lion
         Framework, Spiral Framework, Xyster Framework, …
       
         No JSR 330 for PHP

 Simple Containers vs. fully-stacked Framework
        
          No dependency from application to Container!

 Developers need to be aware of configuration ↔ runtime
http://joind.in/1553

More Related Content

PDF
Testing untestable code - DPC10
PDF
Testing untestable code - PHPBNL11
PDF
Testing untestable Code - PFCongres 2010
PDF
Testing untestable code - phpconpl11
PDF
Testing untestable code - oscon 2012
PDF
Real World Dependency Injection - PFCongres 2010
PDF
Real World Dependency Injection - phpday
PDF
Testing untestable code - phpday
Testing untestable code - DPC10
Testing untestable code - PHPBNL11
Testing untestable Code - PFCongres 2010
Testing untestable code - phpconpl11
Testing untestable code - oscon 2012
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - phpday
Testing untestable code - phpday

What's hot (19)

PDF
Real World Dependency Injection SE - phpugrhh
PDF
Testing untestable code - STPCon11
PDF
Real World Dependency Injection - oscon13
PDF
Spring Certification Questions
KEY
IoC with PHP
PDF
Create Your Own Framework by Fabien Potencier
PPT
Contexts and Dependency Injection for the JavaEE platform
ODP
Dependency Injection, Zend Framework and Symfony Container
PDF
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
PDF
Seven Versions of One Web Application
PPT
比XML更好用的Java Annotation
PPT
Spring talk111204
PDF
slingmodels
KEY
Working Effectively With Legacy Code
PDF
Java EE 與 雲端運算的展望
PDF
Certified Core Java Developer
PPTX
Zend Studio Tips and Tricks
PDF
Testing Legacy Rails Apps
PDF
Integration Testing With ScalaTest and MongoDB
Real World Dependency Injection SE - phpugrhh
Testing untestable code - STPCon11
Real World Dependency Injection - oscon13
Spring Certification Questions
IoC with PHP
Create Your Own Framework by Fabien Potencier
Contexts and Dependency Injection for the JavaEE platform
Dependency Injection, Zend Framework and Symfony Container
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Seven Versions of One Web Application
比XML更好用的Java Annotation
Spring talk111204
slingmodels
Working Effectively With Legacy Code
Java EE 與 雲端運算的展望
Certified Core Java Developer
Zend Studio Tips and Tricks
Testing Legacy Rails Apps
Integration Testing With ScalaTest and MongoDB
Ad

Viewers also liked (20)

KEY
Sophisticated JPA with Spring & Hades
PDF
Spring Data and MongoDB
PDF
Coding & Music Passion And Profession
PDF
Whoops! where did my architecture go?
PDF
Spring Data and MongoDB
PDF
Whoops! Where did my architecture go?
PDF
Generic DAOs With Hades
PDF
Mylyn - Increasing developer productivity
PDF
Increasing developer procutivity with Mylyn (Devoxx 2010)
PDF
Spring Roo 1.0.0 Technical Deep Dive
PDF
REST based web applications with Spring 3
PDF
PDF
Spring in action - Hades & Spring Roo
PDF
Data Access 2.0? Please welcome, Spring Data!
PDF
An introduction into Spring Data
PDF
Spring integration
PDF
Spring Data JPA - Repositories done right
PDF
Data access 2.0? Please welcome: Spring Data!
PDF
Whoops! Where did my architecture go?
PPTX
IoC and Mapper in C#
Sophisticated JPA with Spring & Hades
Spring Data and MongoDB
Coding & Music Passion And Profession
Whoops! where did my architecture go?
Spring Data and MongoDB
Whoops! Where did my architecture go?
Generic DAOs With Hades
Mylyn - Increasing developer productivity
Increasing developer procutivity with Mylyn (Devoxx 2010)
Spring Roo 1.0.0 Technical Deep Dive
REST based web applications with Spring 3
Spring in action - Hades & Spring Roo
Data Access 2.0? Please welcome, Spring Data!
An introduction into Spring Data
Spring integration
Spring Data JPA - Repositories done right
Data access 2.0? Please welcome: Spring Data!
Whoops! Where did my architecture go?
IoC and Mapper in C#
Ad

Similar to Real world dependency injection - DPC10 (20)

PDF
Real World Dependency Injection - IPC11 Spring Edition
PDF
What is Dependency Injection
PDF
Dependency Injection
PPT
Dependency injection with PHP
PDF
DIC To The Limit – deSymfonyDay, Barcelona 2014
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
PDF
Introduction to DI(C)
PDF
Dependency injection Drupal Camp Wrocław 2014
PDF
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
PDF
CDI and Weld
KEY
Zend Di in ZF 2.0
PDF
Dependency Injection in Drupal 8
PPTX
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
PDF
Dependency Inversion and Dependency Injection in PHP
PDF
Real World Dependency Injection - phpugffm13
PDF
CDI and Weld
PPTX
Dependency injection with Symfony 2
PDF
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
PDF
Zend Framework 2 quick start
PDF
The Basic Concept Of IOC
Real World Dependency Injection - IPC11 Spring Edition
What is Dependency Injection
Dependency Injection
Dependency injection with PHP
DIC To The Limit – deSymfonyDay, Barcelona 2014
Clean Code Part II - Dependency Injection at SoCal Code Camp
Introduction to DI(C)
Dependency injection Drupal Camp Wrocław 2014
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
CDI and Weld
Zend Di in ZF 2.0
Dependency Injection in Drupal 8
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Dependency Inversion and Dependency Injection in PHP
Real World Dependency Injection - phpugffm13
CDI and Weld
Dependency injection with Symfony 2
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
Zend Framework 2 quick start
The Basic Concept Of IOC

More from Stephan Hochdörfer (20)

PDF
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
PDF
Phing for power users - frOSCon8
PDF
Offline strategies for HTML5 web applications - frOSCon8
PDF
Offline Strategies for HTML5 Web Applications - oscon13
PDF
Dependency Injection in PHP - dwx13
PDF
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Your Business. Your Language. Your Code - dpc13
PDF
Phing for power users - dpc_uncon13
PDF
Offline Strategies for HTML5 Web Applications - ipc13
PDF
Offline-Strategien für HTML5 Web Applikationen - wmka
PDF
Offline-Strategien für HTML5 Web Applikationen - bedcon13
PDF
Testing untestable code - ConFoo13
PDF
A Phing fairy tale - ConFoo13
PDF
Offline strategies for HTML5 web applications - ConFoo13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
Testing untestable code - IPC12
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
PDF
Offline strategies for HTML5 web applications - pfCongres2012
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Phing for power users - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8
Offline Strategies for HTML5 Web Applications - oscon13
Dependency Injection in PHP - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13
Phing for power users - dpc_uncon13
Offline Strategies for HTML5 Web Applications - ipc13
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Testing untestable code - ConFoo13
A Phing fairy tale - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Testing untestable code - IPC12
Offline strategies for HTML5 web applications - IPC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Offline strategies for HTML5 web applications - pfCongres2012
Wie Software-Generatoren die Welt verändern können - Herbstcampus12

Recently uploaded (20)

PDF
Reconciliation AND MEMORANDUM RECONCILATION
PDF
A Brief Introduction About Julia Allison
PPT
Data mining for business intelligence ch04 sharda
PPTX
5 Stages of group development guide.pptx
PPTX
ICG2025_ICG 6th steering committee 30-8-24.pptx
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PPTX
HR Introduction Slide (1).pptx on hr intro
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PPTX
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
PDF
MSPs in 10 Words - Created by US MSP Network
PDF
Katrina Stoneking: Shaking Up the Alcohol Beverage Industry
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PDF
Training And Development of Employee .pdf
PDF
Types of control:Qualitative vs Quantitative
PPTX
Probability Distribution, binomial distribution, poisson distribution
PDF
Ôn tập tiếng anh trong kinh doanh nâng cao
PDF
How to Get Business Funding for Small Business Fast
PPTX
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
PPTX
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
Reconciliation AND MEMORANDUM RECONCILATION
A Brief Introduction About Julia Allison
Data mining for business intelligence ch04 sharda
5 Stages of group development guide.pptx
ICG2025_ICG 6th steering committee 30-8-24.pptx
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
HR Introduction Slide (1).pptx on hr intro
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
MSPs in 10 Words - Created by US MSP Network
Katrina Stoneking: Shaking Up the Alcohol Beverage Industry
340036916-American-Literature-Literary-Period-Overview.ppt
Training And Development of Employee .pdf
Types of control:Qualitative vs Quantitative
Probability Distribution, binomial distribution, poisson distribution
Ôn tập tiếng anh trong kinh doanh nâng cao
How to Get Business Funding for Small Business Fast
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice

Real world dependency injection - DPC10

  • 1. Real World Dependency Injection Stephan Hochdörfer, bitExpert AG "Dependency Injection is a key element of agile architecture" Ward Cunningham
  • 2. Agenda 1. About me 2. What is Dependency Injection? 3. Real World examples 4. Pros & Cons 5. Questions
  • 3. About me  Stephan Hochdörfer, bitExpert AG  Department Manager Research Labs  enjoying PHP since 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 4. What is Dependency Injection? What is Dependency?
  • 5. What is Dependency Injection? What is Dependency?  Application Layer  Data Access layer  Business logic layer  ...  External components  Framework classes  Webservices  ...
  • 6. What is Dependency Injection? Why are Dependencies bad?
  • 7. What is Dependency Injection? Why are Dependencies bad? „new“ is evil!
  • 8. What is Dependency Injection? Why are Dependencies bad?  Tightly coupled code  Hard to re-use components  Hard to test components, no isolation
  • 9. What is Dependency Injection? Simple Dependency Main Required class class
  • 10. What is Dependency Injection? Complex Dependency Required class Main Required class class Required class
  • 11. What is Dependency Injection? Very complex Dependency Database Required class External Main Required resource class class Required class Required Required Webservice class class
  • 12. What is Dependency Injection? Very complex Dependency Database Required class External Main Required resource class class Required class Required Required Webservice class class
  • 13. What is Dependency Injection? Very complex Dependency Database Required class External Main Required resource class class Required class Required Required Webservice class class
  • 14. What is Dependency Injection? How to Manage Dependencies?
  • 15. What is Dependency Injection? How to Manage Dependencies? You don`t need to. The Framework does it all!
  • 16. What is Dependency Injection? How to Manage Dependencies? Simple Container vs. Full stacked Framework
  • 17. What is Dependency Injection? What is Dependency Injection?
  • 18. What is Dependency Injection? What is Dependency Injection? Consumer
  • 19. What is Dependency Injection? What is Dependency Injection? Consumer Dependencies
  • 20. What is Dependency Injection? What is Dependency Injection? Consumer Dependencies Container
  • 21. What is Dependency Injection? What is Dependency Injection? Consumer Dependencies Container
  • 22. What is Dependency Injection? Types of Dependency Injection Type 1: Constructor injection <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; public function __construct(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } } ?>
  • 23. What is Dependency Injection? Types of Dependency Injection Type 2: Setter injection <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; public function setSampleDao(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } } ?>
  • 24. What is Dependency Injection? Types of Dependency Injection Type 3: Interface injection <?php class MySampleService implements IMySampleService, IApplicationContextAware { /** * @var IApplicationContext */ private $oCtx; public function setApplicationContext(IApplicationContext $poCtx) { $this->oCtx = $poCtx; } } ?>
  • 25. What is Dependency Injection? Configuration Types Type 1: Annotations <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; /** * @Inject */ public function __construct(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } } ?>
  • 26. What is Dependency Injection? Configuration Types Type 1: Annotations <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; /** * @Inject * @Named('TheSampleDao') */ public function __construct(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } } ?>
  • 27. What is Dependency Injection? Configuration Types Type 2: External configuration via XML <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.bitexpert.de/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bitexpert.de/schema/ http://www.bitexpert.de/schema/bitFramework-beans.xsd"> <bean id="SampleDao" class="SampleDao"> <constructor-arg value="app_sample" /> <constructor-arg value="iSampleId" /> <constructor-arg value="BoSample" /> </bean> <bean id="SampleService" class="MySampleService"> <constructor-arg ref="SampleDao" /> </bean> </beans>
  • 28. What is Dependency Injection? Configuration Types Type 2: External configuration via YAML services: SampleDao: class: SampleDao arguments: ['app_sample', 'iSampleId', 'BoSample'] SampleService: class: SampleService arguments: [@SampleDao]
  • 29. What is Dependency Injection? Configuration Types Type 3: PHP Configuration <?php class BeanCache extends bF_Beanfactory_Container_PHP_ACache { protected function createSampleDao() { $oBean = new SampleDao('app_sample', 'iSampleId', 'BoSample'); return array("oBean" => $oBean, "bSingleton" => "1"); } protected function createMySampleService() { $oBean = new MySampleService($this->getBean('SampleDao')); return array("oBean" => $oBean, "bSingleton" => "1"); } ?>
  • 30. What is Dependency Injection? Cache, Cache, Cache! 180 160 140 120 100 80 60 40 20 0 XML no Caching XML with Caching PHP PHP compiled Requests per Second meassured via Apache HTTP server benchmarking tool
  • 31. Real world examples "High-level modules should not depend on low-level modules. Both should depend on abstractions." Robert C. Martin
  • 32. Real World examples Unittesting made easy <?php require_once 'PHPUnit/Framework.php'; class ServiceTest extends PHPUnit_Framework_TestCase { public function testSampleService() { $oSampleDao = $this->getMock('ISampleDao'); // run test case $oService = new MySampleService($oSampleDao); $bReturn = $oService->doWork(); // check assertions $this->assertTrue($bReturn); } } ?>
  • 33. Real World examples One class, multiple configurations Implementation Live Working <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.bitexpert.de/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bitexpert.de/schema/ http://www.bitexpert.de/schema/bitFramework-beans.xsd"> <bean id="ExportLive" class="MyApp_Service_ExportManager"> <constructor-arg ref="DAOPageLive" /> </bean> <bean id="ExportWorking" class="MyApp_Service_ExportManager"> <constructor-arg ref="DAOPageWorking" /> </bean> </beans>
  • 34. Real World examples One class, multiple configurations II <?php class Promio_Action_Account_Auth extends bF_Mvc_Action_AFormAction { private $oAccountManager; private $iType; public function __construct(Promio_Service_IAccountManager $poAccountManager) { $this->oAccountManager = $poAccountManager; } public function setType($piType) { $this->iType = (int) $piType; } protected function processFormSubmission(bF_Bo_ABo $poBOFormBackingObject) { $oMaV = new bF_Mvc_ModelAndView($this->getSuccessView(), true); try { $poBOFormBackingObject->setType($this->iType); $this->oAccountManager->save($poBOFormBackingObject); } catch(bF_Service_ServiceException $oException) { $oMaV = new bF_Mvc_ModelAndView($this->getFailureView(), true); } return $oMaV; } } ?>
  • 35. Real World examples Mocking external services Consumer Connector Webservice IConnector interface <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.bitexpert.de/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bitexpert.de/schema/ http://www.bitexpert.de/schema/bitFramework-beans.xsd"> <bean id="Consumer" class="MyApp_Service_Consumer"> <constructor-arg ref="Connector" /> </bean> </beans>
  • 36. Real World examples Mocking external services alternative Local Consumer Connector filesystem IConnector interface <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.bitexpert.de/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bitexpert.de/schema/ http://www.bitexpert.de/schema/bitFramework-beans.xsd"> <bean id="Consumer" class="MyApp_Service_Consumer"> <constructor-arg ref="AltConnector" /> </bean> </beans>
  • 37. Real World examples Clean, readable code <?php class Promio_Action_News_Delete extends bF_Mvc_Action_AAction { /** * @var Promio_Service_INewsManager */ private $oNewsManager; public function __construct(Promio_Service_INewsManager $poNewsManager) { $this->oNewsManager = $poNewsManager; } protected function execute(bF_Mvc_Request $poRequest) { try { $this->oNewsManager->delete((int) $poRequest->getVar('iNewsId')); } catch(bF_Service_ServiceException $oException) { } $oMaV = new bF_Mvc_ModelAndView($this->getSuccessView(), true); return $oMaV; } } ?>
  • 38. Real World examples No framework dependency <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; public function __construct(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } public function getSample($piSampleId) { try { return $this->oSampleDao->readByPrimaryKey((int) $piSampleId); } catch(DaoException $oException) { } } } ?>
  • 39. Pros & Cons Benefits  Good for agile development  Reducing amount of code  Helpful for Unit testing  Loose coupling  Least intrusive mechanism  Switching implementations by changing configuration  Separation of glue code from business logic  Clean view on the code  Separate configuration from code  Getting rid of boilerpate configuration code
  • 40. Pros & Cons Cons  To many different implementations, no standard today!  Bucket, Crafty, FLOW3, Imind_Context, PicoContainer, Pimple, Phemto, Stubbles, Symfony 2.0, Sphicy, Solar, Substrate, XJConf, Yadif, Zend_Di (Proposal), Lion Framework, Spiral Framework, Xyster Framework, …  No JSR 330 for PHP  Simple Containers vs. fully-stacked Framework  No dependency from application to Container!  Developers need to be aware of configuration ↔ runtime