Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Symfony2 environment in bundle Extension

Tags:

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

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.

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

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?

like image 820
kierans Avatar asked May 15 '13 11:05

kierans


2 Answers

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.

Something like

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

Hope this helps!

like image 136
Yoann Chambonnet Avatar answered Oct 02 '22 13:10

Yoann Chambonnet


echo $this->container->get(‘kernel’)->getEnvironment(); 

in the latest version (2.5)

like image 31
crafter Avatar answered Oct 02 '22 12:10

crafter