Search code examples
phpsymfonyconsolesymfony4

How to get application root path in Symfony 4 Console Command


I have a simple Symfony 4 Console application. In execute() method i need to print application root path.

This $this->getContainer()->get('kernel')->getRootDir() - don't work.
This $this->get('kernel')->getRootDir(); - don't work.
This $this->get('parameter_bag')->get('kernel.project_dir'); - don't work.

How can i get application root path?


Solution

  • I suggest not injecting container to the command but passing the param explicitly in service definition

    src/Command

    class YourCommand extends Command
    {
        private $path; 
    
        public function __construct(string $path) 
        {
             $this->path = $path;
        }
    
        public function (InputInterface $input, OutputInterface $output)
        {
           echo $this->path;
        }
    }
    

    config/services.yaml

    services:
        # ...
    
        App\Command\YourCommand:
            arguments:
                $path: '%kernel.project_dir%'