In the src/Utils directory, I created a custom class Foo for various things. I\'m looking for a way to get the absolute root path of the symfony 4 project <
If your class is extending:
Symfony\Bundle\FrameworkBundle\Controller\AbstractController
, then you can get the root dir as
$projectRoot = $this->getParameter('kernel.project_dir');
or
Inject ContainerBagInterface
to your controller
protected $projectRoot;
public function __construct(ContainerBagInterface $containerBag)
{
$this->projectRoot = $containerBag->get('kernel.project_dir');;
}
or
Even better and the recommended approach
Inject the root_dir
to your Foo
class. Add the following to your config under services
services:
foo:
class: App\Path\To\Foo
arguments: ['%kernel.root_dir%']
The container should pass the argument to your class on resolving, the Foo
class should look like this
rootDir = $rootDir;
}
}