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

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

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

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

谢谢 !


慕后森
浏览 127回答 2
2回答

胡说叔叔

您不需要为此提供任何服务。您可以从控制器中的容器中获取。$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

慕容森

从 Symfony 6.1 开始,您可以自动装配参数https://symfony.com/blog/new-in-symfony-6-1-service-autowiring-attributes<?phpuse Symfony\Component\DependencyInjection\Attribute\Autowire;class MyService{&nbsp; &nbsp; public function __construct(&nbsp; &nbsp; &nbsp; &nbsp; #[Autowire('%kernel.project_dir%/config/dir')]&nbsp; &nbsp; &nbsp; &nbsp; private $dir,&nbsp; &nbsp; ) {}}
打开App,查看更多内容
随时随地看视频慕课网APP