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
About me
 Founder of bitExpert AG, Mannheim

 Field of duty
         
           Department Manager of Research Labs
         
           Head of Development for bitFramework

 Focusing on
        
          PHP
        
          Generative Programming


    Contact me
          
            @shochdoerfer
          
            S.Hochdoerfer@bitExpert.de
Agenda
1.   What is Dependency Injection?

2.   Real World examples

3.   Pros & Cons

4.   Questions
What is Dependency Injection?




     "Dependency Injection is probably one of the most dead simple
      design pattern [...] but it is also one of the most difficult one to
                                 explain well."
                                Fabien Potencier
What is Dependency Injection?




     "Dependency Injection is probably one of the most dead simple
      design pattern [...] but it is also one of the most difficult one to
                                 explain well."
                                Fabien Potencier
What is Dependency Injection?



What is Dependency Injection?

 Popularized by Martin Fowler in 2004

 Technique for supplying external dependencies to a component

 Main idea: Ask for things, do not look for things!

 Three elements
        
          Dependant / Consumer
        
          Dependencies, e.g. service objects
        
          Injector / Container
What is Dependency Injection?



Problems of Dependencies

 Code is very tightly coupled
        
          Hard to re-use code
        
          Hard to test code, no isolation possible

 Difficult to maintain
         
            What is affected when code changes?
         
            Boilerplate configuration code within Business logic
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?



Types of Dependency Injection

Type 1: Interface injection

 <?php

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

      public function setApplicationContext(IApplicationContext $poCtx) {
        $this->oCtx = $poCtx;
      }
 }
 ?>
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: Constructor injection

 <?php

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

   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
         */
       public function __construct(ISampleDao $poSampleDao) {
          $this->oSampleDao = $poSamleDao;
       }
  }
  ?>
What is Dependency Injection?



Configuration Types

Type 2: External configuration via XML, JSON, YAML, ...

 <?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 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");
      }
 ?>
Agenda
1.   What is Dependency Injection?

2.   Real World examples

3.   Pros & Cons

4.   Questions
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



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) {
     }
  }
}
?>
Real World examples



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
Agenda
1.   What is Dependency Injection?

2.   Real World Examples

3.   Pros & Cons

4.   Questions
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

 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
Agenda
1.   What is Dependency Injection?

2.   Pros & Cons

3.   Real World examples

4.   Questions
Real World Dependency Injection - PFCongres 2010

More Related Content

PDF
Testing untestable code - oscon 2012
PDF
Real World Dependency Injection SE - phpugrhh
PDF
Real world dependency injection - DPC10
PDF
Testing untestable code - phpday
PDF
Real World Dependency Injection - phpday
PDF
Dependency Injection in PHP - dwx13
PDF
Real World Dependency Injection - phpugffm13
PDF
Testing untestable code - DPC10
Testing untestable code - oscon 2012
Real World Dependency Injection SE - phpugrhh
Real world dependency injection - DPC10
Testing untestable code - phpday
Real World Dependency Injection - phpday
Dependency Injection in PHP - dwx13
Real World Dependency Injection - phpugffm13
Testing untestable code - DPC10

What's hot (20)

PDF
Real World Dependency Injection - IPC11 Spring Edition
PDF
Testing untestable Code - PFCongres 2010
KEY
IoC with PHP
PDF
Create Your Own Framework by Fabien Potencier
ODP
Dependency Injection, Zend Framework and Symfony Container
PPS
Authentication with zend framework
PDF
ioc-castle-windsor
PDF
Enterprise Security API (ESAPI) Java - Java User Group San Antonio
PDF
JDT Fundamentals 2010
PDF
Instant ACLs with Zend Framework 2
PPT
Contexts and Dependency Injection for the JavaEE platform
ODP
Implementing security routines with zf2
PDF
Advanced java interview questions
PPT
Spring frame work
PDF
Seven Versions of One Web Application
PDF
Java j2ee interview_questions
PPT
Spring talk111204
PDF
iOS API Design
PPTX
Zend Studio Tips and Tricks
PPT
Enterprise java beans(ejb) update 2
Real World Dependency Injection - IPC11 Spring Edition
Testing untestable Code - PFCongres 2010
IoC with PHP
Create Your Own Framework by Fabien Potencier
Dependency Injection, Zend Framework and Symfony Container
Authentication with zend framework
ioc-castle-windsor
Enterprise Security API (ESAPI) Java - Java User Group San Antonio
JDT Fundamentals 2010
Instant ACLs with Zend Framework 2
Contexts and Dependency Injection for the JavaEE platform
Implementing security routines with zf2
Advanced java interview questions
Spring frame work
Seven Versions of One Web Application
Java j2ee interview_questions
Spring talk111204
iOS API Design
Zend Studio Tips and Tricks
Enterprise java beans(ejb) update 2
Ad

Viewers also liked (6)

PDF
Facebook Apps: Ein Entwicklungsleitfaden - WMMRN
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Phing for power users - dpc_uncon13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
The state of DI in PHP - phpbnl12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Facebook Apps: Ein Entwicklungsleitfaden - WMMRN
Offline strategies for HTML5 web applications - IPC12
Phing for power users - dpc_uncon13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
The state of DI in PHP - phpbnl12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Ad

Similar to Real World Dependency Injection - PFCongres 2010 (20)

PDF
Real World Dependency Injection - oscon13
PDF
What is Dependency Injection
PPT
Dependency injection with PHP
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
PDF
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
PDF
Dependency Injection
PDF
The Basic Concept Of IOC
PPTX
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
PDF
CDI and Weld
PDF
Dependencies, dependencies, dependencies
PPTX
Dependency injection with Symfony 2
PDF
Dependency injection Drupal Camp Wrocław 2014
PPTX
L09 Frameworks
KEY
Zend Di in ZF 2.0
PDF
DIC To The Limit – deSymfonyDay, Barcelona 2014
PDF
CDI and Weld
PDF
Dependency Injection in Drupal 8
PPTX
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
PPTX
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
PDF
Using Contexts & Dependency Injection in the Java EE 6 Platform
Real World Dependency Injection - oscon13
What is Dependency Injection
Dependency injection with PHP
Clean Code Part II - Dependency Injection at SoCal Code Camp
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Dependency Injection
The Basic Concept Of IOC
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
CDI and Weld
Dependencies, dependencies, dependencies
Dependency injection with Symfony 2
Dependency injection Drupal Camp Wrocław 2014
L09 Frameworks
Zend Di in ZF 2.0
DIC To The Limit – deSymfonyDay, Barcelona 2014
CDI and Weld
Dependency Injection in Drupal 8
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Using Contexts & Dependency Injection in the Java EE 6 Platform

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
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Your Business. Your Language. Your Code - dpc13
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
Testing untestable code - IPC12
PDF
Offline strategies for HTML5 web applications - pfCongres2012
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
PDF
Testing untestable code - Herbstcampus12
PDF
Introducing a Software Generator Framework - JAZOON12
PDF
The state of DI - DPC12
PDF
Separation of concerns - DPC12
PDF
Managing variability in software applications - scandev12
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
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13
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
Testing untestable code - IPC12
Offline strategies for HTML5 web applications - pfCongres2012
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Testing untestable code - Herbstcampus12
Introducing a Software Generator Framework - JAZOON12
The state of DI - DPC12
Separation of concerns - DPC12
Managing variability in software applications - scandev12

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
cuic standard and advanced reporting.pdf
PPT
Teaching material agriculture food technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Cloud computing and distributed systems.
PDF
KodekX | Application Modernization Development
PDF
Empathic Computing: Creating Shared Understanding
PDF
Modernizing your data center with Dell and AMD
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Weekly Chronicles - August'25 Week I
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
cuic standard and advanced reporting.pdf
Teaching material agriculture food technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Machine learning based COVID-19 study performance prediction
Chapter 3 Spatial Domain Image Processing.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Understanding_Digital_Forensics_Presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Cloud computing and distributed systems.
KodekX | Application Modernization Development
Empathic Computing: Creating Shared Understanding
Modernizing your data center with Dell and AMD

Real World Dependency Injection - PFCongres 2010

  • 1. Real World Dependency Injection Stephan Hochdörfer, bitExpert AG "Dependency Injection is a key element of agile architecture" Ward Cunningham
  • 2. About me  Founder of bitExpert AG, Mannheim  Field of duty  Department Manager of Research Labs  Head of Development for bitFramework  Focusing on  PHP  Generative Programming  Contact me  @shochdoerfer  S.Hochdoerfer@bitExpert.de
  • 3. Agenda 1. What is Dependency Injection? 2. Real World examples 3. Pros & Cons 4. Questions
  • 4. What is Dependency Injection? "Dependency Injection is probably one of the most dead simple design pattern [...] but it is also one of the most difficult one to explain well." Fabien Potencier
  • 5. What is Dependency Injection? "Dependency Injection is probably one of the most dead simple design pattern [...] but it is also one of the most difficult one to explain well." Fabien Potencier
  • 6. What is Dependency Injection? What is Dependency Injection?  Popularized by Martin Fowler in 2004  Technique for supplying external dependencies to a component  Main idea: Ask for things, do not look for things!  Three elements  Dependant / Consumer  Dependencies, e.g. service objects  Injector / Container
  • 7. What is Dependency Injection? Problems of Dependencies  Code is very tightly coupled  Hard to re-use code  Hard to test code, no isolation possible  Difficult to maintain  What is affected when code changes?  Boilerplate configuration code within Business logic
  • 8. What is Dependency Injection? Simple Dependency Main Required class class
  • 9. What is Dependency Injection? Complex Dependency Required class Main Required class class Required class
  • 10. What is Dependency Injection? Very complex Dependency Database Required class External Main Required resource class class Required class Required Required Webservice class 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? How to Manage Dependencies?
  • 14. What is Dependency Injection? How to Manage Dependencies? You don`t need to. The Framework does it all!
  • 15. What is Dependency Injection? Types of Dependency Injection Type 1: Interface injection <?php class MySampleService implements IMySampleService, IApplicationContextAware { /** * @var IApplicationContext */ private $oCtx; public function setApplicationContext(IApplicationContext $poCtx) { $this->oCtx = $poCtx; } } ?>
  • 16. 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; } } ?>
  • 17. What is Dependency Injection? Types of Dependency Injection Type 3: Constructor injection <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $oSampleDao; public function __construct(ISampleDao $poSampleDao) { $this->oSampleDao = $poSamleDao; } } ?>
  • 18. 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; } } ?>
  • 19. What is Dependency Injection? Configuration Types Type 2: External configuration via XML, JSON, YAML, ... <?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>
  • 20. 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"); } ?>
  • 21. Agenda 1. What is Dependency Injection? 2. Real World examples 3. Pros & Cons 4. Questions
  • 22. Real world examples "High-level modules should not depend on low-level modules. Both should depend on abstractions." Robert C. Martin
  • 23. 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); } } ?>
  • 24. 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>
  • 25. 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>
  • 26. 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>
  • 27. 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; } } ?>
  • 28. 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) { } } } ?>
  • 29. Real World examples 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
  • 30. Agenda 1. What is Dependency Injection? 2. Real World Examples 3. Pros & Cons 4. Questions
  • 31. 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  Clean view on the code  Separate configuration from code  Getting rid of boilerpate configuration code
  • 32. 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
  • 33. Agenda 1. What is Dependency Injection? 2. Pros & Cons 3. Real World examples 4. Questions