Symfony 4, get the root path of the project from a custom class (not a controller class)

后端 未结 4 1217
孤街浪徒
孤街浪徒 2020-12-30 03:56

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 <

4条回答
  •  自闭症患者
    2020-12-30 04:32

    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;
      }
    }
    

提交回复
热议问题