在 bundle Extension 中获取 Symfony2 环境 [英] Get Symfony2 environment in bundle Extension

查看:28
本文介绍了在 bundle Extension 中获取 Symfony2 环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Symfony2 捆绑扩展中,我的 services.yml 正在加载

In my Symfony2 bundle extension my services.yml is being loaded

$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).

我发现的大多数获取当前环境的示例都是为了在控制器内访问(例如:$this->get('kernel')->getEnvironment()),但是在扩展中无法基于控制器进行访问.

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.

根据 Twig 扩展 - symfony2 环境 环境可以被构造函数注入,但是我是不确定我的包扩展是如何被 Symfony 注册/实例化的,所以不确定如何注入环境(我通过 grep 找到的唯一引用是在缓存文件中,这不是很有帮助).

According to Twig extension - symfony2 environment the 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).

如何在配置中为每个 env 指定要加载的不同服务 YAML 文件,或者至少找出环境以便我可以编写扩展类以加载正确的文件?

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?

推荐答案

通常,在加载您的服务时,您的方法原型应该是

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")

然后测试 $env 以查看您所在的环境类型.

and then test the $env to see in which environment type you are.

类似的东西

if ("dev" == $env) {
    $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('devServices.yml');
}
...

希望这会有所帮助!

这篇关于在 bundle Extension 中获取 Symfony2 环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆