如何在 Symfony 5 中获取项目或根目录

How to get project or root dir in Symfony 5

我使用 Symfony 5 和 Solarium。我想在我的控制器(从 AbstractController 扩展)中获取项目目录(或根目录)。

我看到了一些关于内核、创建新服务等的答案。

但是,它不只是一个调用项目目录而不创建一些自定义服务等的函数吗?

谢谢!

您不需要为此提供任何服务。您可以从控制器中的容器中获取。

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

其他方法是将其绑定到 yaml。

    _defaults:
        bind:
            # pass this value to any $projectDir argument for any service
            # that's created in this file (including controller arguments)
            string $projectDir: '%kernel.project_dir%'

因此您可以将每个服务和控制器注入为 $projectDir

public class YourController {
   public function index(string $projectDir){
        // Your code
   }
}
public class YourService {
   public function __construct(string $projectDir){
        // Your code
   }
}

https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters