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

More Related Content

Similar to Dependency injection

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael 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 Rails
Simobo
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
Alex 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.pptx
Maarten 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
 
tick cross game
tick cross gametick cross game
tick cross game
sanobersheir
 
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
Alex Theedom
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
25csharp
25csharp25csharp
25csharp
Sireesh K
 
25c
25c25c
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 patterns
Alex 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
 
Javascript
JavascriptJavascript
Javascript
Sunil Thakur
 
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 Java
Radhika Talaviya
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
Nick 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 signatures
mametter
 
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
Henry S
 

Similar to 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
 

Recently uploaded

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 

Recently uploaded (20)

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 

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?