Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get project directory on command symfony 3.4

Using symfony 3.4 In controller i can get project directory using this method :

$this->get('kernel')->getProjectDir()

I would like to get the project directory on command symfony (3.4) , what is the best practise to do it ?

Thanks

like image 978
mohamed jebri Avatar asked Dec 04 '22 18:12

mohamed jebri


1 Answers

Pretty sure this question has been asked many time but I'm too lazy to search for it. Plus Symfony has moved away from pulling parameters/services from the container to injecting them. So I am not sure if previous answers are up to date.

It is pretty easy.

namespace AppBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;

class ProjectDirCommand extends Command
{
    protected static $defaultName = 'app:project-dir';

    private $projectDir;

    public function __construct($projectDir)
    {
        $this->projectDir = $projectDir;
        parent::__construct();
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Project Dir ' . $this->projectDir);
    }
}

Because your project directory is a string, autowire will not know what value to inject. You can either explicitly define your command as a service and manually inject the value or you can use the bind capability:

# services.yml or services.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
        bind:
            $projectDir: '%kernel.project_dir%' # matches on constructor argument name
like image 58
Cerad Avatar answered Dec 06 '22 07:12

Cerad