Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony 4 : How to get "/public" from RootDir

I have an image under the public folder.
How can I get my image directory in symfony4 ?
In symfony 3, it's equivalent is :

$webPath = $this->get('kernel')->getRootDir() . '/../web/';
like image 855
Mouna Ben Hmida Avatar asked Feb 02 '18 14:02

Mouna Ben Hmida


3 Answers

It is a bad practice to inject the whole container, just to access parameters, if you are not in a controller. Just auto wire the ParameterBagInterface like this,

protected $parameterBag;  public function __construct(ParameterBagInterface $parameterBag) {     $this->parameterBag = $parameterBag;  } 

and then access your parameter like this (in this case the project directory),

$this->parameterBag->get('kernel.project_dir'); 

Hope someone will find this helpful.

Cheers.

like image 77
Anjana Silva Avatar answered Sep 16 '22 18:09

Anjana Silva


You can use either

$webPath = $this->get('kernel')->getProjectDir() . '/public/';  

Or the parameter %kernel.project_dir%

$container->getParameter('kernel.project_dir') . '/public/'; 
like image 28
goto Avatar answered Sep 19 '22 18:09

goto


In Controller (also with inheriting AbstractController):

$projectDir = $this->getParameter('kernel.project_dir');
like image 24
godrar Avatar answered Sep 20 '22 18:09

godrar