symfonysymfony-2.3

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


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?


Solution

  • 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');