SlideShare a Scribd company logo
1 of 33
Download to read offline
What is Dependency
    Injection?

    Shawn Stratton

     2nd June 2011—
What I’ll Cover

I will cover:




                  2
What I’ll Cover

I will cover:

  • What DI isn’t




                    2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is




                    2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is

  • Why you should use DI




                            2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is

  • Why you should use DI

I won’t cover:




                            2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is

  • Why you should use DI

I won’t cover:

  • How to implement DI in your project




                                          2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is

  • Why you should use DI

I won’t cover:

  • How to implement DI in your project

  • Differences in available containers



                                          2
What I’ll Cover

I will cover:

  • What DI isn’t

  • What DI is

  • Why you should use DI

I won’t cover:

  • How to implement DI in your project

  • Differences in available containers

  • How to cook awesome bacon (ask Jeff)

                                           2
What is Dependency
  Injection not?
New




Figure 1: http://martinfowler.com/articles/injection.html


                                                            4
Magic




        Figure 2: Merlin by One Luck Guy (Flickr)

                                                    5
Complex




   Figure 3: Complexity 3 by Michael Heiss (Flickr)
                                                      6
So what is it?
A Design Style



<?php
/ / J u s t Some Class
c l a s s Dependant {
    p r o t e c t e d $db ;
    p r o t e c t e d $dependency ;
    p u b l i c f u n c t i o n __construct ( PDO $db , Depdendency
          $dependency ) {
        $this−>db = $db ;
        $this−>dependency = $dependency ;
    }

    p u b l i c f u n c t i o n somefunc ( ) {
       / / Use Dependencies
    }
}



                                                                      8
Easy



<?php
/ / T h i s i s Meta Code Only ( n o t a c o n c r e t e I m p l e m e n t a t i o n )

/ / Create Locator , pass a mappings f i l e o r v a r
/ / Note Dependency would be d e f i n e d here as would
/ / Dependant
$sl = new Container ( ’ / path / t o / mappings / f i l e ’ ) ;
/ / Create PDO ( we don ’ t want t o map i t )
$pdo = new PDO ( ’ dsn ’ ) ;
$sl−>defineSingleton ( ’PDO ’ , $pdo ) ;

$dependant = $sl−>get ( ’ Dependant ’ ) ;
/ / Dependant i s t y p e o f Dependant




                                                                                         9
About Components
Service Locator
Service Locator




       Service Location is like ordering with
   substitutions, and having the waiter completely
   ignore the substitutions; you get what’s on the
   menu, nothing more, nothing less.

Figure 4: Matthew Weier O‘Phinney on Service Locators




                                                        12
Service Locators Detail




 • It’s a fancy registry.

 • Inject the locator into the class via contstructor, call
   the the locator to find your services.

 • Works, but it’s not foolproof




                                                              13
Containers
Another Analogy




        Dependency Injection is like ordering off the
   menu – but specifying things like, ”I’d like to
   substitute portabella mushrooms for the patties,
   please.” The waiter then goes and brings your
   dish, which has portabella mushrooms instead
   of the hamburger patties listed on the menu.

 Figure 5: Matthew Weier O‘Phinney on DI Containers



                                                        15
DI Container Detail




 • Still a fancy registry, basically just a Service Locator.


 • Instantiates new classes by resolving and injecting
   their dependencies.

 • Very Clean in regards to separation of concerns.

 • Not required to run the system (you can do this
   manually, trust me)



                                                               16
What are the benefits of
Dependency Injection?
Makes Testing Easy



<?php
c l a s s DependantTest extends PHPUnit_Framework_TestCase

    p r o t e c t e d $dependant ;

    p r o t e c t e d f u n c t i o n setUp ( ) {
        $pdo = new PDO ( ’ s q l i t e dsn ’ ) ;
        $dependency = $this−>getMock ( ’ Dependency ’ ,
               a r r a y ( ’ someFunction ’ ) ) ;
        $dependency−>expects ( $this−>once ( ) )−>method (
               ’ someFunction ’ ) ;
        $this−>dependant = new Dependant ( $pdo , $dependency ) ;
    }
}




                                                                    18
Easy Extension




Steps to extend and use a class:




                                   19
Easy Extension




Steps to extend and use a class:

 1. Create class b and have it extend class a




                                                19
Easy Extension




Steps to extend and use a class:

 1. Create class b and have it extend class a

 2. Change Mapping




                                                19
Easy Extension




Steps to extend and use a class:

 1. Create class b and have it extend class a

 2. Change Mapping

 3. Profit!




                                                19
What are the costs?
Enforces Interfaces



<?php
/ / I n t e f a c e D e f i n i n g t h e ” Math ” Api
i n t e r f a c e Math {
    p u b l i c f u n c t i o n add ( $a , $b ) ;
    p u b l i c f u n c t i o n sub ( $a , $b ) ;
    p u b l i c f u n c t i o n multiply ( $a , $b ) ;
    p u b l i c f u n c t i o n divide ( $a , $b ) ;
}
/ / 2+2 = 5 f o r l a r g e v a l u e s o f 2
/ / ( see Thinkgeek s h i r t s )
c l a s s HeavyMath implements Math {
    p u b l i c f u n c t i o n add ( $a , $b )
    {
        r e t u r n ( $a == 2 && $b == 2 ) ? 5 : $a+$b ;
    }



                                                           21
Mapping Files



<?php
return array (
   ’ Foo ’ => a r r a y (
      ’ class ’        => ’ Zend Foo ’ ,
      ’ arguments ’ => a r r a y ( ’ c o n s t r u c t ’ => ’ ComponentA ’ ) ,
   ),
   ’ ComponentA ’ => a r r a y (
      ’ class ’           => ’ Zend Foo Component A ’ ,
      ’ instanceof ’        => ’ Zend Foo Component Interface ’ ,
);


Figure 6: Zend DI Proposal by Frederic Cargnelutti (mod-
ified)


                                                                                 22
Thank You

More Resources:

 • Martin Fowler on Inversion of Control -
   http://martinfowler.com/articles/injectio


 • Ralph Schindler on Learning Dependency Injection -
   http://bit.ly/php-di

 • Sebastian Bergmann has an awesome book called
   Real-World Solutions for Developing High-Quality
   PHP Frameworks and Applications


     Ask Luke Allison about his Amazing Horse!
                                                        23

More Related Content

Similar to What is Dependency Injection

Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLADependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLAAshwini Kumar
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toAlexander Makarov
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Singularity Registry HPC
Singularity Registry HPCSingularity Registry HPC
Singularity Registry HPCVanessa S
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principlesXiaoyan Chen
 
The state of DI in PHP - phpbnl12
The state of DI in PHP - phpbnl12The state of DI in PHP - phpbnl12
The state of DI in PHP - phpbnl12Stephan Hochdörfer
 
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010singingfish
 
The Breakup - Logically Sharding a Growing PostgreSQL Database
The Breakup - Logically Sharding a Growing PostgreSQL DatabaseThe Breakup - Logically Sharding a Growing PostgreSQL Database
The Breakup - Logically Sharding a Growing PostgreSQL DatabaseFred Moyer
 
Plugging into plugins
Plugging into pluginsPlugging into plugins
Plugging into pluginsJosh Harrison
 
SPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetupSPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetupHasith Yaggahavita
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Growing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaisesGrowing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaisesPhilip Bauer
 
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner)
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner) Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner)
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner) Puppet
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)andrewnacin
 

Similar to What is Dependency Injection (20)

Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLADependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLA
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading to
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Singularity Registry HPC
Singularity Registry HPCSingularity Registry HPC
Singularity Registry HPC
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
 
The state of DI in PHP - phpbnl12
The state of DI in PHP - phpbnl12The state of DI in PHP - phpbnl12
The state of DI in PHP - phpbnl12
 
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
 
The Breakup - Logically Sharding a Growing PostgreSQL Database
The Breakup - Logically Sharding a Growing PostgreSQL DatabaseThe Breakup - Logically Sharding a Growing PostgreSQL Database
The Breakup - Logically Sharding a Growing PostgreSQL Database
 
Plugging into plugins
Plugging into pluginsPlugging into plugins
Plugging into plugins
 
The breakup
The breakupThe breakup
The breakup
 
2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
 
SPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetupSPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetup
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Growing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaisesGrowing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaises
 
Binding android piece by piece
Binding android piece by pieceBinding android piece by piece
Binding android piece by piece
 
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner)
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner) Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner)
Puppet Camp Melbourne 2014: Puppet and a DevOps Journey (Beginner)
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

What is Dependency Injection

  • 1. What is Dependency Injection? Shawn Stratton 2nd June 2011—
  • 2. What I’ll Cover I will cover: 2
  • 3. What I’ll Cover I will cover: • What DI isn’t 2
  • 4. What I’ll Cover I will cover: • What DI isn’t • What DI is 2
  • 5. What I’ll Cover I will cover: • What DI isn’t • What DI is • Why you should use DI 2
  • 6. What I’ll Cover I will cover: • What DI isn’t • What DI is • Why you should use DI I won’t cover: 2
  • 7. What I’ll Cover I will cover: • What DI isn’t • What DI is • Why you should use DI I won’t cover: • How to implement DI in your project 2
  • 8. What I’ll Cover I will cover: • What DI isn’t • What DI is • Why you should use DI I won’t cover: • How to implement DI in your project • Differences in available containers 2
  • 9. What I’ll Cover I will cover: • What DI isn’t • What DI is • Why you should use DI I won’t cover: • How to implement DI in your project • Differences in available containers • How to cook awesome bacon (ask Jeff) 2
  • 10. What is Dependency Injection not?
  • 12. Magic Figure 2: Merlin by One Luck Guy (Flickr) 5
  • 13. Complex Figure 3: Complexity 3 by Michael Heiss (Flickr) 6
  • 14. So what is it?
  • 15. A Design Style <?php / / J u s t Some Class c l a s s Dependant { p r o t e c t e d $db ; p r o t e c t e d $dependency ; p u b l i c f u n c t i o n __construct ( PDO $db , Depdendency $dependency ) { $this−>db = $db ; $this−>dependency = $dependency ; } p u b l i c f u n c t i o n somefunc ( ) { / / Use Dependencies } } 8
  • 16. Easy <?php / / T h i s i s Meta Code Only ( n o t a c o n c r e t e I m p l e m e n t a t i o n ) / / Create Locator , pass a mappings f i l e o r v a r / / Note Dependency would be d e f i n e d here as would / / Dependant $sl = new Container ( ’ / path / t o / mappings / f i l e ’ ) ; / / Create PDO ( we don ’ t want t o map i t ) $pdo = new PDO ( ’ dsn ’ ) ; $sl−>defineSingleton ( ’PDO ’ , $pdo ) ; $dependant = $sl−>get ( ’ Dependant ’ ) ; / / Dependant i s t y p e o f Dependant 9
  • 19. Service Locator Service Location is like ordering with substitutions, and having the waiter completely ignore the substitutions; you get what’s on the menu, nothing more, nothing less. Figure 4: Matthew Weier O‘Phinney on Service Locators 12
  • 20. Service Locators Detail • It’s a fancy registry. • Inject the locator into the class via contstructor, call the the locator to find your services. • Works, but it’s not foolproof 13
  • 22. Another Analogy Dependency Injection is like ordering off the menu – but specifying things like, ”I’d like to substitute portabella mushrooms for the patties, please.” The waiter then goes and brings your dish, which has portabella mushrooms instead of the hamburger patties listed on the menu. Figure 5: Matthew Weier O‘Phinney on DI Containers 15
  • 23. DI Container Detail • Still a fancy registry, basically just a Service Locator. • Instantiates new classes by resolving and injecting their dependencies. • Very Clean in regards to separation of concerns. • Not required to run the system (you can do this manually, trust me) 16
  • 24. What are the benefits of Dependency Injection?
  • 25. Makes Testing Easy <?php c l a s s DependantTest extends PHPUnit_Framework_TestCase p r o t e c t e d $dependant ; p r o t e c t e d f u n c t i o n setUp ( ) { $pdo = new PDO ( ’ s q l i t e dsn ’ ) ; $dependency = $this−>getMock ( ’ Dependency ’ , a r r a y ( ’ someFunction ’ ) ) ; $dependency−>expects ( $this−>once ( ) )−>method ( ’ someFunction ’ ) ; $this−>dependant = new Dependant ( $pdo , $dependency ) ; } } 18
  • 26. Easy Extension Steps to extend and use a class: 19
  • 27. Easy Extension Steps to extend and use a class: 1. Create class b and have it extend class a 19
  • 28. Easy Extension Steps to extend and use a class: 1. Create class b and have it extend class a 2. Change Mapping 19
  • 29. Easy Extension Steps to extend and use a class: 1. Create class b and have it extend class a 2. Change Mapping 3. Profit! 19
  • 30. What are the costs?
  • 31. Enforces Interfaces <?php / / I n t e f a c e D e f i n i n g t h e ” Math ” Api i n t e r f a c e Math { p u b l i c f u n c t i o n add ( $a , $b ) ; p u b l i c f u n c t i o n sub ( $a , $b ) ; p u b l i c f u n c t i o n multiply ( $a , $b ) ; p u b l i c f u n c t i o n divide ( $a , $b ) ; } / / 2+2 = 5 f o r l a r g e v a l u e s o f 2 / / ( see Thinkgeek s h i r t s ) c l a s s HeavyMath implements Math { p u b l i c f u n c t i o n add ( $a , $b ) { r e t u r n ( $a == 2 && $b == 2 ) ? 5 : $a+$b ; } 21
  • 32. Mapping Files <?php return array ( ’ Foo ’ => a r r a y ( ’ class ’ => ’ Zend Foo ’ , ’ arguments ’ => a r r a y ( ’ c o n s t r u c t ’ => ’ ComponentA ’ ) , ), ’ ComponentA ’ => a r r a y ( ’ class ’ => ’ Zend Foo Component A ’ , ’ instanceof ’ => ’ Zend Foo Component Interface ’ , ); Figure 6: Zend DI Proposal by Frederic Cargnelutti (mod- ified) 22
  • 33. Thank You More Resources: • Martin Fowler on Inversion of Control - http://martinfowler.com/articles/injectio • Ralph Schindler on Learning Dependency Injection - http://bit.ly/php-di • Sebastian Bergmann has an awesome book called Real-World Solutions for Developing High-Quality PHP Frameworks and Applications Ask Luke Allison about his Amazing Horse! 23