Laravel IoC 不会自动解析接口

Laravel IoC doesn't automatically resolving the interface

我刚刚遇到了这个例子,但它无法解析绑定接口到实现。

有以下代码文件:

// File: app/App/Services/Talkable.php
<?php

namespace App\Services;

interface Talkable {
    public function talk();
}



// File: app/App/Services/Cat.php
<?php

namespace App\Services;

use App\Services\Talkable;

class Cat implements Talkable
{
    public function talk()
    {
        return 'meow meow';
    }
}



// File: app/Jobs/MakeSomeNoise.php
<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Services\Talkable;

class MakeSomeNoise extends Job
{
    private $talkable;

    public function __construct(Talkable $talkable)
    {
        $this->talkable = $talkable;
    }

    public function handle()
    {
        return ($this->talkable->talk());
    }
}

绑定发生在app/Providers/AppServiceProvider.php

// File: app/Providers/AppServiceProvider.php

    ...
    $this->app->bind('App\Services\Talkable', 'App\Services\Cat');

MakeSomeNoise 作业是从 Controller

分派的
// File: any controller

    public function makeNoises()
    {
        return $this->dispatch(new MakeSomeNoise); // (*)
    }

在 (*) 处,我希望 Laravel 会自动解析绑定,但它不会。这里的错误,

Argument 1 passed to App\Jobs\MakeSomeNoise::__construct() must be an instance of App\Services\Talkable, none given, called in ...

但是如果我只是注入控制器构造函数,它工作正常。

有什么想法吗?

我的代码有误。 DI 应该在 handle() 方法中,而不是构造函数中。

public function handle(Talkable $talkable) {
    // blah lbah
}