本文介绍了Laravel:命令中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在command中依赖注入自定义类?

Is dependency injection of a custom class in a command possible?

我正在尝试:

<?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;
    }

但是当我尝试这样做时:

But when I try to do this:

public function handle()
{
    $this->stats->updateFbStats();

}

我突然得到Segmentation fault: 11

当我删除use vendor\package\Updates\UpdateStatistics;部分时,没有得到该错误.

When I delete the use vendor\package\Updates\UpdateStatistics; part, I don't get that error.

那么我在这里做错了什么?不可能在命令中使用依赖注入吗?

So what am I doing wrong here? Is it not possible to use dependency injection in a command?

推荐答案

您可以在handle方法中注入任何服务:

You can inject any service in the handle method:

来源: https://laravel.com/docs/5.8/artisan#command -结构

这篇关于Laravel:命令中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 11:35