LoginSignup
10
10

More than 5 years have passed since last update.

Laravel5.3 でDIコンテナ(サービスコンテナ)を使ってインスタンス生成処理を簡略化する

Last updated at Posted at 2016-11-15

環境

  • CentOS 7
  • PHP 7
  • Laravel 5.3

はじめに

Laravel ではDIコンテナのことをサービスコンテナと呼ぶらしい。
そして、以前まではIoCコンテナと呼ばれていたらしい。
なので、

DIコンテナ = サービスコンテナ(現名称) = IoCコンテナ(旧名称)

という認識で大丈夫だと思う。

※以降、サービスコンテナと記述

やりたいこと

以下のようなクラスがあるとする。

app/Http/Controllers/SampleController.php
class SampleController extends Controller
{
    public function hoge()
    {
        $client = new \GuzzleHttp\Client();
        if (env('APP_ENV') === 'local') {
            $client = new \GuzzleHttp\Client(
                [\GuzzleHttp\RequestOptions::VERIFY => false]
            );
        }
        ...
    }

    public function foo()
    {
        $client = new \GuzzleHttp\Client();
        if (env('APP_ENV') === 'local') {
            $client = new \GuzzleHttp\Client(
                [\GuzzleHttp\RequestOptions::VERIFY => false]
            );
        }
        ...
    }
    ...
}

各メソッドごとに毎回同じ条件でインスタンスを生成しているので、この処理をまとめたい。
そして他のクラスでも同じように使いたい。

目指すゴール

app/Http/Controllers/SampleController.php
class SampleController extends Controller
{
    public function hoge()
    {
        $client = app()->make('HttpClient');
        ...
    }

    public function foo()
    {
        $client = app()->make('HttpClient');
        ...
    }
    ...
}

方法

サービスコンテナを使う。
サービスコンテナ使わなくてもできる気がするけど、簡単にできそうなので今回は使う。

サービスコンテナの使い方

サービスプロバイダーを作成する

サービスプロバイダーを使ってサービスコンテナに登録したいので、まずは以下のコマンドでサービスプロバイダーを作成する。

php artisan make:provider SampleServiceProvider

作られたSampleServiceProviderを以下のように編集する。

/app/Providers/SampleServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class SamplServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('HttpClient', function () {
            $client = new \GuzzleHttp\Client();
            if (env('APP_ENV') === 'local') {
                $client = new \GuzzleHttp\Client(
                    [\GuzzleHttp\RequestOptions::VERIFY => false]
                );
            }
            return $client;
        });
    }
}

解説

  • registerという文字の通り、ここでサービスコンテナに登録する
  • 今回はインスタンスを共有していいのでsingletonにしている
    • 毎回生成したい場合はbindを使う

config/app.phpに作成したサービスプロバイダーを追記する

config/app.php
'providers' => [
    ...
    App\Providers\SamplServiceProvider::class,
];

...

使用する(ゴール)

app/Http/Controllers/SampleController.php
class SampleController extends Controller
{
    public function hoge()
    {
        $client = app()->make('HttpClient');
        ...
    }

    public function foo()
    {
        $client = app()->make('HttpClient');
        ...
    }
    ...
}

これで毎回同じ条件を書かなくて済むので、かなりスッキリした。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10