对于某人来说,我的问题的标题很普遍很抱歉,但事实是我已经努力了几个小时才能获得预期的结果,但是我没有成功。
碰巧,我正在为Laravel开发一个小程序包,并且无法在包含该程序包的命令内的方法中执行依赖项注入。
在包的目录结构中,我有ServiceProvider
<?php
namespace Author\Package;
use Author\Package\Commands\BaseCommand;
use Author\Package\Contracts\MyInterface;
use Illuminate\Support\ServiceProvider;
class PackageServiceProvider extends ServiceProvider
{
/**
* The commands to be registered.
*
* @var array
*/
protected $commands = [
\Author\Package\Commands\ExampleCommand::class
];
/**
* Register services.
*
* @return void
*/
public function register()
{
if (! $this->app->configurationIsCached()) {
$this->mergeConfigFrom(__DIR__ . '/../config/package.php', 'package');
}
$this->app->bind(MyInterface::class, BaseCommand::class);
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/package.php' => config_path('package.php')
], 'package-config');
$this->configureCommands();
}
}
/**
* Register the package's custom Artisan commands.
*
* @return void
*/
public function configureCommands()
{
$this->commands($this->commands);
}
}
从register
方法中可以看到,我正在创建一个binding
,当它调用MyInterface
接口时,它将返回具体的BaseCommand
类
public function register()
{
...
$this->app->bind(MyInterface::class, BaseCommand::class);
}
ExampleCommand
文件的结构如下:
<?php
namespace Author\Package\Commands;
use Author\Package\Contracts\MyInterface;
use Illuminate\Console\Command;
class ExampleCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'my:command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command Description';
/**
* Execute the console command.
*
* @return void
*/
public function handle(MyInterface $interface)
{
// TODO
}
}
但是当我运行命令时,出现以下错误:
TypeError
Argument 1 passed to Author\Package\Commands\ExampleCommand::handle() must be an instance of Author\Package\Contracts\MyInterface, instance of Author\Package\Commands\BaseCommand given
我想知道为什么依赖项注入不起作用,从本质上讲,应该将具体的BaseCommand
类注入到handle
类的ExampleCommand
方法中,但事实并非如此。您能给我任何帮助,我将不胜感激。
答案 0 :(得分:1)
您的BaseCommand
必须实现为此handle
方法键入的接口。依赖注入发生在调用方法之前,因此容器解析了您的绑定(因为它试图将BaseCommand
的实例传递给方法调用handle
),但是绑定没有返回实现的内容该合同,因此PHP不允许将其传递给该参数,因为它与签名中参数的类型不匹配(不实现该合同)。
简而言之:如果要将混凝土绑定到抽象,请确保混凝土实际上是您要绑定到的类型。