atorscho
atorscho

Reputation: 2109

Dependency Injection from Package Command

I am creating a command for my package.

My constructor is:

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

    $this->artisan = $artisan;
}

Protected $artisan property, of course, is present.

In my service provider register() method I have tried several methods for registering the command.

First:

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

Second:

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

Normally, it is supposed to work. But when I run the command I always get Call to undefined method Illuminate\Support\Facades\Artisan::call() error message as soon as I run $this->artisan->call('migrate') in my fire() method.

However when I write \Artisan::call('migrate') instead of the $this->artisan->call('migrate') everything works fine.

Does someone have an idea what I did wrong?

Thanks in advance.

Upvotes: 0

Views: 127

Answers (1)

Robert Bakker
Robert Bakker

Reputation: 191

I think the problem is that you inject the facade of Artisan and not Artisan itself.

Try

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

and in your service provider:

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

Upvotes: 1

Related Questions