如何从 symfony2 控制器中的 parameters.yml 读取? [英] How do I read from parameters.yml in a controller in symfony2?
问题描述
我在 app/config/parameters.yml 中放置了几个自定义变量.
I have put a couple of custom variables in my app/config/parameters.yml.
parameters:
api_pass: apipass
api_user: apiuser
我需要从我的控制器访问这些,并尝试使用
I need to access these from my controller, and have tried to fetch them with
$this->get('api_user');
来自我的控制器文件.当我尝试此操作时,我收到此错误消息:
from within my controller file. When I try this, I get this error message:
You have requested a non-existent service "api_user".
这样做的正确方法是什么?
What is the correct way to do this?
推荐答案
在 Symfony 2.6 及更早版本中,要在控制器中获取参数 - 您应该先获取容器,然后 -需要的参数.
In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.
$this->container->getParameter('api_user');
这个文档章节 解释一下.
虽然控制器中的 $this->get()
方法将加载服务 (doc)
While $this->get()
method in a controller will load a service (doc)
在 Symfony 2.7 和更新版本中,要在控制器中获取参数,您可以使用以下命令:
In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:
$this->getParameter('api_user');
这篇关于如何从 symfony2 控制器中的 parameters.yml 读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!