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

Laravel 依存性注入

Last updated at Posted at 2025-12-08

Laravel 依存性注入

依存性注入とはクラスが必要とする別のオブジェクトを、そのクラス自身が作らず、外部から受け取るようにする方法のこと。言葉だけだと理解しにくいが、やっていることはシンプルで「自分でやらず、人任せにする」だけ。

日常的な例え
あなたがコーヒーを飲みたい場合

  • 依存注入でない場合

    1.台所に行く。
    2.コーヒーメーカーを探し、電源を入れる。
    3.自分でコーヒーを作る。

  • 依存注入の場合

    1.誰か(Laravelのサービスコンテナ)にコーヒーを飲みたいとお願いする。
    2.お願いした誰かがコーヒーメーカーを用意してくれる。

コード例

  • 依存されるクラス(具体的な商品を作る)
// app/Services/EmailSender.php

class EmailSender
{
    public function send(string $recipient, string $message)
    {
        // 📧 実際にメールを送る処理(SMTP接続など)
        echo "{$recipient} へメールを送信しました: \"{$message}\"";
    }
}
  • 依存するクラス
// app/Http/Controllers/OrderController.php

use App\Services\EmailSender;

class OrderController extends Controller
{
    private $emailSender;

    // ✨ ここがDIの核心!コンストラクタに「EmailSenderが必要です」と書くだけ。
    public function __construct(EmailSender $sender)
    {
        // Laravelが自動的にインスタンスを作って $sender に渡してくれる!
        $this->emailSender = $sender;
    }

    public function processOrder(int $userId)
    {
        // 注文処理ロジック...

        $message = "注文番号: {$userId} の処理が完了しました。";

        // 外部から注入された $this->emailSender を使う
        $this->emailSender->send("user-{$userId}@example.com", $message);

        return "注文処理が完了し、ユーザーに通知しました。";
    }
}
0
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
0
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?