SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
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?

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
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
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
[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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Dernier (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
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)
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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?