Get project directory on command symfony 3.4

Viewed 5839

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

3 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

You can inject KernelInterface to the command just adding it to the constructor parameters and then get the project directory with $kernel->getProjectDir():

<?php

namespace App\Command;

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

class FooCommand extends Command
{
    protected $projectDir;

    public function __construct(KernelInterface $kernel)
    {
        parent::__construct();
        $this->projectDir = $kernel->getProjectDir();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        echo "This is the project directory: " . $this->projectDir;
        //...
    }
}

Well, I would say, inject the %kernel.project_dir% or %kernel.root_dir% parameters directly in your command. No need to make your command dependent on the Kernel service.

And by the way you can also make your Command extends Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand which is an abstract class. So you can access the container within your command by just calling getContainer method.

But, I would not advice you to this actually. Better take benefit of autowiring or configure your service in a "yaml" way.

Related