SlideShare a Scribd company logo
Dependency Injection and
       Symfony
Introduction
Cameron Manderson
Developer, Director of Flint, Melbourne Symfony2 Organiser




cameronmanderson@gmail.com
Follow: @cammanderson
www.linkedin.com/in/cameronmanderson
Topic Highlight
• More in-depth look at the background of
  “Dependency Injection”
• Aiming to uncover in Symfony
  – Modularity in our implementation
  – Loose decoupling of dependencies
  – Managing scope and access to dependencies
Background
Some terminology
• Dependency
  – Something that is required by another object to
    fulfill its function
• Dependent
  – A client object that needs a dependency in order
    to perform its function
Shown easiest like this..

Dependent           Dependency


            Like…

 Emailer            Spell Checker
Example in code
This seems fine.. Right?
What about English or French?
Can we test it was called? – no…
We need an approach to handling these
           dependencies.
      We need looser coupling.
Dependency Injection



So what is Dependency Injection?
Dependency Injection
Dependency Injection
“A design pattern whose purpose is to improve the
testability of, and simplify deployment of components”

Essentially something that takes care of creating and
linking our objects

Involves 3 parts
• Our 2 objects; dependency and dependent
• And.. An Injector to instantiate objects at runtime
Example
Injector configures our objects at runtime,
figuring out the order of creation
                                 Injector reads the
                                 dependencies, and
                   Injector      creates and stiches
                                 them together




      Dependent               Dependency
So.. Why dependency injection?
• Why do we need better management?
  – Applications are full of objects and dependencies
     • We want automation of construction
     • We want easy management of objects
     • We don’t want hundreds of Factories
  – Hard to manage those dependencies
     • Applications become tightly coupled to one-another
     • Difficult to swap out implementations
     • Manage configuration of those dependencies
Pre-dependency injection
• How do we currently do it?
  – Hand-written construction
  – Using Factory patterns
Hand-construction
Factory
Enter Dependency Injection
• Offset the instantiation of those objects to
  something else, as well as the dependencies
  – Some behind the scenes magic
  – Read a definition of how these dependencies
    should be handled
  – Create the objects and associate their
    dependencies
• Scope (talk about later)
Injector/idioms
• Simple logic:
  – Can it create the object yet? If there is a
    dependency, go create it.. Loop etc.
• Essentially… a role to..
  – Creating the “new” object when needed
  – Managing the dependencies
     • Constructor Injection
     • Setter Injection
Injector Configuration
Plain PHP files..
Constructor Injection
• Constructor injection has dependencies in the
  constructor
  – Need to create the dependencies for the
    dependent first
  – Inject them through the constructor
Setter Injection
• Create the object first and inject the
  dependents through methods (setters)
Some stuff to be careful of…
• Circular dependencies
  – Oops. Be careful. (There are ways to handle.. Not
    yet in Symfony)

                        A


           C                         B
So how does this help?
• We are all about building modular
  applications
  – Decoupling dependencies
  – Making clear what the intent of the module is
  – Separation of concerns
  – Improve testability
Decoupling
• Reduce the specific hard-value reliance
  – Facilitate swapping out new implementations
  – Reduce that complexity
  – Hopefully reduce the risk..
Make clear what it is
• We want clear intent to our application
  – Make it easy to use and modify
  – “Program to contract”
     • Implement interfaces that clearly defines the intent of
       our code
Separation of concerns
• We want to better encourage design to
  separate the concerns in our application
  – Discreet features
• Application Logic vs Infrastructure Logic

                   Application


                  Infrastructure
Testability
• Keep it clean
  – Avoiding static calls or singletons
  – Out of container testing easy
  – Easy to test concerns individually and manually
    define dependencies and mocks
We are lazy
• It is much easier utilising a dependency
  injector to handle creating objects and handle
  those dependencies than to worry about
  implementing patterns and configuration
  yourself.
Basics… check!
• That’s the theory
  – Dependencies exist in our application
  – Dependency injection assists creating and
    managing those objects
  – Makes our life easier
• Let’s talk about Symfony and Services..
Symfony Service Architecture
• Symfony is an Event Driven application
• Also provides a dependency injector and
  service locator
The Service
Service
  – An object that performs a well defined function
    when called upon
  – Separated from other parts of the application
  – Implements an action
     • e.g. Template Renderer, Mail, etc
Configuring the Injector
Service Locator (Service Container)
• Assists by providing a way to access services
  by “key”
Finding Keys
• Might be a problem?
• Symfony makes it easy, use the CLI
Further stuff to read…
• Topics
  – Aliasing
  – Public and Private
  – Specifying parameters in your config.yml


• http://symfony.com/doc/current/book/service
  _container.html
Wrapping it up
• My experience with it has been that:
  – You are encouraged to write services that others
    can use and extend
  – Your applications are much easier to test
  – Scope is much easier to manage
  – It encourages others to implement their own
    domain logic when needed, thanking you how
    easy it is to implement their own part. ;-)
Conclusion
• Covered the concepts of dependency injection
  – The problem
  – Using dependency injection to remove (code)
• Showed how it applies in Symfony
  – Better decoupling, modularity and reuse

More Related Content

What's hot (20)

PPTX
04 managing the database
Марина Босова
 
PDF
Beam me up, scotty (PUG Roma)
Gianluca Padovani
 
PPTX
DDD loves Actor Model and Actor Model loves Elixir
Gianluca Padovani
 
PPT
Design Patterns
Anuja Arosha
 
PPTX
Dependency Inversion Principle
Shahriar Hyder
 
PDF
Design patterns difference between interview questions
Umar Ali
 
PPTX
How I Learned To Apply Design Patterns
Andy Maleh
 
PPT
Zero redeployment with JRebel
Minh Hoang
 
PPTX
IoC and Mapper in C#
Huy Hoàng Phạm
 
PDF
Refactoring to SOLID Code
Adil Mughal
 
PPT
Structural patterns
Himanshu
 
DOCX
Java Design Pattern Interview Questions
jbashask
 
PDF
iOS development best practices
Michal Juhas
 
PPTX
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
PPTX
Refactoring Applications using SOLID Principles
Steven Smith
 
PPTX
Do we need SOLID principles during software development?
Anna Shymchenko
 
PPTX
Js tips & tricks
Asia Tyshchenko
 
PDF
Lecture 5 Software Engineering and Design Design Patterns
op205
 
PDF
Alex Theedom Java ee revisits design patterns
Аліна Шепшелей
 
04 managing the database
Марина Босова
 
Beam me up, scotty (PUG Roma)
Gianluca Padovani
 
DDD loves Actor Model and Actor Model loves Elixir
Gianluca Padovani
 
Design Patterns
Anuja Arosha
 
Dependency Inversion Principle
Shahriar Hyder
 
Design patterns difference between interview questions
Umar Ali
 
How I Learned To Apply Design Patterns
Andy Maleh
 
Zero redeployment with JRebel
Minh Hoang
 
IoC and Mapper in C#
Huy Hoàng Phạm
 
Refactoring to SOLID Code
Adil Mughal
 
Structural patterns
Himanshu
 
Java Design Pattern Interview Questions
jbashask
 
iOS development best practices
Michal Juhas
 
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
Refactoring Applications using SOLID Principles
Steven Smith
 
Do we need SOLID principles during software development?
Anna Shymchenko
 
Js tips & tricks
Asia Tyshchenko
 
Lecture 5 Software Engineering and Design Design Patterns
op205
 
Alex Theedom Java ee revisits design patterns
Аліна Шепшелей
 

Viewers also liked (6)

PDF
A Glymse of Symfony 2
shaduli
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
PDF
Dependency Injection
Fabien Potencier
 
PPTX
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Max Romanovsky
 
PPTX
Dependency injection - the right way
Thibaud Desodt
 
PDF
AngularJS Security: defend your Single Page Application
Carlo Bonamico
 
A Glymse of Symfony 2
shaduli
 
Introduction to Spring's Dependency Injection
Richard Paul
 
Dependency Injection
Fabien Potencier
 
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Max Romanovsky
 
Dependency injection - the right way
Thibaud Desodt
 
AngularJS Security: defend your Single Page Application
Carlo Bonamico
 
Ad

Similar to Dependency injection with Symfony 2 (20)

PDF
Dependency injection Drupal Camp Wrocław 2014
Greg Szczotka
 
PDF
DIC To The Limit – deSymfonyDay, Barcelona 2014
Ronny López
 
PDF
Dependency Injection in Drupal 8
katbailey
 
PPTX
I gotta dependency on dependency injection
mhenroid
 
PPTX
The Dependency Injection - Sorin Damian, Software Developer@RomSoft
RomSoft SRL
 
ODP
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
KEY
Zend Di in ZF 2.0
Ralph Schindler
 
ODP
Dependency injection explained (Zbigniew Lukasiak)
Ontico
 
PPTX
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Theo Jungeblut
 
PDF
What is Dependency Injection
Shawn Stratton
 
PDF
Introduction to DI(C)
Radek Benkel
 
PPTX
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Theo Jungeblut
 
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
Theo Jungeblut
 
PDF
Dependency Inversion and Dependency Injection in PHP
mtoppa
 
PPTX
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Theo Jungeblut
 
PDF
Aspect-Oriented Programming and Depedency Injection
Robert Lemke
 
PDF
Real World Dependency Injection - phpday
Stephan Hochdörfer
 
PDF
Real World Dependency Injection - oscon13
Stephan Hochdörfer
 
PPT
Dependency injection with PHP
AiTi Education
 
ODP
Learning Symfony2 by practice
Vytautas Beliunas
 
Dependency injection Drupal Camp Wrocław 2014
Greg Szczotka
 
DIC To The Limit – deSymfonyDay, Barcelona 2014
Ronny López
 
Dependency Injection in Drupal 8
katbailey
 
I gotta dependency on dependency injection
mhenroid
 
The Dependency Injection - Sorin Damian, Software Developer@RomSoft
RomSoft SRL
 
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
Zend Di in ZF 2.0
Ralph Schindler
 
Dependency injection explained (Zbigniew Lukasiak)
Ontico
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Theo Jungeblut
 
What is Dependency Injection
Shawn Stratton
 
Introduction to DI(C)
Radek Benkel
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Theo Jungeblut
 
Clean Code Part II - Dependency Injection at SoCal Code Camp
Theo Jungeblut
 
Dependency Inversion and Dependency Injection in PHP
mtoppa
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Theo Jungeblut
 
Aspect-Oriented Programming and Depedency Injection
Robert Lemke
 
Real World Dependency Injection - phpday
Stephan Hochdörfer
 
Real World Dependency Injection - oscon13
Stephan Hochdörfer
 
Dependency injection with PHP
AiTi Education
 
Learning Symfony2 by practice
Vytautas Beliunas
 
Ad

Recently uploaded (20)

PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 

Dependency injection with Symfony 2

  • 2. Introduction Cameron Manderson Developer, Director of Flint, Melbourne Symfony2 Organiser [email protected] Follow: @cammanderson www.linkedin.com/in/cameronmanderson
  • 3. Topic Highlight • More in-depth look at the background of “Dependency Injection” • Aiming to uncover in Symfony – Modularity in our implementation – Loose decoupling of dependencies – Managing scope and access to dependencies
  • 5. Some terminology • Dependency – Something that is required by another object to fulfill its function • Dependent – A client object that needs a dependency in order to perform its function
  • 6. Shown easiest like this.. Dependent Dependency Like… Emailer Spell Checker
  • 9. What about English or French?
  • 10. Can we test it was called? – no…
  • 11. We need an approach to handling these dependencies. We need looser coupling.
  • 12. Dependency Injection So what is Dependency Injection?
  • 13. Dependency Injection Dependency Injection “A design pattern whose purpose is to improve the testability of, and simplify deployment of components” Essentially something that takes care of creating and linking our objects Involves 3 parts • Our 2 objects; dependency and dependent • And.. An Injector to instantiate objects at runtime
  • 14. Example Injector configures our objects at runtime, figuring out the order of creation Injector reads the dependencies, and Injector creates and stiches them together Dependent Dependency
  • 15. So.. Why dependency injection? • Why do we need better management? – Applications are full of objects and dependencies • We want automation of construction • We want easy management of objects • We don’t want hundreds of Factories – Hard to manage those dependencies • Applications become tightly coupled to one-another • Difficult to swap out implementations • Manage configuration of those dependencies
  • 16. Pre-dependency injection • How do we currently do it? – Hand-written construction – Using Factory patterns
  • 19. Enter Dependency Injection • Offset the instantiation of those objects to something else, as well as the dependencies – Some behind the scenes magic – Read a definition of how these dependencies should be handled – Create the objects and associate their dependencies • Scope (talk about later)
  • 20. Injector/idioms • Simple logic: – Can it create the object yet? If there is a dependency, go create it.. Loop etc. • Essentially… a role to.. – Creating the “new” object when needed – Managing the dependencies • Constructor Injection • Setter Injection
  • 23. Constructor Injection • Constructor injection has dependencies in the constructor – Need to create the dependencies for the dependent first – Inject them through the constructor
  • 24. Setter Injection • Create the object first and inject the dependents through methods (setters)
  • 25. Some stuff to be careful of… • Circular dependencies – Oops. Be careful. (There are ways to handle.. Not yet in Symfony) A C B
  • 26. So how does this help? • We are all about building modular applications – Decoupling dependencies – Making clear what the intent of the module is – Separation of concerns – Improve testability
  • 27. Decoupling • Reduce the specific hard-value reliance – Facilitate swapping out new implementations – Reduce that complexity – Hopefully reduce the risk..
  • 28. Make clear what it is • We want clear intent to our application – Make it easy to use and modify – “Program to contract” • Implement interfaces that clearly defines the intent of our code
  • 29. Separation of concerns • We want to better encourage design to separate the concerns in our application – Discreet features • Application Logic vs Infrastructure Logic Application Infrastructure
  • 30. Testability • Keep it clean – Avoiding static calls or singletons – Out of container testing easy – Easy to test concerns individually and manually define dependencies and mocks
  • 31. We are lazy • It is much easier utilising a dependency injector to handle creating objects and handle those dependencies than to worry about implementing patterns and configuration yourself.
  • 32. Basics… check! • That’s the theory – Dependencies exist in our application – Dependency injection assists creating and managing those objects – Makes our life easier • Let’s talk about Symfony and Services..
  • 33. Symfony Service Architecture • Symfony is an Event Driven application • Also provides a dependency injector and service locator
  • 34. The Service Service – An object that performs a well defined function when called upon – Separated from other parts of the application – Implements an action • e.g. Template Renderer, Mail, etc
  • 36. Service Locator (Service Container) • Assists by providing a way to access services by “key”
  • 37. Finding Keys • Might be a problem? • Symfony makes it easy, use the CLI
  • 38. Further stuff to read… • Topics – Aliasing – Public and Private – Specifying parameters in your config.yml • http://symfony.com/doc/current/book/service _container.html
  • 39. Wrapping it up • My experience with it has been that: – You are encouraged to write services that others can use and extend – Your applications are much easier to test – Scope is much easier to manage – It encourages others to implement their own domain logic when needed, thanking you how easy it is to implement their own part. ;-)
  • 40. Conclusion • Covered the concepts of dependency injection – The problem – Using dependency injection to remove (code) • Showed how it applies in Symfony – Better decoupling, modularity and reuse