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

后端 未结 4 1219
孤街浪徒
孤街浪徒 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:40

    This is work :

    // from Foo class
    use Symfony\Component\HttpKernel\KernelInterface;
    ...
    class Foo{
        private $rootDir;
        public function __construct(KernelInterface $kernel)
        {
            $this->rootDir = $kernel->getProjectDir();
        }
        public function myfoomethod(){
            return $this->getRootDir();
        }
        public function getRootDir(){
            return $this->rootDir;
        }
    }
    
    
    // from the controller class 
    use App\Utils\Foo;
    ...
    class FaaController extends AbstractController
    {
        /**
         * @Route("/scenario", name="scenario")
         */
        public function new(Foo $foo)
        {
            dump($foo->myfoomethod()); //show the dir path !
            return $this->render('faa/index.html.twig');
        }
    }
    

提交回复
热议问题