laravel - 命令方法中的 Laravel 依赖注入
问题描述
如果对某人来说我的问题的标题很常见,我很抱歉,但事实是我已经尝试了几个小时来获得预期的结果,但我没有成功。
碰巧,我正在为 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
for,当它调用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
,但事实并非如此。我将不胜感激您能给我的任何帮助。
解决方案
您BaseCommand
必须实现您为该handle
方法输入的接口。依赖注入发生在方法被调用之前,所以容器解析了你的绑定(因为它试图将一个实例传递BaseCommand
给方法调用,handle
)但是绑定没有返回实现该合约的东西,所以 PHP 不允许这样做为该参数传递,因为它与签名中参数的类型不匹配(不实现合同)。
简而言之:如果要将具体绑定到抽象,请确保具体是您要绑定的类型。
推荐阅读
- android - android.app.RemoteServiceException:startForeground 的错误通知:java.lang.RuntimeException:服务通知的无效通道:null
- mysql - MySQL UNION 表按列分组
- haskell - 如何重写使用 modifyIORef' 的 Haskell 函数以使用 atomicModifyIORef'
- c# - Create multiple indexes in a transaction using C# Mongodb strongly typed driver
- html - 带有复选框的导航栏汉堡菜单不起作用
- html - 第n个孩子食谱
- python - tensorflow TFRecord k-hot 编码
- keras - Python - RNN LSTM 模型准确率低
- oracle - 如何使用不带参数的oracle存储过程在表中插入多行
- linux - Symfony 文件权限问题