Search code examples
phplaravellaravel-5laravel-artisanlaravel-facade

Injecting Artisan into Service class


I am trying to inject Artisan into a service so I can avoid using the facade. Looking at the facade class reference I can see that the class I should be injecting is:

Illuminate\Console\Application

So I would assume that doing this:

<?php

namespace App\Service;

use Illuminate\Console\Application;

class DummyDataService
{
    /**
     * @var Application
     */
    private $application;

    public function __construct(
        Application $application
    ) {
        $this->application = $application;
    }

    public function insertDummyData()
    {
        $this->application->call('db:seed', [
            '--class' => 'DummyDataSeeder'
        ]);
    }
}

...would work. However, I get the following error:

BindingResolutionException in Container.php line 824:
Unresolvable dependency resolving [Parameter #2 [ <required> $version ]] in class Illuminate\Console\Application

It works if I just call the method on the facade like so:

Artisan::call('db:seed', [
    '--class' => 'DummyDataSeeder'
]);

I can't figure out what the problem is so far. Has anyone experienced any similar issues? I try to avoid facades where possible.

Thanks in advance.


Solution

  • You should inject Illuminate\Contracts\Console\Kernel and not Illuminate\Console\Application to achieve what you want, so your class should look like this:

    <?php
    
    namespace App\Service;
    
    use Illuminate\Contracts\Console\Kernel;
    
    class DummyDataService
    {
        private $kernel;
    
        public function __construct(Kernel $kernel) 
        {
            $this->kernel = $kernel;
        }
    
        public function insertDummyData()
        {
            $this->kernel->call('db:seed', [
                '--class' => 'DummyDataSeeder'
            ]);
        }
    }