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

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.


You can use either

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

Or the parameter %kernel.project_dir%

$container->getParameter('kernel.project_dir') . '/public/';

In Controller (also with inheriting AbstractController):

$projectDir = $this->getParameter('kernel.project_dir');