Help us understand the problem. What are the problem?

More than 1 year has passed since last update.


Laravel の Tinker で DI

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


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

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


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);
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?