How do I read from parameters.yml in a controller in symfony2?

Bohr picture Bohr · Dec 16, 2012 · Viewed 155.8k times · Source

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?

Answer

Vitalii Zurian picture Vitalii Zurian · Dec 16, 2012

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 documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');