在 Laravel 5 命令中使用构造函数参数时出现 BindingResolutionException

BindingResolutionException when using constructor params in Laravel 5 Command

我正在制作一个通过控制器调用的命令。当我像这样执行一个简单的示例命令和控制器时,它起作用了:

//Controller
$command = new TestCommand();
$this->dispatch($command);

//Command
public $name;

public function __construct()
{
        $this->name = 'hi';
}

public function handle(TestCommand $command)
{
        dd($command->name);
}

当我通过控制器调用命令时,我得到 'hi',这是正确的。但是当我试图通过构造函数传递一些东西时,我得到了绑定解析异常:

//Controller
$command = new TestCommand('hi');
$this->dispatch($command);

//Command
public $name;

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

public function handle(TestCommand $command)
{
        dd($command->name);
}

这是为什么?我所做的看起来与我在 Laravel 文档示例中发现的相同,但我得到了这个异常:

Container.php 行 872 中的 BindingResolutionException:class App\Commands\TestCommand

中解析 [Parameter #0 [ $name ]] 无法解决的依赖关系

这是因为依赖注入。如果您在构造函数中使用 User $userGuard $auth Laravel 之类的对象,则会将这些对象注入构造函数,因此您已设置此属性。但是 Laravel 不能注入简单类型变量所以你得到这个错误。

您还可以在 docs 页面阅读:

Of course, the constructor allows you to pass any relevant objects to the command, while the handle method executes the command.

所以它不适用于非对象参数