SlideShare a Scribd company logo
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
Ad

More Related Content

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
Ashwini 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 PHP
mtoppa
 
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
Alexander 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 2014
Greg Szczotka
 
Singularity Registry HPC
Singularity Registry HPCSingularity Registry HPC
Singularity Registry HPC
Vanessa S
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
Xiaoyan Chen
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
Stephan Hochdörfer
 
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
Stephan 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 2010
singingfish
 
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
Fred Moyer
 
Plugging into plugins
Plugging into pluginsPlugging into plugins
Plugging into plugins
Josh Harrison
 
The breakup
The breakupThe breakup
The breakup
Samantha Billington
 
2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
terry chay
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
ColdFusionConference
 
SPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetupSPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetup
Hasith Yaggahavita
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Growing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaisesGrowing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaises
Philip Bauer
 
Binding android piece by piece
Binding android piece by pieceBinding android piece by piece
Binding android piece by piece
Bucharest Java User Group
 
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
 
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
Ashwini 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 PHP
mtoppa
 
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
Alexander 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 2014
Greg Szczotka
 
Singularity Registry HPC
Singularity Registry HPCSingularity Registry HPC
Singularity Registry HPC
Vanessa S
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
Xiaoyan 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 - phpbnl12
Stephan 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 2010
singingfish
 
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
Fred Moyer
 
Plugging into plugins
Plugging into pluginsPlugging into plugins
Plugging into plugins
Josh Harrison
 
SPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetupSPA Architecture Basics - Colombo JS meetup
SPA Architecture Basics - Colombo JS meetup
Hasith Yaggahavita
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Growing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaisesGrowing pains - PosKeyErrors and other malaises
Growing pains - PosKeyErrors and other malaises
Philip 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
 

Recently uploaded (20)

AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Ad

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