2015-01-08 34 views
0

我正在为我的程序包创建命令。程序包命令中的依赖注入

我的构造函数是:

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')一切工作正常。

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

在此先感谢。

回答

1

我认为问题在于你注入了工匠的门面而不是工匠本身。

尝试

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

和服务提供商:

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

+0

OMG,我想到了好几次,但始终拒绝它作为坏主意。非常感谢你!有用。 – Alexxali