SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
dependency injection
The pattern
by Marc Morera
@BeFactory
class Carpenter	

{	

	

 public function work()	

	

 {	

	

 	

 $hammer = new Hammer();	

	

 	

 $hammer->chop();	

	

 }	

}	

!

$carpenter = new Carpenter();	

$carpenter->work();
Problems?
Let’s talk about	

responsibility
•

Any carpenter should ignore how to build a
hammer, but how to use it.	


•

The carpenter goes to a hardware store to get
some nice brown and big hammer.
•

Not testable	


•

High coupling
class Carpenter	

{	

	

 public function work(Hammer $hammer)	

	

 {	

	

 	

 $hammer->chop();	

	

 }	

}	

!

$hammer = new Hammer();	

$carpenter = new Carpenter();	

$carpenter->work($hammer);
•

So can we just have a carpenter without a
hammer?	


•

No way!	


•

A carpenter ALWAYS have a hammer.	


•

No hammer, no carpenter.
class Carpenter	

{	

	

 private $hammer;	

!

	

	

	

	


public function __construct(Hammer $hammer)	

{	

 	

	

 $this->hammer = $hammer;	

}	


!

	

	

	

	

}	


public function work()	

{	

	

 $this->hammer->chop();	

}	


!

$hammer = new Hammer();	

$carpenter = new Carpenter($hammer);	

$carpenter->work();
2 years later…
•

All carpenters are upgraded.	


•

No hammers anymore.	


•

All carpenters will use a simple small red mallet
•

We want to make sure all objects that every
carpenter will use to chop, will be suitable for
that.	


•

How can ensure this?
Interfaces
interface ToolInterface	

{	

	

 public function chop();	

}	

!

class Hammer implements ToolInterface	

{	

	

 public function chop()	

	

 {	

	

 }	

}	

!

class Mallet implements ToolInterface	

{	

	

 public function chop()	

	

 {	

	

 }	

}
class Carpenter	

{	

	

 private $tool;	

!

	

	

	

	


public function __construct(ToolInterface $tool)	

{	

 	

	

 $this->tool = $tool;	

}	


!

	

	

	

	

}	


public function work()	

{	

	

 $this->tool->chop();	

}	


!

$carpenter = new Carpenter(new Hammer);	

$carpenter = new Carpenter(new Mallet);	

$carpenter->work();
•

Very testable and easily mockable	


•

Low coupling	


•

Seems to be the best solution ever
But…
is this implementation a good one?
NO.
•

This is purely what means dependency
injection.	


•

Every dependency of an object is injected	


•

… into the constructor if is needed for the
class to be built	


•

… in a method if is just needed for this
method
Think about a full project with this code
$iron = new Iron;	

$wood = new Wood;	

$plastic = new Plastic(new Blue);	

$hammer = new Hammer($iron, $wood, $plastic);	

$paintCan = new Paint(new Red);	

$carpenter = new Carpenter($hammer, $glasses, $paintCan);	

!

$nail = new Nail($iron);	

$carpenter->work($iron);
•

Not maintainable	


•

Not scalable	


•

Responsibility of building a carpenter is now
distributed by all controllers.
Container
What container should provide?
•

Definition	


•

Customization	


•

Instantiation
•

Our container is the provider of all instances.	


•

It is therefore responsable of building them
Services
•

A service is just an instance of an object	


•

Each service must define the path of the object
( given by the namespace )	


•

Also can define how to be built ( arguments )	


•

An argument can be another service ( using @ )
services:	

	

 iron:	

	

 	

 class: Iron	

	

 wood:	

	

 	

 class: Wood	

	

 plastic:	

	

 	

 class: Plastic	

	

 hammer:	

	

 	

 class: Hammer	

	

 	

 arguments:	

	

 	

 	

 iron: @iron	

	

 	

 	

 wood: @wood	

	

 	

 	

 plastic: @plastic	

	

 carpenter:	

	

 	

 class: Carpenter	

	

 	

 arguments:	

	

 	

 	

 hammer: @hammer
$carpenter = $container->get(‘carpenter’);
Customization
•

In this example, every time a Carpenter is
requested, a new Hammer will be used.	


•

If we want to switch to a Mallet, we must change
definition.	


•

We should be able to configure it outside the
definition of the container.
services:	

	

 iron:	

	

 	

 class: Iron	

	

 wood:	

	

 	

 class: Wood	

	

 plastic:	

	

 	

 class: Plastic	

	

 hammer:	

	

 	

 class: Hammer	

	

 	

 arguments:	

	

 	

 	

 iron: @iron	

	

 	

 	

 wood: @wood	

	

 	

 	

 plastic: @plastic	

	

 carpenter:	

	

 	

 class: Carpenter	

	

 	

 arguments:	

	

 	

 	

 hammer: @hammer
Parameters

•

Any parameter should be able to be defined in
the project	


•

A parameter is used using “%” keyword.
parameters:	

	

 tool_class: Hammer	

services:	

	

 iron:	

	

 	

 class: Iron	

	

 wood:	

	

 	

 class: Wood	

	

 plastic:	

	

 	

 class: Plastic	

	

 tool:	

	

 	

 class: %tool_class%	

	

 	

 arguments:	

	

 	

 	

 iron: @iron	

	

 	

 	

 wood: @wood	

	

 	

 	

 plastic: @plastic	

	

 carpenter:	

	

 	

 class: Carpenter	

	

 	

 arguments:	

	

 	

 	

 tool: @tool
Scopes
•

Prototype. 	


•

Container. Some objects can be just reused in
every request ( an infinite paint can ) - In the
real world, a Logger or a simple Text library.
Prototype
•

One instance per container request	


•

Container just build an instance and return it	


•

It’s defined by setting scope: prototype	


•

For example, a nail
Container
•

First time, object is built and stored.	


•

From next requests, same instance is reused and
returned	


•

Saving memory ( storing objects ) and cpu ( building
them )	


•

It’s defined by setting scope: container. Default behavior
services:	

	

 paint_can:	

	

 	

 class: PaintCan	

	

 	

 scope: container	

	

 carpenter:	

	

 	

 class: Painter	

	

 	

 scope: prototype	

	

 	

 arguments:	

	

 	

 	

 paint_can: @paint_can
•

Each time a painter is requested, we’ll reuse
same paint can object since they all can share
it.
Implementations
•

Symfony2 - DependencyInjection Component	


•

Android - Dagger	


•

Objective C - Typhoon
DI Saves your life
Use it, dude!
QA?

Mais conteúdo relacionado

Semelhante a Dependency injection

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JSFestUA
 
Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsSimobo
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design PatternsAlex Theedom
 
Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxMaarten Balliauw
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016Alex Theedom
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns Alex Theedom
 
Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patternsAlex Theedom
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 Sumant Tambe
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Bruce Li
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compassNick Cooley
 
Type Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesType Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesmametter
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 

Semelhante a Dependency injection (20)

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
 
Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on Rails
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptx
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
tick cross game
tick cross gametick cross game
tick cross game
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
25csharp
25csharp25csharp
25csharp
 
25c
25c25c
25c
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
 
Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patterns
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
Javascript
JavascriptJavascript
Javascript
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
 
Type Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesType Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signatures
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 

Último

MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Dependency injection

  • 3. class Carpenter { public function work() { $hammer = new Hammer(); $hammer->chop(); } } ! $carpenter = new Carpenter(); $carpenter->work();
  • 6. • Any carpenter should ignore how to build a hammer, but how to use it. • The carpenter goes to a hardware store to get some nice brown and big hammer.
  • 8. class Carpenter { public function work(Hammer $hammer) { $hammer->chop(); } } ! $hammer = new Hammer(); $carpenter = new Carpenter(); $carpenter->work($hammer);
  • 9. • So can we just have a carpenter without a hammer? • No way! • A carpenter ALWAYS have a hammer. • No hammer, no carpenter.
  • 10. class Carpenter { private $hammer; ! public function __construct(Hammer $hammer) { $this->hammer = $hammer; } ! } public function work() { $this->hammer->chop(); } ! $hammer = new Hammer(); $carpenter = new Carpenter($hammer); $carpenter->work();
  • 11. 2 years later… • All carpenters are upgraded. • No hammers anymore. • All carpenters will use a simple small red mallet
  • 12. • We want to make sure all objects that every carpenter will use to chop, will be suitable for that. • How can ensure this?
  • 14. interface ToolInterface { public function chop(); } ! class Hammer implements ToolInterface { public function chop() { } } ! class Mallet implements ToolInterface { public function chop() { } }
  • 15. class Carpenter { private $tool; ! public function __construct(ToolInterface $tool) { $this->tool = $tool; } ! } public function work() { $this->tool->chop(); } ! $carpenter = new Carpenter(new Hammer); $carpenter = new Carpenter(new Mallet); $carpenter->work();
  • 16. • Very testable and easily mockable • Low coupling • Seems to be the best solution ever
  • 18. NO.
  • 19. • This is purely what means dependency injection. • Every dependency of an object is injected • … into the constructor if is needed for the class to be built • … in a method if is just needed for this method
  • 20. Think about a full project with this code $iron = new Iron; $wood = new Wood; $plastic = new Plastic(new Blue); $hammer = new Hammer($iron, $wood, $plastic); $paintCan = new Paint(new Red); $carpenter = new Carpenter($hammer, $glasses, $paintCan); ! $nail = new Nail($iron); $carpenter->work($iron);
  • 21. • Not maintainable • Not scalable • Responsibility of building a carpenter is now distributed by all controllers.
  • 23. What container should provide? • Definition • Customization • Instantiation
  • 24. • Our container is the provider of all instances. • It is therefore responsable of building them
  • 25. Services • A service is just an instance of an object • Each service must define the path of the object ( given by the namespace ) • Also can define how to be built ( arguments ) • An argument can be another service ( using @ )
  • 26. services: iron: class: Iron wood: class: Wood plastic: class: Plastic hammer: class: Hammer arguments: iron: @iron wood: @wood plastic: @plastic carpenter: class: Carpenter arguments: hammer: @hammer
  • 28. Customization • In this example, every time a Carpenter is requested, a new Hammer will be used. • If we want to switch to a Mallet, we must change definition. • We should be able to configure it outside the definition of the container.
  • 29. services: iron: class: Iron wood: class: Wood plastic: class: Plastic hammer: class: Hammer arguments: iron: @iron wood: @wood plastic: @plastic carpenter: class: Carpenter arguments: hammer: @hammer
  • 30. Parameters • Any parameter should be able to be defined in the project • A parameter is used using “%” keyword.
  • 31. parameters: tool_class: Hammer services: iron: class: Iron wood: class: Wood plastic: class: Plastic tool: class: %tool_class% arguments: iron: @iron wood: @wood plastic: @plastic carpenter: class: Carpenter arguments: tool: @tool
  • 32. Scopes • Prototype. • Container. Some objects can be just reused in every request ( an infinite paint can ) - In the real world, a Logger or a simple Text library.
  • 33. Prototype • One instance per container request • Container just build an instance and return it • It’s defined by setting scope: prototype • For example, a nail
  • 34. Container • First time, object is built and stored. • From next requests, same instance is reused and returned • Saving memory ( storing objects ) and cpu ( building them ) • It’s defined by setting scope: container. Default behavior
  • 35. services: paint_can: class: PaintCan scope: container carpenter: class: Painter scope: prototype arguments: paint_can: @paint_can
  • 36. • Each time a painter is requested, we’ll reuse same paint can object since they all can share it.
  • 37. Implementations • Symfony2 - DependencyInjection Component • Android - Dagger • Objective C - Typhoon
  • 38. DI Saves your life Use it, dude!
  • 39. QA?