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.

Tobias Gies

May 03, 2012
Tweet

More Decks by Tobias Gies

Other Decks in Programming

Transcript

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

    new Dependency2(); $this->dep3 = new Dependency3(); }
  2. 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 ); } }
  3. class DoctrineEntityManagerBuilder { private static $instance; public function build() {

    if (empty(static::$instance)) { // ... static::$instance = EntityManager::create( $connOpts, $config ); } return static::$instance; } }
  4. class DataImporter { private $em; Private $sourceUrl; public function __construct(

    EntityManager $em, $sourceUrl) { $this->em = $em; $this->sourceUrl = $sourceUrl; } public function import() { // ... } }
  5. <?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>
  6. 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"; } }
  7. class MyController extends Controller { public function importAction() { $importer

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