SlideShare uma empresa Scribd logo
1 de 64
Baixar para ler offline
Introduction to DI(C)


meet.php #5    http://meetphp.pl/   19.05.2012
About me

$speaker = new Speaker;

$speaker->name            = "Radosław Benkel";
$speaker->twitter         = "@singlespl";
$speaker->blog            = "http://blog.rbenkel.me";

$speaker->givePresentation();
What?
What?


Dependency
Injection
Container
What?




Dependency
Dependency

class TwitterAPIClient
{
    protected $httpClient;
    public function __construct()
    {
        $this->httpClient = new SomeCurlWrapper();
    }

    /* ... */
}

$client = new TwitterApiClient;
Dependency
                                  This
 is
 your
 dependency.
class TwitterAPIClient
{
    protected $httpClient;
    public function __construct()
    {
        $this-httpClient = new SomeCurlWrapper();
    }

    /* ... */
}

$client = new TwitterApiClient;
Dependency



“What’s
 wrong
 with
 
      that”?
Dependency




Try testing it...
Dependency



...or change client
  implementation
Dependency
Dependency




So let’s use Injection
What?




Injection
Injection

class TwitterAPIClient
{
    protected $httpClient;
    public function __construct($httpClient)
    {
        $this-httpClient = $httpClient;
    }

    /* ... */
}                           And
 here
 you
 inject
 dependency

$client = new TwitterApiClient(new SomeCurlWrapper);
Injection




 So...
Injection
public function __construct()
{
    $this-httpClient = new SomeCurlWrapper();
}

                     VS
public function __construct($httpClient)
{
    $this-httpClient = $httpClient;
}
Injection




it’s just like...
Injection




  VS
Injection




                                                                                                                                                                VS

Try
 replacing
 battery,
 and
 you
 will
 now
 what
 I’m
 talking
 
                                                                                                                            about.
 
Injection




Injection types:
Injection

    Injection types:
•   constructor injection
Injection

    Injection types:
•   constructor injection
•   setter injection
Injection

    Injection types:
•   constructor injection
•   setter injection
•   interface injection
Injection
          Constructor injection
class TwitterAPIClient
{
    protected $httpClient;
    public function __construct($httpClient)
    {
        $this-httpClient = $httpClient;
    }

    /* ... */
}
$client = new TwitterApiClient(new SomeCurlWrapper);
Injection
                Setter injection
class TwitterAPIClient
{
    protected $httpClient;
    public function __construct() {}

    public function setHttpClient($httpClient) {
        $this-httpClient = $httpClient;
    }

    /* ... */
}
$client = new TwitterApiClient;
$client-setHttpClient(new SomeCurlWrapper);
Injection
             Interface injection
interface HttpClientInterface {
    public function setHttpClient($httpClient);
}

class TwitterAPIClient implements HttpClientInterface {
    protected $httpClient;
    public function __construct() {}
    public function setHttpClient($httpClient) {
        $this-httpClient = $httpClient;
    }
    /* ... */
}

$client = new TwitterApiClient;
$client-setHttpClient(new SomeCurlWrapper);
Injection




So far so good...
Injection



...until you don’t have
 to do something like
          that:
Injection
$mapper = new UserMapperEncrypted(
    new UserMapperCached(
        new UserMapperDB(
            new PDO(
                'mysql:host=127.0.0.1',
                'user',
                'password'
            )
        ),
        new RedisCacheAdapter(
            '127.0.0.1:6379'
        )
    ),
    'YourSuperSecretPass'
);

$mapper-save(new User('John', 'Doe'));
Injection
Injection




“How
 to
 solve
 that”?
Injection




Just use...
What?




Container
Container



require_once container_prod.php;

$mapper = $container-get('mapper.user');

/* mapper is UserMapperEncrypted, which uses UserMapperCached,
which uses UserMapperDB, which uses PDO. */
$mapper-save(new User('John', 'Doe'));
Container



require_once container_dev.php;

$mapper = $container-get('mapper.user');

/* mapper is UserMapperDB, with different PDO configuration.
*/
$mapper-save(new User('John', 'Doe'));
Container
require_once container_prod.php;
$mapper = $container-get('mapper.user');
$mapper-save(new User('John', 'Doe'));



        Find
 the
 difference

require_once container_dev.php;
$mapper = $container-get('mapper.user');
$mapper-save(new User('John', 'Doe'));
Container
require_once container_prod.php;
$mapper = $container-get('mapper.user');
$mapper-save(new User('John', 'Doe'));




require_once container_dev.php;
$mapper = $container-get('mapper.user');
$mapper-save(new User('John', 'Doe'));
Container
require_once container_prod.php;
$mapper = $container-get('mapper.user');
$mapper-save(new User('John', 'Doe'));


                                         Find

Mais conteúdo relacionado

Mais procurados

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
Fabien Potencier
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
Fabien Potencier
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 

Mais procurados (20)

Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Php Enums
Php EnumsPhp Enums
Php Enums
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 Application
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 

Destaque

"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
MoscowJS
 
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальность
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальностьДенис Измайлов, JavaScript сегодня: React, Redux и новая реальность
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальность
ScrumTrek
 

Destaque (10)

[PL] Etat czy B2B
[PL] Etat czy B2B[PL] Etat czy B2B
[PL] Etat czy B2B
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframework
 
Asynchroniczny PHP & komunikacja czasu rzeczywistego z wykorzystaniem websock...
Asynchroniczny PHP & komunikacja czasu rzeczywistego z wykorzystaniem websock...Asynchroniczny PHP & komunikacja czasu rzeczywistego z wykorzystaniem websock...
Asynchroniczny PHP & komunikacja czasu rzeczywistego z wykorzystaniem websock...
 
"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
"Flux — новый взгляд на старые проблемы" — Сергей Прохоров, MoscowJS 18
 
Dynamiczna analiza aplikacji php - meet.php
Dynamiczna analiza aplikacji php - meet.phpDynamiczna analiza aplikacji php - meet.php
Dynamiczna analiza aplikacji php - meet.php
 
The story of GOG.com Cache
The story of GOG.com Cache The story of GOG.com Cache
The story of GOG.com Cache
 
PHP i Microsoft - kto się lubi, ten się czubi
PHP i Microsoft - kto się lubi, ten się czubiPHP i Microsoft - kto się lubi, ten się czubi
PHP i Microsoft - kto się lubi, ten się czubi
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Flux architecture
Flux architectureFlux architecture
Flux architecture
 
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальность
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальностьДенис Измайлов, JavaScript сегодня: React, Redux и новая реальность
Денис Измайлов, JavaScript сегодня: React, Redux и новая реальность
 

Semelhante a Introduction to DI(C)

SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
Stephan Hochdörfer
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 

Semelhante a Introduction to DI(C) (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 

Último

+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+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...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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)
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 

Introduction to DI(C)