Accessing configuration parameters in Symfony 2

Hi,

Today, in this small post, I am going to show you how to access a parameter which is defined in config.yml file, inside the program.

Imaging you are creating/have a parameter called ‘is_something_enabled‘  inside config.yml. You need to access this parameter inside your code, let’s say inside a controller. This is how you do this. First of all let’s see how the parameter is defined in config.yml file.

parameters:
  is_something_enabled: true
Accessing this in a controller is very easy. Actually you don’t need to be in a controller to access these parameters. What you need is the container. If you can inject the container, to any of your class, that’s pretty much it. Here is how you access the above parameter in a controller,
$this->container->getParameter(‘is_something_enabled’);
In a container injected constructor class, this is how you access it. (Refer to my previous post to see how to inject the container to constructor)
namespace ACME\TestBundle;class Test
{
protected $ct;public function __construct(Symfony\Component\DependencyInjection\Container $container)
{
$this->ct = $container;
}public function test()
{
$isSomethingEnabled  = $this->ct->getParameter(‘is_something_enabled’);
}
}
Well that’s pretty much it for the today’s post. Hope you enjoyed my short post today.
More,

 

If you want to access nested parameters in the controller, this is the way to do it,
parameters: 
    is_something:
        enabled: true
$this->ct->getParameter('is_something')['enabled'];

Cheers 🙂

Share

3 thoughts on “Accessing configuration parameters in Symfony 2

  1. Anjana Silva says:

    Hi, @Manuel,
    Thanks for your comment. Well it’s 50-50 I would say. In some situations we need to access the services container in non-container aware classes not just to access parameters. So in situation like that we need to inject the SC to the constructor or setter method. In here I posted the easiest way to access parameters in non container aware (Controller) class.
    Thanks.

Leave a Reply to Manuel Aguirre Cancel reply

Your email address will not be published. Required fields are marked *