【问题标题】:Dependency Injection from Package Command包命令的依赖注入
【发布时间】:2015-01-08 17:35:34
【问题描述】:

我正在为我的包创建一个命令。

我的构造函数是:

public function __construct(\Artisan $artisan)
{
    parent::__construct();

    $this->artisan = $artisan;
}

受保护的$artisan 属性当然存在。

在我的服务提供者register()方法中,我尝试了几种注册命令的方法。

第一:

$this->app['custom.command'] = $this->app->share(function ($app)
{
    return new CustomCommand(new \Artisan);
});
$this->commands('custom.command');

第二:

$this->app['custom.command'] = $this->app->share(function ($app)
{
    return $app->make('CustomCommand');
});
$this->commands('custom.command');

通常,它应该可以工作。但是当我运行命令时,我总是在我的 fire() 方法中运行 $this->artisan->call('migrate') 时收到 Call to undefined method Illuminate\Support\Facades\Artisan::call() 错误消息。

但是,当我写 \Artisan::call('migrate') 而不是 $this->artisan->call('migrate') 时,一切正常。

有人知道我做错了什么吗?

提前致谢。

【问题讨论】:

    标签: laravel ioc-container laravel-artisan


    【解决方案1】:

    我认为问题在于您注入了 Artisan 的外观,而不是 Artisan 本身。

    试试

    public function __construct(Illuminate\Foundation\Artisan $artisan)

    在您的服务提供商中:

    return new CustomCommand($app['artisan']);

    【讨论】:

    • 天啊,我想了好几次,但总是认为这是个坏主意。非常感谢你!它有效。
    猜你喜欢
    • 2016-10-05
    • 2021-02-20
    • 1970-01-01
    • 2020-05-01
    • 2011-09-30
    • 1970-01-01
    • 2011-07-18
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多