Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency Injection

Dependency Injection

A talk about dependency injection and the Symfony2 DI Container given at PHPUG Cologne / Bonn in September 2011.

503778aa6a31b4ecb5b37ffb62ff5dab?s=128

Tobias Gies

May 03, 2012
Tweet

Transcript

  1. Dependency Injection

  2. Konzept

  3. Statt dem hier:

  4. public function __construct() { $this->dep1 = new Dependency1(); $this->dep2 =

    new Dependency2(); $this->dep3 = new Dependency3(); }
  5. … nimmt man das da:

  6. public function __construct( DependencyInterface1 $dep1, DependencyInterface2 $dep2, DependencyInterface3 $dep3) {

    $this->dep1 = $dep1; // ... }
  7. Das ist alles.

  8. Warum?

  9. Separation of concerns

  10. Testbarkeit

  11. Übersichtlichkeit

  12. Praxis

  13. Wer braucht schon ein Framework?

  14. class DoctrineEntityManagerBuilder { public static function build() { $config =

    new Configuration(); $config->setFoo("bar"); $connOpts = array( "driver" => "pdo_sqlite", "path" => "database.sqlite" ); return EntityManager::create( $connOpts, $config ); } }
  15. Wildwuchs vermeiden

  16. class DoctrineEntityManagerBuilder { private static $instance; public function build() {

    if (empty(static::$instance)) { // ... static::$instance = EntityManager::create( $connOpts, $config ); } return static::$instance; } }
  17. Symfony2 ServiceContainer

  18. Service?

  19. class DataImporter { private $em; Private $sourceUrl; public function __construct(

    EntityManager $em, $sourceUrl) { $this->em = $em; $this->sourceUrl = $sourceUrl; } public function import() { // ... } }
  20. <?xml version="1.0" encoding="utf-8" ?> <container xmlns="http://symfony.com/schema/dic/services" ...> <parameters> <parameter key="dataimporter.class">DataImporter</parameter>

    <parameter key="dataimporter.source_url" /> </parameters> <services> <service id="dataimporter" class="%dataimporter.class%"> <argument type="service" id="doctrine.orm.entity_manager" /> <argument>%dataimporter.source_url%</argument> </service> </services> </container>
  21. class MyExtension extends Extension { public function load(...) { $loader

    = new XmlFileLoader(...); $loader->load('services.xml'); // Konfiguration auslesen // und in Container einfügen } public function getAlias() { return "my_extension"; } }
  22. class MyController extends Controller { public function importAction() { $importer

    = $this->get("dataimporter"); $importer->import(); // ... } }
  23. Fragen?