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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With