[英]Laravel: dependency injection in commands
是否可以在command
依赖注入自定义类 ?
我正在尝试这个:
<?php
namespace vendor\package\Commands;
use Illuminate\Console\Command;
use vendor\package\Models\Log;
use vendor\package\Updates\UpdateStatistics;
class UpdatePublishmentStats extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'vendorname:updatePublishmentStats';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Updates Twitter followers & Facebook page likes';
/**
* Contact implementation
* @var vendor\package\Update\UpdateStatistics
*/
protected $stats;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(
Log $log,
UpdateStatistics $stats
) {
parent::__construct();
$this->log = $log;
$this->stats = $stats;
}
但是当我尝试这样做时:
public function handle()
{
$this->stats->updateFbStats();
}
我突然得到Segmentation fault: 11
当我删除use vendor\\package\\Updates\\UpdateStatistics;
部分,我没有得到那个错误。
那么我在这里做错了什么? 是不是可以在命令中使用依赖注入?
根据5.2文档的命令结构部分( https://laravel.com/docs/5.2/artisan#writing-commands ):
“请注意,我们能够将所需的任何依赖项注入到命令的构造函数中.Laravel服务容器将自动注入构造函数中所有类型提示的依赖项。”
所以我觉得你在那里很好,只要有能力存在和可用。
至于让它工作,对我来说,段错误指向UpdateStats类的错误,它如何在服务容器中引用,或者如何从服务容器中解析它。
我没有明确的答案,但我要做的是尝试另一个类,看看我是否可以将问题本地化到这个特定的类,或者如果问题发生在其他人,然后从那里尝试调试。
此外,如果您无法使其工作, app()
函数将在您需要时解析服务容器中的项目(虽然查看5.2文档我不再看到它,因此它可能已被弃用 - 我看到$this->app->make()
但是)。
如果没有别的办法,这可能对你有用:
public function __construct(
Log $log,
) {
parent::__construct();
$this->log = $log;
$this->stats = app(UpdateStatistics::class);
}
然而,我的猜测是,你也会得到一个段错误,因为它应该尝试以相同的方式解析同一个类。 如果你这样做,那么至少错误更清晰,与自动注入功能无关。
希望至少帮助一点。
更新app()
函数
因此app()
函数似乎没有记录,但我现在安装了5.2并且Illuminate / Foundation中的helpers.php文件肯定具有以下功能:
if (! function_exists('app')) {
/**
* Get the available container instance.
*
* @param string $make
* @param array $parameters
* @return mixed|\Illuminate\Foundation\Application
*/
function app($make = null, $parameters = [])
{
if (is_null($make)) {
return Container::getInstance();
}
return Container::getInstance()->make($make, $parameters);
}
}
遗憾的是,API文档不包含任何辅助函数,但Github上当前的master,5.2和5.3版本的文件都具有以下功能:
您可以在handle
方法中注入任何服务:
请注意,我们能够将所需的任何依赖项注入命令的
handle
方法。
资料来源: https : //laravel.com/docs/5.8/artisan#command-structure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.