SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
Nashville symfony Group




Dependency Injection: Make your
      enemies fear you
            April 6th, 2010


            Ryan Weaver
           @weaverryan
         www.sympalphp.org
          www.iostudio.com
Nashville symfony Group April 2010


What is Dependency Injection (DI)?
 ●   First, let's show examples of what DI is NOT
 ●   Rewind 5 years – hopefully :) - to this code:
Nashville symfony Group April 2010




Where the heck did $renderAbsolute come from?
Pray to God that it's defined...
And that it's set to a meaningful value
Nashville symfony Group April 2010


Better, but still not Dependency Injection




But, who's in control?
  The image_tag() function grabs a value it needs from
  the global scope. It's not wrong, but not quite DI.
Nashville symfony Group April 2010


Take Control of your code (simple DI)




●   You are the authoritarian leader of your app
●   The method depends on you for everything
Nashville symfony Group April 2010


It's all about Control
●   When using globals or statics, the method
    depends on the global environment
●   Dependency injection simply means that you
    pass to your method EVERYTHING it needs,
    and don't allow it to fetch variables globally
Nashville symfony Group April 2010




The greater the control you exhibit over the
input to your methods, the more independent,
and decoupled your objects become.
Nashville symfony Group April 2010


Services Container
●   A “service container” is the iron fist behind a
    tightly controlled group of objects
●   A service container is a special class that helps
    you instantiate your services (objects) and pass
    in the correct dependencies.
●   Instead of constructing objects, it does it for you
Nashville symfony Group April 2010


Symfony's Dependency Injection Component
(also known as the “service container” component)

●Allows you to define all of your services in YAML,
XML or PHP
●   For each service (object), you define
      ● Class name

      ● Arguments to pass to the constructor



●The service container then constructs each object for
you when you ask for it
●   Used by Sympal CMF to manager all core objects
Nashville symfony Group April 2010


                                     Service Container
    You        $sc->response          ●   Event Dispatcher
                                      ●   Request
                                      ●   Response
Response object is created. The       ●   Routing
SC passes all dependent objects       ●   I18N
to its constructor
                                      ●   View Cache
             sfWebResponse            ●   …
                                      ●   Theme Manager
    You                               ●   Stats Tracker
Nashville symfony Group April 2010

 ●The SC looks to see if the response                Service Container
 object has already been instantiated                  ●   Event Dispatcher
 ●The SC instantiates the response                     ●   Request
 object if necessary. It knows the                     ●   Response
 arguments of the constructor, and                     ●   Routing
 passes it everything it needs
                                                       ●   I18N
                                                       ●   …

Class sfWebResponse
{
...
public function __construct(sfEventDispatcher $dispatcher, $options = array())
Nashville symfony Group April 2010
Nashville symfony Group April 2010


Example: A gallery plugin
●   Create a service container that houses all of
    symfony's core classes (factories)
●   Create a service that renders galleries
●   Allow the end user to override the gallery service
    class to make customizations
Nashville symfony Group April 2010
Nashville symfony Group April 2010


The “old” setup (without a service container)
Setup configuration
for the class and
options


Instantiate the renderer using these options
Nashville symfony Group April 2010


Use a service container instead
●   Define your services and their dependencies
●   This can be done in yaml, xml or php
Nashville symfony Group April 2010




●   The service container creates the gallery_renderer
service for you
●   No service is ever created until it is asked for
●   This is one of the keys behind Symfony 2's speed
Nashville symfony Group April 2010


Creating the Service Container
●   In Symfony 2, the core classes (called factories in
symfony 1) will all be loaded through a service
container.


●   Defining a new service (e.g. in YAML) is enough to
make it available in the main service container
Nashville symfony Group April 2010


Creating the Service Container
●   In symfony 1, we'll need to setup a service container
if we want to use one.


●   To make it worth a damn, we'll add symfony's core
factories to the service container so that any new
services can access them
Nashville symfony Group April 2010




                              1
                              2
                              3

                              4
Nashville symfony Group April 2010


1. Register the autoloader
2. Instantiate the service container
3. Load the services from YAML
4. Add the symfony factories to the container


The service container has everything it needs to
instantiate our “gallery_renderer” service

      $renderer = $sc->gallery_renderer
Nashville symfony Group April 2010


Define more and more services...
Nashville symfony Group April 2010


Real-World Examples
The dependency injection container for symfony
1 IS used on some well-known projects
●   Sympal CMF
      http://www.sympalphp.org
      http://github.com/sympal/sympal/blob/master/lib/util/sf
      SympalContext.php#L117

●   Diem
      http://diem-project.org/
      http://github.com/diem-
      project/diem/blob/master/dmCorePlugin/lib/context/dm
      Context.php#L121
Nashville symfony Group April 2010


Questions? Idea Bubbles?


                   Ryan Weaver
                  @weaverryan
                www.sympalphp.org
                 www.iostudio.com

Mais conteúdo relacionado

Mais procurados

Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
yoavwix
 
Ruby tutorial
Ruby tutorialRuby tutorial
Ruby tutorial
knoppix
 

Mais procurados (14)

DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014
 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part one
 
TMAPI 2.0 tutorial
TMAPI 2.0 tutorialTMAPI 2.0 tutorial
TMAPI 2.0 tutorial
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projects
 
Java byte code & virtual machine
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machine
 
C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...
 
Enriching EMF Models with Scala (quick overview)
Enriching EMF Models with Scala (quick overview)Enriching EMF Models with Scala (quick overview)
Enriching EMF Models with Scala (quick overview)
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Python Crash Course
Python Crash CoursePython Crash Course
Python Crash Course
 
Ruby tutorial
Ruby tutorialRuby tutorial
Ruby tutorial
 

Semelhante a Dependency Injection: Make your enemies fear you

Learning Symfony2 by practice
Learning Symfony2 by practiceLearning Symfony2 by practice
Learning Symfony2 by practice
Vytautas Beliunas
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
Fabien Potencier
 
Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009
Fabien Potencier
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?
Oliver Gierke
 
BP214 IBM Lotus Symphony : Finally, A Developer's Friend
BP214 IBM Lotus Symphony : Finally, A Developer's FriendBP214 IBM Lotus Symphony : Finally, A Developer's Friend
BP214 IBM Lotus Symphony : Finally, A Developer's Friend
John Head
 

Semelhante a Dependency Injection: Make your enemies fear you (20)

Learning Symfony2 by practice
Learning Symfony2 by practiceLearning Symfony2 by practice
Learning Symfony2 by practice
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
 
Modularity problems
Modularity  problemsModularity  problems
Modularity problems
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards
 
Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009
 
How Symfony Changed My Life
How Symfony Changed My LifeHow Symfony Changed My Life
How Symfony Changed My Life
 
The Art of Doctrine Migrations
The Art of Doctrine MigrationsThe Art of Doctrine Migrations
The Art of Doctrine Migrations
 
How Symfony changed my life (#SfPot, Paris, 19th November 2015)
How Symfony changed my life (#SfPot, Paris, 19th November 2015)How Symfony changed my life (#SfPot, Paris, 19th November 2015)
How Symfony changed my life (#SfPot, Paris, 19th November 2015)
 
Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...
Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...
Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...
 
Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?
 
BP214 IBM Lotus Symphony : Finally, A Developer's Friend
BP214 IBM Lotus Symphony : Finally, A Developer's FriendBP214 IBM Lotus Symphony : Finally, A Developer's Friend
BP214 IBM Lotus Symphony : Finally, A Developer's Friend
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Symfony4: A new way to develop applications | Antonio Peric | CODEiD
Symfony4: A new way to develop applications | Antonio Peric | CODEiDSymfony4: A new way to develop applications | Antonio Peric | CODEiD
Symfony4: A new way to develop applications | Antonio Peric | CODEiD
 
Symfony2 components to the rescue of your PHP projects
Symfony2 components to the rescue of your PHP projectsSymfony2 components to the rescue of your PHP projects
Symfony2 components to the rescue of your PHP projects
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
Symfony4 - A new way of developing web applications
Symfony4 - A new way of developing web applicationsSymfony4 - A new way of developing web applications
Symfony4 - A new way of developing web applications
 
Strategy to setup Subversion for Salesforce development for Agile Team
Strategy to setup Subversion for Salesforce development for Agile TeamStrategy to setup Subversion for Salesforce development for Agile Team
Strategy to setup Subversion for Salesforce development for Agile Team
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
 

Mais de Ryan Weaver

Symfony2: Get your project started
Symfony2: Get your project startedSymfony2: Get your project started
Symfony2: Get your project started
Ryan Weaver
 
Doctrine2 In 10 Minutes
Doctrine2 In 10 MinutesDoctrine2 In 10 Minutes
Doctrine2 In 10 Minutes
Ryan Weaver
 

Mais de Ryan Weaver (18)

Webpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San FranciscoWebpack Encore Symfony Live 2017 San Francisco
Webpack Encore Symfony Live 2017 San Francisco
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
 
Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)Symfony: Your Next Microframework (SymfonyCon 2015)
Symfony: Your Next Microframework (SymfonyCon 2015)
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with BehatGrand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
 
Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!
 
Master the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and SilexMaster the New Core of Drupal 8 Now: with Symfony and Silex
Master the New Core of Drupal 8 Now: with Symfony and Silex
 
Silex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender SymfonySilex: Microframework y camino fácil de aprender Symfony
Silex: Microframework y camino fácil de aprender Symfony
 
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love itDrupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
Drupal 8: Huge wins, a Bigger Community, and why you (and I) will Love it
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony Components
 
A PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 appA PHP Christmas Miracle - 3 Frameworks, 1 app
A PHP Christmas Miracle - 3 Frameworks, 1 app
 
Symfony2: Get your project started
Symfony2: Get your project startedSymfony2: Get your project started
Symfony2: Get your project started
 
Hands-on with the Symfony2 Framework
Hands-on with the Symfony2 FrameworkHands-on with the Symfony2 Framework
Hands-on with the Symfony2 Framework
 
Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with Twig
 
Doctrine2 In 10 Minutes
Doctrine2 In 10 MinutesDoctrine2 In 10 Minutes
Doctrine2 In 10 Minutes
 

Dependency Injection: Make your enemies fear you

  • 1. Nashville symfony Group Dependency Injection: Make your enemies fear you April 6th, 2010 Ryan Weaver @weaverryan www.sympalphp.org www.iostudio.com
  • 2. Nashville symfony Group April 2010 What is Dependency Injection (DI)? ● First, let's show examples of what DI is NOT ● Rewind 5 years – hopefully :) - to this code:
  • 3. Nashville symfony Group April 2010 Where the heck did $renderAbsolute come from? Pray to God that it's defined... And that it's set to a meaningful value
  • 4. Nashville symfony Group April 2010 Better, but still not Dependency Injection But, who's in control? The image_tag() function grabs a value it needs from the global scope. It's not wrong, but not quite DI.
  • 5. Nashville symfony Group April 2010 Take Control of your code (simple DI) ● You are the authoritarian leader of your app ● The method depends on you for everything
  • 6. Nashville symfony Group April 2010 It's all about Control ● When using globals or statics, the method depends on the global environment ● Dependency injection simply means that you pass to your method EVERYTHING it needs, and don't allow it to fetch variables globally
  • 7. Nashville symfony Group April 2010 The greater the control you exhibit over the input to your methods, the more independent, and decoupled your objects become.
  • 8. Nashville symfony Group April 2010 Services Container ● A “service container” is the iron fist behind a tightly controlled group of objects ● A service container is a special class that helps you instantiate your services (objects) and pass in the correct dependencies. ● Instead of constructing objects, it does it for you
  • 9. Nashville symfony Group April 2010 Symfony's Dependency Injection Component (also known as the “service container” component) ●Allows you to define all of your services in YAML, XML or PHP ● For each service (object), you define ● Class name ● Arguments to pass to the constructor ●The service container then constructs each object for you when you ask for it ● Used by Sympal CMF to manager all core objects
  • 10. Nashville symfony Group April 2010 Service Container You $sc->response ● Event Dispatcher ● Request ● Response Response object is created. The ● Routing SC passes all dependent objects ● I18N to its constructor ● View Cache sfWebResponse ● … ● Theme Manager You ● Stats Tracker
  • 11. Nashville symfony Group April 2010 ●The SC looks to see if the response Service Container object has already been instantiated ● Event Dispatcher ●The SC instantiates the response ● Request object if necessary. It knows the ● Response arguments of the constructor, and ● Routing passes it everything it needs ● I18N ● … Class sfWebResponse { ... public function __construct(sfEventDispatcher $dispatcher, $options = array())
  • 13. Nashville symfony Group April 2010 Example: A gallery plugin ● Create a service container that houses all of symfony's core classes (factories) ● Create a service that renders galleries ● Allow the end user to override the gallery service class to make customizations
  • 15. Nashville symfony Group April 2010 The “old” setup (without a service container) Setup configuration for the class and options Instantiate the renderer using these options
  • 16. Nashville symfony Group April 2010 Use a service container instead ● Define your services and their dependencies ● This can be done in yaml, xml or php
  • 17. Nashville symfony Group April 2010 ● The service container creates the gallery_renderer service for you ● No service is ever created until it is asked for ● This is one of the keys behind Symfony 2's speed
  • 18. Nashville symfony Group April 2010 Creating the Service Container ● In Symfony 2, the core classes (called factories in symfony 1) will all be loaded through a service container. ● Defining a new service (e.g. in YAML) is enough to make it available in the main service container
  • 19. Nashville symfony Group April 2010 Creating the Service Container ● In symfony 1, we'll need to setup a service container if we want to use one. ● To make it worth a damn, we'll add symfony's core factories to the service container so that any new services can access them
  • 20. Nashville symfony Group April 2010 1 2 3 4
  • 21. Nashville symfony Group April 2010 1. Register the autoloader 2. Instantiate the service container 3. Load the services from YAML 4. Add the symfony factories to the container The service container has everything it needs to instantiate our “gallery_renderer” service $renderer = $sc->gallery_renderer
  • 22. Nashville symfony Group April 2010 Define more and more services...
  • 23. Nashville symfony Group April 2010 Real-World Examples The dependency injection container for symfony 1 IS used on some well-known projects ● Sympal CMF http://www.sympalphp.org http://github.com/sympal/sympal/blob/master/lib/util/sf SympalContext.php#L117 ● Diem http://diem-project.org/ http://github.com/diem- project/diem/blob/master/dmCorePlugin/lib/context/dm Context.php#L121
  • 24. Nashville symfony Group April 2010 Questions? Idea Bubbles? Ryan Weaver @weaverryan www.sympalphp.org www.iostudio.com