6
1

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 3 years have passed since last update.

Laravel の Tinker で DI

Posted at

Laravel では Service Provider に依存解決のルールを記述することで、 Constructor Injection のような形で DI が実現可能です。
この DI を Tinker の実行時に行う方法がすぐ出てこなかったので、そのメモです。

TL;DR

app() ヘルパー関数または App ファサードを使えば良い。

Repository パターンを用いる際に以下のような ServiceProvider を作成した場合について考えます。

RepositoryServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Domain\User\UserRepository;
use Infra\User\UserRepository as EloquentUserRepository;

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(UserRepository::class, EloquentUserRepository::class);
    }
}

Tinker 中で以下のように DI が実現できます。

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.1  cli) by Justin Hileman
>>> $repository = app()->make(\Domain\User\UserRepository::class);
>>> // or
>>> // App::make(\Domain\User\UserRepository::class);
>>> $user = $repository->get(1);
6
1
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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?