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

実践DIコンテナ

 実践DIコンテナ

DIコンテナを使って役に立った場面をご紹介
PHP BLT#4 (http://phpblt.connpass.com/event/27655/) 発表資料

Sota Sugiura

April 20, 2016
Tweet

More Decks by Sota Sugiura

Other Decks in Technology

Transcript

  1. $MBTT#JOEJOH <?php /* ུ */ /** * */ public function

    boot() { $this->app->bind( // ίϯετϥΫλͰλΠϓώϯτ͞ΕΔΫϥε໊ \App\Dinners\PotatoTips::class, function ($app) { // ࣮ࡍʹฦ͞ΕΔΠϯελϯε return new \App\Dinners\Blt; } ); }
  2. *OUFSGBDFBOE$MBTT interface Burger { public function addTopping($toppingName); } class Blt

    implements Burger { public function addTopping($toppingName) { // } }
  3. #JOE*OUFSGBDF /* in DI Container */ public function boot() {

    // ΠϯλʔϑΣʔεʹ۩৅ΫϥεΛbind // BurgerΠϯλʔϑΣʔεΛλΠϓώϯτ͢Δͱ // BltΫϥε͕஫ೖ͞ΕΔ $this->app->bind(Burger::class, Blt::class); }
  4. /FX$MBTT interface Burger { public function addTopping($toppingName); } class Blt

    implements Burger { public function addTopping($toppingName) { // } } class Teriyaki implements Burger { public function addTopping($toppingName) { // } }
  5. $IBOHF$MBTT#JOEJOH /* in DI Container */ public function boot() {

    // ݩʑͷΫϥε // $this->app->bind(Burger::class, Blt::class); // ৽ࠩ͘͠͠ସ͑ΔΫϥεΛBinding $this->app->bind(Burger::class, Teriyaki::class); }
  6. 5FTUJOH public function testAccessTopPage() { // σʔλΞΫηεΫϥεͷϞοΫ࡞੒ $userMock = \Mockery::mock(\User::class);

    $userMock->shouldReceive('getUsers')->andReturn('username'); // ϞοΫΫϥεΛBinding $this->app->bind(\User::class, function () use ($userMock) { return $userMock; }); // ςετ࣮ߦ $this->visit('/top') ->see('username') ->assertResponseOk(); }