SlideShare a Scribd company logo
Dependency Injection
Was, wie, warum?
Stephan Hochdörfer, bitExpert AG
Dependency Injection – Was, wie warum?
Über mich
 Stephan Hochdörfer
 Head of IT der bitExpert AG, Mannheim
 PHP`ler seit 1999
 S.Hochdoerfer@bitExpert.de
 @shochdoerfer
Dependency Injection – Was, wie warum?
DI ist nicht alles. Es geht um mehr.
Dependency Injection – Was, wie warum?
Separation of Concerns
Design by Contract
Dependency Injection – Was, wie warum?
Dependency Injection – Was, wie warum?
Dependency Injection
Dependency Injection – Was, wie warum?
Dependency Injection
"[...] zur Laufzeit die Abhängigkeiten
eines Objekts diesem von einem
anderen Objekt als Referenzen zur
Verfügung gestellt werden."
(Wikipedia)
Dependency Injection – Was, wie warum?
Was sind Dependencies?
Dependency Injection – Was, wie warum?
Sind Dependencies schlecht?
Dependency Injection – Was, wie warum?
Dependencies: Starke Kopplung
Keine Wiederverwendung!
Dependency Injection – Was, wie warum?
Keine Isolation, nicht testbar!
Dependency Injection – Was, wie warum?
Dependency Injection – Was, wie warum?
Dependency Wahnsinn!
Was ist Dependency Injection?
Dependency Injection – Was, wie warum?
Was ist Dependency Injection?
Dependency Injection – Was, wie warum?
new DeletePage(new PageManager());
Was ist Dependency Injection?
Consumer
Dependency Injection – Was, wie warum?
Was ist Dependency Injection?
Consumer Dependencies
Dependency Injection – Was, wie warum?
Was ist Dependency Injection?
Consumer Dependencies Container
Dependency Injection – Was, wie warum?
Was ist Dependency Injection?
Consumer Dependencies Container
Dependency Injection – Was, wie warum?
s
Dependency Injection – Was, wie warum?
„new“ is evil!
<?php
class DeletePage extends Mvc_Action_AAction {
private $pageManager;
public function __construct() {
$this->pageManager = new PageManager();
}
protected function execute(Mvc_Request $request) {
$this->pageManager->delete(
(int) $request->get('pageId')
);
}
}
Dependency Injection – Was, wie warum?
„new“ is evil!
Dependency Injection – Was, wie warum?
„new“ is evil!
<?php
class DeletePage extends Mvc_Action_AAction {
private $pageManager;
public function __construct(PageManager $pm) {
$this->pageManager = $pm;
}
protected function execute(Mvc_Request $request) {
$this->pageManager->delete(
(int) $request->get('pageId')
);
}
}
"High-level modules should not
depend on low-level modules.
Both should depend on abstractions."
Robert C. Martin
Dependency Injection – Was, wie warum?
Dependency Injection – Was, wie warum?
„new“ is evil!
<?php
class DeletePage extends Mvc_Action_AAction {
private $pageManager;
public function __construct(IPageManager $pm) {
$this->pageManager = $pm;
}
protected function execute(Mvc_Request $request) {
$this->pageManager->delete(
(int) $request->get('pageId')
);
}
}
Wie verwaltet man Dependencies?
Dependency Injection – Was, wie warum?
Wie verwaltet man Dependencies?
Simple Container vs. Full stacked
DI Framework
Dependency Injection – Was, wie warum?
Der Container nimmt uns die Arbeit ab!
Dependency Injection – Was, wie warum?
Wie Dependencies injizieren?
Dependency Injection – Was, wie warum?
Constructor Injection
<?php
class MySampleService implements IMySampleService {
/**
* @var ISampleDao
*/
private $sampleDao;
public function __construct(ISampleDao $sampleDao) {
$this->sampleDao = $sampleDao;
}
}
Dependency Injection – Was, wie warum?
Setter Injection
<?php
class MySampleService implements IMySampleService {
/**
* @var ISampleDao
*/
private $sampleDao;
public function setSampleDao(ISampleDao $sampleDao){
$this->sampleDao = $sampleDao;
}
}
Dependency Injection – Was, wie warum?
Interface Injection
<?php
interface IApplicationContextAware {
public function setCtx(IApplicationContext $ctx);
}
Dependency Injection – Was, wie warum?
Interface Injection
<?php
class MySampleService implements IMySampleService,
IApplicationContextAware {
/**
* @var IApplicationContext
*/
private $ctx;
public function setCtx(IApplicationContext $ctx) {
$this->ctx = $ctx;
}
}
Dependency Injection – Was, wie warum?
Property Injection
Dependency Injection – Was, wie warum?
Property Injection
Dependency Injection – Was, wie warum?
"NEIN NEIN NEIN!"
David Zülke
Wie funktioniert das „Wiring“?
Dependency Injection – Was, wie warum?
Dependency Injection – Was, wie warum?
Annotations
<?php
class MySampleService implements IMySampleService {
private $sampleDao;
/**
* @Inject
*/
public function __construct(ISampleDao $sampleDao)
{
$this->sampleDao = $sampleDao;
}
}
Dependency Injection – Was, wie warum?
Annotations
<?php
class MySampleService implements IMySampleService {
private $sampleDao;
/**
* @Inject
* @Named('TheSampleDao')
*/
public function __construct(ISampleDao $sampleDao)
{
$this->sampleDao = $sampleDao;
}
}
Externe Konfiguration - XML
<?xml version="1.0" encoding="UTF-8" ?>
<beans>
<bean id="SampleDao" class="SampleDao">
<constructor-arg value="app_sample" />
<constructor-arg value="iSampleId" />
<constructor-arg value="BoSample" />
</bean>
<bean id="SampleService" class="MySampleService">
<constructor-arg ref="SampleDao" />
</bean>
</beans>
Dependency Injection – Was, wie warum?
Externe Konfiguration - YAML
services:
SampleDao:
class: SampleDao
arguments: ['app_sample', 'iSampleId', 'BoSample']
SampleService:
class: SampleService
arguments: [@SampleDao]
Dependency Injection – Was, wie warum?
Externe Konfiguration - PHP
<?php
class BeanCache extends Beanfactory_Container_PHP {
protected function createSampleDao() {
$oBean = new SampleDao('app_sample',
'iSampleId', 'BoSample');
return $oBean;
}
protected function createMySampleService() {
$oBean = new MySampleService(
$this->getBean('SampleDao')
);
return $oBean;
}
}
Dependency Injection – Was, wie warum?
Interne vs. Externe Konfiguration
Dependency Injection – Was, wie warum?
Interne vs. Externe Konfiguration
Dependency Injection – Was, wie warum?
Klassenkonfiguration
vs.
Instanzkonfiguration
Dependency Injection – Was, wie warum?
Was bringt mir das? Beispiel bitte.
Unittesting einfach gemacht
Dependency Injection – Was, wie warum?
Unittesting einfach gemacht
<?php
require_once 'PHPUnit/Framework.php';
class ServiceTest extends PHPUnit_Framework_TestCase {
public function testSampleService() {
// set up dependencies
$sampleDao = $this->getMock('ISampleDao');
$service = new MySampleService($sampleDao);
// run test case
$return = $service->doWork();
// check assertions
$this->assertTrue($return);
}
}
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
Page ExporterPage Exporter
Released / Published
Pages
Released / Published
Pages
Workingcopy
Pages
Workingcopy
Pages
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?php
abstract class PageExporter {
protected function setPageDao(IPageDao $pageDao) {
$this->pageDao = $pageDao;
}
}
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?php
abstract class PageExporter {
protected function setPageDao(IPageDao $pageDao) {
$this->pageDao = $pageDao;
}
}
Zur Erinnerung:
Der Vertrag!
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?php
class PublishedPageExporter extends PageExporter {
public function __construct() {
$this->setPageDao(new PublishedPageDao());
}
}
class WorkingCopyPageExporter extends PageExporter {
public function __construct() {
$this->setPageDao(new WorkingCopyPageDao());
}
}
Dependency Injection – Was, wie warum?
"Only deleted code is good code!"
Oliver Gierke
Eine Klasse, mehrfache Ausprägung
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?php
class PageExporter {
public function __construct(IPageDao $pageDao) {
$this->pageDao = $pageDao;
}
}
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?xml version="1.0" encoding="UTF-8" ?>
<beans>
<bean id="ExportLive" class="PageExporter">
<constructor-arg ref="PublishedPageDao" />
</bean>
<bean id="ExportWorking" class="PageExporter">
<constructor-arg ref="WorkingCopyPageDao" />
</bean>
</beans>
Dependency Injection – Was, wie warum?
Eine Klasse, mehrfache Ausprägung
<?php
// create ApplicationContext instance
$ctx = new ApplicationContext();
// retrieve live exporter
$exporter = $ctx->getBean('ExportLive');
// retrieve working copy exporter
$exporter = $ctx->getBean('ExportWorking');
Dependency Injection – Was, wie warum?
Externe Services mocken
Dependency Injection – Was, wie warum?
Externe Services mocken
BookingmanagerBookingmanager WS-
Konnektor
WS-
Konnektor WebserviceWebservice
Dependency Injection – Was, wie warum?
Externe Services mocken
BookingmanagerBookingmanager WS-
Konnektor
WS-
Konnektor WebserviceWebservice
Dependency Injection – Was, wie warum?
Zur Erinnerung:
Der Vertrag!
Externe Services mocken
BookingmanagerBookingmanager FS-
Konnektor
FS-
Konnektor FilesystemFilesystem
Dependency Injection – Was, wie warum?
Externe Services mocken
BookingmanagerBookingmanager FS-
Konnektor
FS-
Konnektor FilesystemFilesystem
erfüllt den
Vertrag!
Dependency Injection – Was, wie warum?
Sauberer, lesbarer Code
Dependency Injection – Was, wie warum?
Sauberer, lesbarer Code
<?php
class DeletePage extends Mvc_Action_AAction {
private $pageManager;
public function __construct(IPageManager $pm) {
$this->pageManager = $pm;
}
protected function execute(Mvc_Request $request) {
$this->pageManager->delete(
(int) $request->get('pageId'));
return new ModelAndView($this->getSuccessView());
}
}
Dependency Injection – Was, wie warum?
Keine Framework Abhängigkeit
Dependency Injection – Was, wie warum?
Keine Framework Abhängigkeit
<?php
class MySampleService implements IMySampleService {
private $sampleDao;
public function __construct(ISampleDao $sampleDao) {
$this->sampleDao = $sampleDao;
}
public function getSample($sampleId) {
try {
return $this->sampleDao->readById($sampleId);
}
catch(DaoException $exception) {}
}
}
Dependency Injection – Was, wie warum?
Dependency Injection – Was, wie warum?
Wie siehst das nun in der Praxis aus?
Dependency Injection – Was, wie warum?
Pimple
Pimple – Erste Schritte
Dependency Injection – Was, wie warum?
<?php
class TalkService {
public function __construct() {
}
public function getTalks() {
}
}
Pimple – Erste Schritte
Dependency Injection – Was, wie warum?
<?php
require_once '/path/to/Pimple.php';
require_once '/path/to/TalkService.php';
// create the Container
$container = new Pimple();
// define talkService object in container
$container['talkService'] = function ($c) {
return new TalkService();
};
// instantiate talkService from container
$talkService = $container['talkService'];
Pimple – Constructor Injection
Dependency Injection – Was, wie warum?
<?php
interface GenericRepository {
public function readTalks();
}
class TalkRepository implements GenericRepository {
public function readTalks() {
}
}
class TalkService {
public function __construct(TalkRepository $repo) {
}
public function getTalks() {
}
}
Pimple – Constructor Injection
Dependency Injection – Was, wie warum?
<?php
require_once '/path/to/Pimple.php';
require_once '/path/to/TalkService.php';
// create the Container
$container = new Pimple();
// define services in container
$container['talkRepository'] = function ($c) {
return new TalkRepository();
};
$container['talkService'] = function ($c) {
return new TalkService($c['talkRepository']);
};
// instantiate talkService from container
$talkService = $container['talkService'];
Pimple – Setter Injection
Dependency Injection – Was, wie warum?
<?php
class Logger {
public function doLog($logMsg) {
}
}
class TalkService {
public function __construct(TalkRepository $repo) {
}
public function setLogger(Logger $logger) {
}
public function getTalks() {
}
}
Pimple – Setter Injection
Dependency Injection – Was, wie warum?
<?php
require_once '/path/to/Pimple.php';
require_once '/path/to/TalkService.php';
// create the Container
$container = new Pimple();
// define services in container
$container['logger'] = function ($c) {
return new Logger();
};
$container['talkRepository'] = function ($c) {
return new TalkRepository();
};
$container['talkService'] = function ($c) {
$service = new TalkService($c['talkRepository']);
$service->setLogger($c['logger']);
return $service;
};
// instantiate talkService from container
$talkService = $container['talkService'];
Dependency Injection – Was, wie warum?
ZendDi – Erste Schritte
Dependency Injection – Was, wie warum?
<?php
namespace Acme;
class TalkService {
public function __construct() {
}
public function getTalks() {
}
}
ZendDi – Erste Schritte
Dependency Injection – Was, wie warum?
<?php
$di = new ZendDiDi();
$service = $di->get('AcmeTalkService');
$service->getTalks();
ZendDi – Constructor Injection
Dependency Injection – Was, wie warum?
<?php
namespace Acme;
interface GenericRepository {
public function readTalks();
}
class TalkRepository implements GenericRepository {
public function readTalks() {
}
}
class TalkService {
public function __construct(TalkRepository $repo) {
}
public function getTalks() {
}
}
ZendDi – Constructor Injection
Dependency Injection – Was, wie warum?
<?php
$di = new ZendDiDi();
$service = $di->get('AcmeTalkService');
$service->getTalks();
ZendDi – Setter Injection
Dependency Injection – Was, wie warum?
<?php
namespace Acme;
class Logger {
public function doLog($logMsg) {
}
}
class TalkService {
public function __construct(TalkRepository $repo) {
}
public function setLogger(Logger $logger) {
}
public function getTalks() {
}
}
ZendDi – Setter Injection
Dependency Injection – Was, wie warum?
<?php
$di = new ZendDiDi();
$di->configure(
new ZendDiConfiguration(
array(
'definition' => array(
'class' => array(
'AcmeTalkService' => array(
'setLogger' => array('required' => true)
)
)
)
)
)
);
$service = $di->get('AcmeTalkService');
var_dump($service);
ZendDi – Interface Injection
Dependency Injection – Was, wie warum?
<?php
namespace Acme;
class Logger {
public function doLog($logMsg) {
}
}
interface LoggerAware {
public function setLogger(Logger $logger);
}
class TalkService implements LoggerAware {
public function __construct(TalkRepository $repo) {
}
public function setLogger(Logger $logger) {
}
public function getTalks() {
}
}
ZendDi – Interface Injection
Dependency Injection – Was, wie warum?
<?php
$di = new ZendDiDi();
$service = $di->get('AcmeTalkService');
$service->getTalks();
ZendDi – Grundsätzliches
Dependency Injection – Was, wie warum?
<?php
$di = new ZendDiDi();
$service = $di->get('AcmeTalkService');
var_dump($service);
$service2 = $di->get('AcmeTalkService');
var_dump($service2); // same instance as $service
$service3 = $di->get(
'AcmeTalkService',
array(
'repo' => new AcmeTalkRepository()
)
);
ZendDi – Builder Definition
Dependency Injection – Was, wie warum?
<?php
// describe dependency
$dep = new ZendDiDefinitionBuilderPhpClass();
$dep->setName('AcmeTalkRepository');
// describe class
$class = new ZendDiDefinitionBuilderPhpClass();
$class->setName('AcmeTalkService');
// add injection method
$im = new ZendDiDefinitionBuilderInjectionMethod();
$im->setName('__construct');
$im->addParameter('repo', 'AcmeTalkRepository');
$class->addInjectionMethod($im);
// configure builder
$builder = new ZendDiDefinitionBuilderDefinition();
$builder->addClass($dep);
$builder->addClass($class);
ZendDi – Builder Definition
Dependency Injection – Was, wie warum?
<?php
// add to Di
$defList = new ZendDiDefinitionList($builder);
$di = new ZendDiDi($defList);
$service = $di->get('AcmeTalkService');
var_dump($service);
Dependency Injection – Was, wie warum?
Symfony2
Dependency Injection – Was, wie warum?
<?php
namespace AcmeTalkBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;
class TalkController extends Controller {
/**
* @Route("/", name="_talk")
* @Template()
*/
public function indexAction() {
$service = $this->get('acme.talk.service');
return array();
}
}
Symfony2 – Konfigurationsdatei
Dependency Injection – Was, wie warum?
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
</container>
File services.xml in src/Acme/DemoBundle/Resources/config
Symfony2 – Constructor Injection
Dependency Injection – Was, wie warum?
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.talk.repo"
class="AcmeTalkBundleServiceTalkRepository" />
<service id="acme.talk.service"
class="AcmeTalkBundleServiceTalkService">
<argument type="service" id="acme.talk.repo" />
</service>
</services>
</container>
Symfony2 – Setter Injection
Dependency Injection – Was, wie warum?
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.talk.logger"
class="AcmeTalkBundleServiceLogger" />
<service id="acme.talk.repo"
class="AcmeTalkBundleServiceTalkRepository" />
<service id="acme.talk.service"
class="AcmeTalkBundleServiceTalkService">
<argument type="service" id="acme.talk.repo" />
<call method="setLogger">
<argument type="service" id="acme.talk.logger" />
</call>
</service>
</services>
</container>
Symfony2 – Setter Injection (optional)
Dependency Injection – Was, wie warum?
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.talk.logger"
class="AcmeTalkBundleServiceLogger" />
<service id="acme.talk.repo"
class="AcmeTalkBundleServiceTalkRepository" />
<service id="acme.talk.service"
class="AcmeTalkBundleServiceTalkService">
<argument type="service" id="acme.talk.repo" />
<call method="setLogger">
<argument type="service" id="acme.talk.logger"
on-invalid="ignore" />
</call>
</service>
</services>
</container>
Symfony2 – Property Injection
Dependency Injection – Was, wie warum?
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.talk.repo"
class="AcmeTalkBundleServiceTalkRepository" />
<service id="acme.talk.service"
class="AcmeTalkBundleServiceTalkService">
<property name="talkRepository" type="service"
id="acme.talk.repo" />
</service>
</services>
</container>
Dependency Injection – Was, wie warum?
Flow3 – Constructor Injection
Dependency Injection – Was, wie warum?
<?php
namespace AcmeDemoController;
use TYPO3FLOW3Annotations as FLOW3;
/**
* @FLOW3Scope("session")
*/
class StandardController extends TYPO3FLOW3MVCControllerActionController {
/**
* @var AcmeDemoServiceTalkServiceInterface
*/
protected $talkService;
public function __construct(
AcmeDemoServiceTalkService $talkService) {
$this->talkService = $talkService;
}
public function indexAction() {
}
}
Flow3 – Setter Injection (manuell)
Dependency Injection – Was, wie warum?
<?php
namespace AcmeDemoController;
use TYPO3FLOW3Annotations as FLOW3;
/**
* @FLOW3Scope("session")
*/
class StandardController extends TYPO3FLOW3MVCControllerActionController {
/**
* @var AcmeDemoServiceTalkServiceInterface
*/
protected $talkService;
public function setTalkService(
AcmeDemoServiceTalkService $talkService) {
$this->talkService = $talkService;
}
public function indexAction() {
}
}
Flow3 – Setter Injection (manuell)
Dependency Injection – Was, wie warum?
File Objects.yaml in Packages/Application/Acme.Demo/Configuration
# @package Acme
AcmeDemoControllerStandardController:
properties:
talkService:
object: AcmeDemoServiceTalkService
Flow3 – Setter Injection (automatisch)
Dependency Injection – Was, wie warum?
<?php
namespace AcmeDemoController;
use TYPO3FLOW3Annotations as FLOW3;
/**
* @FLOW3Scope("session")
*/
class StandardController extends TYPO3FLOW3MVCControllerActionController {
/**
* @var AcmeDemoServiceTalkServiceInterface
*/
protected $talkService;
public function injectTalkService(
AcmeDemoServiceTalkService $talkService) {
$this->talkService = $talkService;
}
public function indexAction() {
}
}
Dependency Injection – Was, wie warum?
Fokus aufs Wesentliche. Keine Ablenkung.
Dependency Injection – Was, wie warum?
Wiederverwendung steigern.
Dependency Injection – Was, wie warum?
Hilft den Code besser zu verstehen.
Dependency Injection – Was, wie warum?
Wieder Spaß bei der Arbeit ;)
Dependency Injection – Was, wie warum?
Kein Standard. Kein Tooling.
Dependency Injection – Was, wie warum?
Es braucht Zeit um DI zu verstehen.
Dependency Injection – Was, wie warum?
Konfiguration vs. Laufzeit
Vielen Dank!

More Related Content

PDF
Real World Dependency Injection - IPC11 Spring Edition
PDF
Real World Dependency Injection SE - phpugrhh
PDF
Real World Dependency Injection - oscon13
PDF
Real World Dependency Injection - PFCongres 2010
PDF
Testing untestable code - oscon 2012
PDF
Testing untestable Code - PFCongres 2010
PDF
Your Business. Your Language. Your Code - dpc13
PDF
Frontin like-a-backer
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection SE - phpugrhh
Real World Dependency Injection - oscon13
Real World Dependency Injection - PFCongres 2010
Testing untestable code - oscon 2012
Testing untestable Code - PFCongres 2010
Your Business. Your Language. Your Code - dpc13
Frontin like-a-backer

What's hot (19)

PDF
Curso Symfony - Clase 4
PDF
Curso Symfony - Clase 2
PDF
Zf2 how arrays will save your project
PPTX
Zend server 6 using zf2, 2013 webinar
PPS
Authentication with zend framework
PDF
Phing for power users - frOSCon8
PPTX
Making Magento flying like a rocket! (A set of valuable tips for developers)
PDF
Instant ACLs with Zend Framework 2
PDF
Quick Start to iOS Development
PDF
Boost your angular app with web workers
PDF
Introduction to Zend framework
KEY
2011 a grape odyssey
PDF
Sane Async Patterns
ZIP
YUI 3
PDF
Your code are my tests
KEY
Design Patterns for Tablets and Smartphones
PPTX
Magento Indexes
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
PPTX
Building Progressive Web Apps for Windows devices
Curso Symfony - Clase 4
Curso Symfony - Clase 2
Zf2 how arrays will save your project
Zend server 6 using zf2, 2013 webinar
Authentication with zend framework
Phing for power users - frOSCon8
Making Magento flying like a rocket! (A set of valuable tips for developers)
Instant ACLs with Zend Framework 2
Quick Start to iOS Development
Boost your angular app with web workers
Introduction to Zend framework
2011 a grape odyssey
Sane Async Patterns
YUI 3
Your code are my tests
Design Patterns for Tablets and Smartphones
Magento Indexes
Promises are so passé - Tim Perry - Codemotion Milan 2016
Building Progressive Web Apps for Windows devices
Ad

Similar to Dependency Injection in PHP - dwx13 (20)

PDF
Real World Dependency Injection - phpugffm13
PDF
Real World Dependency Injection - phpday
PDF
Real world dependency injection - DPC10
PDF
Dependency Injection in Laravel
ODP
Dependency Injection, Zend Framework and Symfony Container
PDF
Unit testing after Zend Framework 1.8
PDF
20150516 modern web_conf_tw
PDF
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
KEY
Yii Introduction
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
PDF
From 0 to Spring Security 4.0
ODP
Angular js-crash-course
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
PDF
Čtvrtkon #53 - Štěpán Zikmund
PDF
WCLA12 JavaScript
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
PDF
深入淺出 MVC
PDF
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpday
Real world dependency injection - DPC10
Dependency Injection in Laravel
Dependency Injection, Zend Framework and Symfony Container
Unit testing after Zend Framework 1.8
20150516 modern web_conf_tw
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Yii Introduction
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
From 0 to Spring Security 4.0
Angular js-crash-course
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Čtvrtkon #53 - Štěpán Zikmund
WCLA12 JavaScript
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
深入淺出 MVC
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Ad

More from Stephan Hochdörfer (20)

PDF
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
PDF
Offline strategies for HTML5 web applications - frOSCon8
PDF
Offline Strategies for HTML5 Web Applications - oscon13
PDF
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Phing for power users - dpc_uncon13
PDF
Offline Strategies for HTML5 Web Applications - ipc13
PDF
Offline-Strategien für HTML5 Web Applikationen - wmka
PDF
Offline-Strategien für HTML5 Web Applikationen - bedcon13
PDF
Testing untestable code - ConFoo13
PDF
A Phing fairy tale - ConFoo13
PDF
Offline strategies for HTML5 web applications - ConFoo13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
Testing untestable code - IPC12
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
PDF
Offline strategies for HTML5 web applications - pfCongres2012
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
PDF
Testing untestable code - Herbstcampus12
PDF
Introducing a Software Generator Framework - JAZOON12
PDF
The state of DI - DPC12
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline strategies for HTML5 web applications - frOSCon8
Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategien für HTML5 Web Applikationen - dwx13
Phing for power users - dpc_uncon13
Offline Strategies for HTML5 Web Applications - ipc13
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Testing untestable code - ConFoo13
A Phing fairy tale - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Testing untestable code - IPC12
Offline strategies for HTML5 web applications - IPC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Offline strategies for HTML5 web applications - pfCongres2012
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Testing untestable code - Herbstcampus12
Introducing a Software Generator Framework - JAZOON12
The state of DI - DPC12

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Electronic commerce courselecture one. Pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Electronic commerce courselecture one. Pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
The AUB Centre for AI in Media Proposal.docx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation_ Review paper, used for researhc scholars
MIND Revenue Release Quarter 2 2025 Press Release
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf

Dependency Injection in PHP - dwx13

  • 1. Dependency Injection Was, wie, warum? Stephan Hochdörfer, bitExpert AG
  • 2. Dependency Injection – Was, wie warum? Über mich  Stephan Hochdörfer  Head of IT der bitExpert AG, Mannheim  PHP`ler seit 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 3. Dependency Injection – Was, wie warum? DI ist nicht alles. Es geht um mehr.
  • 4. Dependency Injection – Was, wie warum? Separation of Concerns
  • 5. Design by Contract Dependency Injection – Was, wie warum?
  • 6. Dependency Injection – Was, wie warum? Dependency Injection
  • 7. Dependency Injection – Was, wie warum? Dependency Injection "[...] zur Laufzeit die Abhängigkeiten eines Objekts diesem von einem anderen Objekt als Referenzen zur Verfügung gestellt werden." (Wikipedia)
  • 8. Dependency Injection – Was, wie warum? Was sind Dependencies?
  • 9. Dependency Injection – Was, wie warum? Sind Dependencies schlecht?
  • 10. Dependency Injection – Was, wie warum? Dependencies: Starke Kopplung
  • 12. Keine Isolation, nicht testbar! Dependency Injection – Was, wie warum?
  • 13. Dependency Injection – Was, wie warum? Dependency Wahnsinn!
  • 14. Was ist Dependency Injection? Dependency Injection – Was, wie warum?
  • 15. Was ist Dependency Injection? Dependency Injection – Was, wie warum? new DeletePage(new PageManager());
  • 16. Was ist Dependency Injection? Consumer Dependency Injection – Was, wie warum?
  • 17. Was ist Dependency Injection? Consumer Dependencies Dependency Injection – Was, wie warum?
  • 18. Was ist Dependency Injection? Consumer Dependencies Container Dependency Injection – Was, wie warum?
  • 19. Was ist Dependency Injection? Consumer Dependencies Container Dependency Injection – Was, wie warum?
  • 20. s Dependency Injection – Was, wie warum? „new“ is evil!
  • 21. <?php class DeletePage extends Mvc_Action_AAction { private $pageManager; public function __construct() { $this->pageManager = new PageManager(); } protected function execute(Mvc_Request $request) { $this->pageManager->delete( (int) $request->get('pageId') ); } } Dependency Injection – Was, wie warum? „new“ is evil!
  • 22. Dependency Injection – Was, wie warum? „new“ is evil! <?php class DeletePage extends Mvc_Action_AAction { private $pageManager; public function __construct(PageManager $pm) { $this->pageManager = $pm; } protected function execute(Mvc_Request $request) { $this->pageManager->delete( (int) $request->get('pageId') ); } }
  • 23. "High-level modules should not depend on low-level modules. Both should depend on abstractions." Robert C. Martin Dependency Injection – Was, wie warum?
  • 24. Dependency Injection – Was, wie warum? „new“ is evil! <?php class DeletePage extends Mvc_Action_AAction { private $pageManager; public function __construct(IPageManager $pm) { $this->pageManager = $pm; } protected function execute(Mvc_Request $request) { $this->pageManager->delete( (int) $request->get('pageId') ); } }
  • 25. Wie verwaltet man Dependencies? Dependency Injection – Was, wie warum?
  • 26. Wie verwaltet man Dependencies? Simple Container vs. Full stacked DI Framework Dependency Injection – Was, wie warum?
  • 27. Der Container nimmt uns die Arbeit ab! Dependency Injection – Was, wie warum?
  • 28. Wie Dependencies injizieren? Dependency Injection – Was, wie warum?
  • 29. Constructor Injection <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $sampleDao; public function __construct(ISampleDao $sampleDao) { $this->sampleDao = $sampleDao; } } Dependency Injection – Was, wie warum?
  • 30. Setter Injection <?php class MySampleService implements IMySampleService { /** * @var ISampleDao */ private $sampleDao; public function setSampleDao(ISampleDao $sampleDao){ $this->sampleDao = $sampleDao; } } Dependency Injection – Was, wie warum?
  • 31. Interface Injection <?php interface IApplicationContextAware { public function setCtx(IApplicationContext $ctx); } Dependency Injection – Was, wie warum?
  • 32. Interface Injection <?php class MySampleService implements IMySampleService, IApplicationContextAware { /** * @var IApplicationContext */ private $ctx; public function setCtx(IApplicationContext $ctx) { $this->ctx = $ctx; } } Dependency Injection – Was, wie warum?
  • 34. Property Injection Dependency Injection – Was, wie warum? "NEIN NEIN NEIN!" David Zülke
  • 35. Wie funktioniert das „Wiring“? Dependency Injection – Was, wie warum?
  • 36. Dependency Injection – Was, wie warum? Annotations <?php class MySampleService implements IMySampleService { private $sampleDao; /** * @Inject */ public function __construct(ISampleDao $sampleDao) { $this->sampleDao = $sampleDao; } }
  • 37. Dependency Injection – Was, wie warum? Annotations <?php class MySampleService implements IMySampleService { private $sampleDao; /** * @Inject * @Named('TheSampleDao') */ public function __construct(ISampleDao $sampleDao) { $this->sampleDao = $sampleDao; } }
  • 38. Externe Konfiguration - XML <?xml version="1.0" encoding="UTF-8" ?> <beans> <bean id="SampleDao" class="SampleDao"> <constructor-arg value="app_sample" /> <constructor-arg value="iSampleId" /> <constructor-arg value="BoSample" /> </bean> <bean id="SampleService" class="MySampleService"> <constructor-arg ref="SampleDao" /> </bean> </beans> Dependency Injection – Was, wie warum?
  • 39. Externe Konfiguration - YAML services: SampleDao: class: SampleDao arguments: ['app_sample', 'iSampleId', 'BoSample'] SampleService: class: SampleService arguments: [@SampleDao] Dependency Injection – Was, wie warum?
  • 40. Externe Konfiguration - PHP <?php class BeanCache extends Beanfactory_Container_PHP { protected function createSampleDao() { $oBean = new SampleDao('app_sample', 'iSampleId', 'BoSample'); return $oBean; } protected function createMySampleService() { $oBean = new MySampleService( $this->getBean('SampleDao') ); return $oBean; } } Dependency Injection – Was, wie warum?
  • 41. Interne vs. Externe Konfiguration Dependency Injection – Was, wie warum?
  • 42. Interne vs. Externe Konfiguration Dependency Injection – Was, wie warum? Klassenkonfiguration vs. Instanzkonfiguration
  • 43. Dependency Injection – Was, wie warum? Was bringt mir das? Beispiel bitte.
  • 44. Unittesting einfach gemacht Dependency Injection – Was, wie warum?
  • 45. Unittesting einfach gemacht <?php require_once 'PHPUnit/Framework.php'; class ServiceTest extends PHPUnit_Framework_TestCase { public function testSampleService() { // set up dependencies $sampleDao = $this->getMock('ISampleDao'); $service = new MySampleService($sampleDao); // run test case $return = $service->doWork(); // check assertions $this->assertTrue($return); } } Dependency Injection – Was, wie warum?
  • 46. Eine Klasse, mehrfache Ausprägung Dependency Injection – Was, wie warum?
  • 47. Eine Klasse, mehrfache Ausprägung Page ExporterPage Exporter Released / Published Pages Released / Published Pages Workingcopy Pages Workingcopy Pages Dependency Injection – Was, wie warum?
  • 48. Eine Klasse, mehrfache Ausprägung <?php abstract class PageExporter { protected function setPageDao(IPageDao $pageDao) { $this->pageDao = $pageDao; } } Dependency Injection – Was, wie warum?
  • 49. Eine Klasse, mehrfache Ausprägung <?php abstract class PageExporter { protected function setPageDao(IPageDao $pageDao) { $this->pageDao = $pageDao; } } Zur Erinnerung: Der Vertrag! Dependency Injection – Was, wie warum?
  • 50. Eine Klasse, mehrfache Ausprägung <?php class PublishedPageExporter extends PageExporter { public function __construct() { $this->setPageDao(new PublishedPageDao()); } } class WorkingCopyPageExporter extends PageExporter { public function __construct() { $this->setPageDao(new WorkingCopyPageDao()); } } Dependency Injection – Was, wie warum?
  • 51. "Only deleted code is good code!" Oliver Gierke Eine Klasse, mehrfache Ausprägung Dependency Injection – Was, wie warum?
  • 52. Eine Klasse, mehrfache Ausprägung <?php class PageExporter { public function __construct(IPageDao $pageDao) { $this->pageDao = $pageDao; } } Dependency Injection – Was, wie warum?
  • 53. Eine Klasse, mehrfache Ausprägung <?xml version="1.0" encoding="UTF-8" ?> <beans> <bean id="ExportLive" class="PageExporter"> <constructor-arg ref="PublishedPageDao" /> </bean> <bean id="ExportWorking" class="PageExporter"> <constructor-arg ref="WorkingCopyPageDao" /> </bean> </beans> Dependency Injection – Was, wie warum?
  • 54. Eine Klasse, mehrfache Ausprägung <?php // create ApplicationContext instance $ctx = new ApplicationContext(); // retrieve live exporter $exporter = $ctx->getBean('ExportLive'); // retrieve working copy exporter $exporter = $ctx->getBean('ExportWorking'); Dependency Injection – Was, wie warum?
  • 55. Externe Services mocken Dependency Injection – Was, wie warum?
  • 56. Externe Services mocken BookingmanagerBookingmanager WS- Konnektor WS- Konnektor WebserviceWebservice Dependency Injection – Was, wie warum?
  • 57. Externe Services mocken BookingmanagerBookingmanager WS- Konnektor WS- Konnektor WebserviceWebservice Dependency Injection – Was, wie warum? Zur Erinnerung: Der Vertrag!
  • 58. Externe Services mocken BookingmanagerBookingmanager FS- Konnektor FS- Konnektor FilesystemFilesystem Dependency Injection – Was, wie warum?
  • 59. Externe Services mocken BookingmanagerBookingmanager FS- Konnektor FS- Konnektor FilesystemFilesystem erfüllt den Vertrag! Dependency Injection – Was, wie warum?
  • 60. Sauberer, lesbarer Code Dependency Injection – Was, wie warum?
  • 61. Sauberer, lesbarer Code <?php class DeletePage extends Mvc_Action_AAction { private $pageManager; public function __construct(IPageManager $pm) { $this->pageManager = $pm; } protected function execute(Mvc_Request $request) { $this->pageManager->delete( (int) $request->get('pageId')); return new ModelAndView($this->getSuccessView()); } } Dependency Injection – Was, wie warum?
  • 62. Keine Framework Abhängigkeit Dependency Injection – Was, wie warum?
  • 63. Keine Framework Abhängigkeit <?php class MySampleService implements IMySampleService { private $sampleDao; public function __construct(ISampleDao $sampleDao) { $this->sampleDao = $sampleDao; } public function getSample($sampleId) { try { return $this->sampleDao->readById($sampleId); } catch(DaoException $exception) {} } } Dependency Injection – Was, wie warum?
  • 64. Dependency Injection – Was, wie warum? Wie siehst das nun in der Praxis aus?
  • 65. Dependency Injection – Was, wie warum? Pimple
  • 66. Pimple – Erste Schritte Dependency Injection – Was, wie warum? <?php class TalkService { public function __construct() { } public function getTalks() { } }
  • 67. Pimple – Erste Schritte Dependency Injection – Was, wie warum? <?php require_once '/path/to/Pimple.php'; require_once '/path/to/TalkService.php'; // create the Container $container = new Pimple(); // define talkService object in container $container['talkService'] = function ($c) { return new TalkService(); }; // instantiate talkService from container $talkService = $container['talkService'];
  • 68. Pimple – Constructor Injection Dependency Injection – Was, wie warum? <?php interface GenericRepository { public function readTalks(); } class TalkRepository implements GenericRepository { public function readTalks() { } } class TalkService { public function __construct(TalkRepository $repo) { } public function getTalks() { } }
  • 69. Pimple – Constructor Injection Dependency Injection – Was, wie warum? <?php require_once '/path/to/Pimple.php'; require_once '/path/to/TalkService.php'; // create the Container $container = new Pimple(); // define services in container $container['talkRepository'] = function ($c) { return new TalkRepository(); }; $container['talkService'] = function ($c) { return new TalkService($c['talkRepository']); }; // instantiate talkService from container $talkService = $container['talkService'];
  • 70. Pimple – Setter Injection Dependency Injection – Was, wie warum? <?php class Logger { public function doLog($logMsg) { } } class TalkService { public function __construct(TalkRepository $repo) { } public function setLogger(Logger $logger) { } public function getTalks() { } }
  • 71. Pimple – Setter Injection Dependency Injection – Was, wie warum? <?php require_once '/path/to/Pimple.php'; require_once '/path/to/TalkService.php'; // create the Container $container = new Pimple(); // define services in container $container['logger'] = function ($c) { return new Logger(); }; $container['talkRepository'] = function ($c) { return new TalkRepository(); }; $container['talkService'] = function ($c) { $service = new TalkService($c['talkRepository']); $service->setLogger($c['logger']); return $service; }; // instantiate talkService from container $talkService = $container['talkService'];
  • 72. Dependency Injection – Was, wie warum?
  • 73. ZendDi – Erste Schritte Dependency Injection – Was, wie warum? <?php namespace Acme; class TalkService { public function __construct() { } public function getTalks() { } }
  • 74. ZendDi – Erste Schritte Dependency Injection – Was, wie warum? <?php $di = new ZendDiDi(); $service = $di->get('AcmeTalkService'); $service->getTalks();
  • 75. ZendDi – Constructor Injection Dependency Injection – Was, wie warum? <?php namespace Acme; interface GenericRepository { public function readTalks(); } class TalkRepository implements GenericRepository { public function readTalks() { } } class TalkService { public function __construct(TalkRepository $repo) { } public function getTalks() { } }
  • 76. ZendDi – Constructor Injection Dependency Injection – Was, wie warum? <?php $di = new ZendDiDi(); $service = $di->get('AcmeTalkService'); $service->getTalks();
  • 77. ZendDi – Setter Injection Dependency Injection – Was, wie warum? <?php namespace Acme; class Logger { public function doLog($logMsg) { } } class TalkService { public function __construct(TalkRepository $repo) { } public function setLogger(Logger $logger) { } public function getTalks() { } }
  • 78. ZendDi – Setter Injection Dependency Injection – Was, wie warum? <?php $di = new ZendDiDi(); $di->configure( new ZendDiConfiguration( array( 'definition' => array( 'class' => array( 'AcmeTalkService' => array( 'setLogger' => array('required' => true) ) ) ) ) ) ); $service = $di->get('AcmeTalkService'); var_dump($service);
  • 79. ZendDi – Interface Injection Dependency Injection – Was, wie warum? <?php namespace Acme; class Logger { public function doLog($logMsg) { } } interface LoggerAware { public function setLogger(Logger $logger); } class TalkService implements LoggerAware { public function __construct(TalkRepository $repo) { } public function setLogger(Logger $logger) { } public function getTalks() { } }
  • 80. ZendDi – Interface Injection Dependency Injection – Was, wie warum? <?php $di = new ZendDiDi(); $service = $di->get('AcmeTalkService'); $service->getTalks();
  • 81. ZendDi – Grundsätzliches Dependency Injection – Was, wie warum? <?php $di = new ZendDiDi(); $service = $di->get('AcmeTalkService'); var_dump($service); $service2 = $di->get('AcmeTalkService'); var_dump($service2); // same instance as $service $service3 = $di->get( 'AcmeTalkService', array( 'repo' => new AcmeTalkRepository() ) );
  • 82. ZendDi – Builder Definition Dependency Injection – Was, wie warum? <?php // describe dependency $dep = new ZendDiDefinitionBuilderPhpClass(); $dep->setName('AcmeTalkRepository'); // describe class $class = new ZendDiDefinitionBuilderPhpClass(); $class->setName('AcmeTalkService'); // add injection method $im = new ZendDiDefinitionBuilderInjectionMethod(); $im->setName('__construct'); $im->addParameter('repo', 'AcmeTalkRepository'); $class->addInjectionMethod($im); // configure builder $builder = new ZendDiDefinitionBuilderDefinition(); $builder->addClass($dep); $builder->addClass($class);
  • 83. ZendDi – Builder Definition Dependency Injection – Was, wie warum? <?php // add to Di $defList = new ZendDiDefinitionList($builder); $di = new ZendDiDi($defList); $service = $di->get('AcmeTalkService'); var_dump($service);
  • 84. Dependency Injection – Was, wie warum?
  • 85. Symfony2 Dependency Injection – Was, wie warum? <?php namespace AcmeTalkBundleController; use SymfonyBundleFrameworkBundleControllerController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SensioBundleFrameworkExtraBundleConfigurationTemplate; class TalkController extends Controller { /** * @Route("/", name="_talk") * @Template() */ public function indexAction() { $service = $this->get('acme.talk.service'); return array(); } }
  • 86. Symfony2 – Konfigurationsdatei Dependency Injection – Was, wie warum? <?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> </container> File services.xml in src/Acme/DemoBundle/Resources/config
  • 87. Symfony2 – Constructor Injection Dependency Injection – Was, wie warum? <?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="acme.talk.repo" class="AcmeTalkBundleServiceTalkRepository" /> <service id="acme.talk.service" class="AcmeTalkBundleServiceTalkService"> <argument type="service" id="acme.talk.repo" /> </service> </services> </container>
  • 88. Symfony2 – Setter Injection Dependency Injection – Was, wie warum? <?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="acme.talk.logger" class="AcmeTalkBundleServiceLogger" /> <service id="acme.talk.repo" class="AcmeTalkBundleServiceTalkRepository" /> <service id="acme.talk.service" class="AcmeTalkBundleServiceTalkService"> <argument type="service" id="acme.talk.repo" /> <call method="setLogger"> <argument type="service" id="acme.talk.logger" /> </call> </service> </services> </container>
  • 89. Symfony2 – Setter Injection (optional) Dependency Injection – Was, wie warum? <?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="acme.talk.logger" class="AcmeTalkBundleServiceLogger" /> <service id="acme.talk.repo" class="AcmeTalkBundleServiceTalkRepository" /> <service id="acme.talk.service" class="AcmeTalkBundleServiceTalkService"> <argument type="service" id="acme.talk.repo" /> <call method="setLogger"> <argument type="service" id="acme.talk.logger" on-invalid="ignore" /> </call> </service> </services> </container>
  • 90. Symfony2 – Property Injection Dependency Injection – Was, wie warum? <?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="acme.talk.repo" class="AcmeTalkBundleServiceTalkRepository" /> <service id="acme.talk.service" class="AcmeTalkBundleServiceTalkService"> <property name="talkRepository" type="service" id="acme.talk.repo" /> </service> </services> </container>
  • 91. Dependency Injection – Was, wie warum?
  • 92. Flow3 – Constructor Injection Dependency Injection – Was, wie warum? <?php namespace AcmeDemoController; use TYPO3FLOW3Annotations as FLOW3; /** * @FLOW3Scope("session") */ class StandardController extends TYPO3FLOW3MVCControllerActionController { /** * @var AcmeDemoServiceTalkServiceInterface */ protected $talkService; public function __construct( AcmeDemoServiceTalkService $talkService) { $this->talkService = $talkService; } public function indexAction() { } }
  • 93. Flow3 – Setter Injection (manuell) Dependency Injection – Was, wie warum? <?php namespace AcmeDemoController; use TYPO3FLOW3Annotations as FLOW3; /** * @FLOW3Scope("session") */ class StandardController extends TYPO3FLOW3MVCControllerActionController { /** * @var AcmeDemoServiceTalkServiceInterface */ protected $talkService; public function setTalkService( AcmeDemoServiceTalkService $talkService) { $this->talkService = $talkService; } public function indexAction() { } }
  • 94. Flow3 – Setter Injection (manuell) Dependency Injection – Was, wie warum? File Objects.yaml in Packages/Application/Acme.Demo/Configuration # @package Acme AcmeDemoControllerStandardController: properties: talkService: object: AcmeDemoServiceTalkService
  • 95. Flow3 – Setter Injection (automatisch) Dependency Injection – Was, wie warum? <?php namespace AcmeDemoController; use TYPO3FLOW3Annotations as FLOW3; /** * @FLOW3Scope("session") */ class StandardController extends TYPO3FLOW3MVCControllerActionController { /** * @var AcmeDemoServiceTalkServiceInterface */ protected $talkService; public function injectTalkService( AcmeDemoServiceTalkService $talkService) { $this->talkService = $talkService; } public function indexAction() { } }
  • 96. Dependency Injection – Was, wie warum? Fokus aufs Wesentliche. Keine Ablenkung.
  • 97. Dependency Injection – Was, wie warum? Wiederverwendung steigern.
  • 98. Dependency Injection – Was, wie warum? Hilft den Code besser zu verstehen.
  • 99. Dependency Injection – Was, wie warum? Wieder Spaß bei der Arbeit ;)
  • 100. Dependency Injection – Was, wie warum? Kein Standard. Kein Tooling.
  • 101. Dependency Injection – Was, wie warum? Es braucht Zeit um DI zu verstehen.
  • 102. Dependency Injection – Was, wie warum? Konfiguration vs. Laufzeit