1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】サービスコンテナが何者かを簡単にしらべてみました。

Posted at

はじめに

現在インターン先でLaravelを使った開発を1年ほどしています。Laravelの核と言われているサービスコンテナを理解するために調ことをメモとして残しておきたいと思います。

サービスコンテナとは

サービスコンテナとは、クラスのインスタンス化を管理してくれる仕組みのことです。

例)Exampleクラスのインスタンスを生成

Example.php
$example = app()->make(Example::class);

また、上記コードと以下の結果は同じです。

Example.php
$example = new Example();

これだけだと、サービスコンテナを使う必要ないのでは?と思います。
しかしサービスコンテンナには、依存関係を自動解決をしてくれる働きを持っています。

依存関係の自動解決とは?

以下のように、ExampleクラスがMailクラスに依存しているとします。

Example.php
class Example
{
    public $mail;

    public function __construct(Mail $mail)
    {
        $this->mail = $mail;
    }

    public function run()
    {
        $this->mail->send();
    }
}
Mail.php
class Mail
{
    public function send()
    {
        \Log::info('sendメソッド実行');
    }
}

通常であれば、以下のようにExampleクラスをインスタンス化する前に、Exampleクラスの依存先であるMailクラスのインスタンス化を実行する必要があります。

$mail = new Mail();
$example = new Exmaple($mail);

これをサービスコンテナを使った書き方で書くと以下のようになります。

①bindメソッドでサービスコンテナへ登録

$example = app()->bind('example', Example::class);

②makeメソッドを使ってExampleクラスのインスタンス化

$myClass = app()->make('example');

サービスコンテナが自動的に依存関係を解決するため、上記は正常に実行されます。

まとめ

サービスコンテナの役割について簡単にまとめてみました。
サービスコンテナを使うことで依存関係を自動解決してクラスをインスタンス化してくれることがわかりました。

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?