php 在 bundle Extension 中获取 Symfony2 环境
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16563769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Symfony2 environment in bundle Extension
提问by kierans
In my Symfony2 bundle extension my services.yml
is being loaded
在我的 Symfony2 捆绑扩展中,我services.yml
正在加载
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
However I want to load different services config per environment (eg: a different one for tests).
但是我想为每个环境加载不同的服务配置(例如:不同的测试)。
Most of the examples I've found for getting the current environment is for access within Controllers (eg: $this->get('kernel')->getEnvironment()
), however Controller based access is not possible in Extensions.
我发现的大多数用于获取当前环境的示例都是为了在控制器内进行访问(例如:)$this->get('kernel')->getEnvironment()
,但是在扩展中无法进行基于控制器的访问。
According to Twig extension - symfony2 environmentthe environment can be constructor injected however I'm not sure how my bundle extension is registered/instantiated by Symfony so not sure how to have the enviroment injected (the only references I find via grep are in the cache files, which isn't too helpful).
根据Twig 扩展 - symfony2 环境,环境可以被构造函数注入,但是我不确定我的包扩展是如何被 Symfony 注册/实例化的,所以不确定如何注入环境(我通过 grep 找到的唯一引用在缓存中文件,这不是很有帮助)。
How can I either specify a different services YAML file to be loaded per env in config, or at least find out the environment so that I can code my Extension class to load the correct file?
如何在配置中为每个 env 指定要加载的不同服务 YAML 文件,或者至少找出环境以便我可以编写扩展类以加载正确的文件?
回答by Yoann Chambonnet
Normally, while loading your services, your method prototype should be
通常,在加载您的服务时,您的方法原型应该是
public function load(array $configs, ContainerBuilder $container).
then you can access your environment doing a
然后你可以访问你的环境做一个
$env = $container->getParameter("kernel.environment")
and then test the $env to see in which environment type you are.
然后测试 $env 以查看您所在的环境类型。
Something like
就像是
if ("dev" == $env) {
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('devServices.yml');
}
...
Hope this helps!
希望这可以帮助!
回答by crafter
echo $this->container->get(‘kernel')->getEnvironment();
in the latest version (2.5)
在最新版本 (2.5)