SlideShare una empresa de Scribd logo
1 de 40
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

Más contenido relacionado

La actualidad más candente

Beam me up, scotty (PUG Roma)
Beam me up, scotty (PUG Roma)Beam me up, scotty (PUG Roma)
Beam me up, scotty (PUG Roma)Gianluca Padovani
 
DDD loves Actor Model and Actor Model loves Elixir
DDD loves Actor Model and Actor Model loves ElixirDDD loves Actor Model and Actor Model loves Elixir
DDD loves Actor Model and Actor Model loves ElixirGianluca Padovani
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsAndy Maleh
 
Zero redeployment with JRebel
Zero redeployment with JRebelZero redeployment with JRebel
Zero redeployment with JRebelMinh Hoang
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID CodeAdil Mughal
 
Structural patterns
Structural patternsStructural patterns
Structural patternsHimanshu
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questionsjbashask
 
iOS development best practices
iOS development best practicesiOS development best practices
iOS development best practicesMichal Juhas
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural PatternsSameh Deabes
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Anna Shymchenko
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patternsop205
 

La actualidad más candente (20)

04 managing the database
04   managing the database04   managing the database
04 managing the database
 
Beam me up, scotty (PUG Roma)
Beam me up, scotty (PUG Roma)Beam me up, scotty (PUG Roma)
Beam me up, scotty (PUG Roma)
 
DDD loves Actor Model and Actor Model loves Elixir
DDD loves Actor Model and Actor Model loves ElixirDDD loves Actor Model and Actor Model loves Elixir
DDD loves Actor Model and Actor Model loves Elixir
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design Patterns
 
Zero redeployment with JRebel
Zero redeployment with JRebelZero redeployment with JRebel
Zero redeployment with JRebel
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
 
Structural patterns
Structural patternsStructural patterns
Structural patterns
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questions
 
iOS development best practices
iOS development best practicesiOS development best practices
iOS development best practices
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
 
What is design pattern
What is design patternWhat is design pattern
What is design pattern
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
 
Js tips & tricks
Js tips & tricksJs tips & tricks
Js tips & tricks
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patterns
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 

Destacado

A Glymse of Symfony 2
A Glymse of Symfony 2A Glymse of Symfony 2
A Glymse of Symfony 2shaduli
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Max Romanovsky
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application Carlo Bonamico
 

Destacado (6)

A Glymse of Symfony 2
A Glymse of Symfony 2A Glymse of Symfony 2
A Glymse of Symfony 2
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application
 

Similar a Dependency injection with Symfony 2

Magento Developer Talk. Microservice Architecture and Actor Model
Magento Developer Talk. Microservice Architecture and Actor ModelMagento Developer Talk. Microservice Architecture and Actor Model
Magento Developer Talk. Microservice Architecture and Actor ModelIgor Miniailo
 
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...CocoaHeads Tricity
 
From Monoliths to Services: Grafually paying your Technical Debt
From Monoliths to Services: Grafually paying your Technical DebtFrom Monoliths to Services: Grafually paying your Technical Debt
From Monoliths to Services: Grafually paying your Technical DebtDavid Litvak Bruno
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of AngularKnoldus Inc.
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleP Heinonen
 
Weekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design PatternWeekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design PatternNguyen Trung Kien
 
SOA with Zend Framework
SOA with Zend FrameworkSOA with Zend Framework
SOA with Zend FrameworkMike Willbanks
 
Dependency injection explained (Zbigniew Lukasiak)
Dependency injection explained (Zbigniew Lukasiak) Dependency injection explained (Zbigniew Lukasiak)
Dependency injection explained (Zbigniew Lukasiak) Ontico
 
How to Build Composite Applications with PRISM
How to Build Composite Applications with PRISMHow to Build Composite Applications with PRISM
How to Build Composite Applications with PRISMDataLeader.io
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminarGal Marder
 
Component based development | what, why and how
Component based development | what, why and howComponent based development | what, why and how
Component based development | what, why and howRakesh Kumar Jha
 
Onion Architecture / Clean Architecture
Onion Architecture / Clean ArchitectureOnion Architecture / Clean Architecture
Onion Architecture / Clean ArchitectureAttila Bertók
 
Microservice Architecture Patterns, by Richard Langlois P. Eng.
Microservice Architecture Patterns, by Richard Langlois P. Eng.Microservice Architecture Patterns, by Richard Langlois P. Eng.
Microservice Architecture Patterns, by Richard Langlois P. Eng.Richard Langlois P. Eng.
 
Microservice Architecture
Microservice ArchitectureMicroservice Architecture
Microservice ArchitectureEngin Yoeyen
 
The "Why", "What" and "How" of Microservices
The "Why", "What" and "How" of Microservices The "Why", "What" and "How" of Microservices
The "Why", "What" and "How" of Microservices INPAY
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionKnoldus Inc.
 

Similar a Dependency injection with Symfony 2 (20)

Magento Developer Talk. Microservice Architecture and Actor Model
Magento Developer Talk. Microservice Architecture and Actor ModelMagento Developer Talk. Microservice Architecture and Actor Model
Magento Developer Talk. Microservice Architecture and Actor Model
 
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
 
From Monoliths to Services: Grafually paying your Technical Debt
From Monoliths to Services: Grafually paying your Technical DebtFrom Monoliths to Services: Grafually paying your Technical Debt
From Monoliths to Services: Grafually paying your Technical Debt
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of Angular
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Weekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design PatternWeekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design Pattern
 
SOA with Zend Framework
SOA with Zend FrameworkSOA with Zend Framework
SOA with Zend Framework
 
Dependency injection explained (Zbigniew Lukasiak)
Dependency injection explained (Zbigniew Lukasiak) Dependency injection explained (Zbigniew Lukasiak)
Dependency injection explained (Zbigniew Lukasiak)
 
How to Build Composite Applications with PRISM
How to Build Composite Applications with PRISMHow to Build Composite Applications with PRISM
How to Build Composite Applications with PRISM
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminar
 
Component based development | what, why and how
Component based development | what, why and howComponent based development | what, why and how
Component based development | what, why and how
 
Onion Architecture / Clean Architecture
Onion Architecture / Clean ArchitectureOnion Architecture / Clean Architecture
Onion Architecture / Clean Architecture
 
Microservice Architecture Patterns, by Richard Langlois P. Eng.
Microservice Architecture Patterns, by Richard Langlois P. Eng.Microservice Architecture Patterns, by Richard Langlois P. Eng.
Microservice Architecture Patterns, by Richard Langlois P. Eng.
 
Microservice Architecture
Microservice ArchitectureMicroservice Architecture
Microservice Architecture
 
The "Why", "What" and "How" of Microservices
The "Why", "What" and "How" of Microservices The "Why", "What" and "How" of Microservices
The "Why", "What" and "How" of Microservices
 
Grails Services
Grails ServicesGrails Services
Grails Services
 
Think Big - Build Small
Think Big - Build SmallThink Big - Build Small
Think Big - Build Small
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test Automaion
 
Orchestration, the conductor's score
Orchestration, the conductor's scoreOrchestration, the conductor's score
Orchestration, the conductor's score
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
[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
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[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
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Dependency injection with Symfony 2

  • 2. Introduction Cameron Manderson Developer, Director of Flint, Melbourne Symfony2 Organiser cameronmanderson@gmail.com 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