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

Mouna Ben Hmida picture Mouna Ben Hmida · Feb 2, 2018 · Viewed 39k times · Source

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/';

Answer

Anjana Silva picture Anjana Silva · Aug 7, 2019

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.