RW2*_*W24 6 php dependency-injection laravel laravel-5
是否可能对自定义类进行依赖注入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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这样做时:
public function handle()
{
$this->stats->updateFbStats();
}
Run Code Online (Sandbox Code Playgroud)
我突然得到 Segmentation fault: 11
当我删除该use vendor\package\Updates\UpdateStatistics;部分时,我没有收到该错误。
那么我在这里做错了什么?不能在命令中使用依赖注入吗?
您可以在该方法中注入任何服务handle:
请注意,我们可以将所需的任何依赖项注入到命令的
handle方法中。
来源: https: //laravel.com/docs/5.8/artisan#command-struct
根据 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);
}
Run Code Online (Sandbox Code Playgroud)
然而,我的猜测是,您也会遇到段错误,因为它应该尝试以相同的方式解析同一个类。如果这样做,那么至少错误会更清晰一些,并且与自动注入功能无关。
希望至少有一点帮助。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,API 文档不包含任何辅助函数,但 Github 上当前的 master、5.2 和 5.3 版本的文件都具有该函数:
| 归档时间: |
|
| 查看次数: |
6554 次 |
| 最近记录: |