ʎɹnɔɹǝW
ʎɹnɔɹǝW

Reputation: 881

How to get parameters of a service inside symfony controllers?

Say I have a app/config/parameters.yml which contains

parameters:
    database_driver:   pdo_mysql
    ...
nacho_image: 
    upload: true
    progress: false 
    key: secret_id

Now, I would like to get upload, progress, key in my controller, but doing

$this->get('upload'); 
$this->get('nacho_image.upload'); 
$this->get('nacho.image.upload'); 
$this->getParameter('nacho.upload'); 
$this->getParameter('acho_image.upload.upload'); 

doesn't work...

Upvotes: 0

Views: 2232

Answers (2)

KhorneHoly
KhorneHoly

Reputation: 4766

You're getting this error, because your .yml file isn't well formatted. Your nacho_image parameter isn't within the range of the parameters part, but on the same level, so you can't access it over the parameters.

Edit your parameters shown as below, then you can access your parameters.

parameters:
    database_driver:   pdo_mysql
    ...
    nacho_image: 
        upload: true
        progress: false 
        key: secret_id

For everything else look @CROZET's answer.

If you need to access an value from the config, that isn't set within the parameters section, you could do it the way that is described in this answer.

Upvotes: 1

ᴄʀᴏᴢᴇᴛ
ᴄʀᴏᴢᴇᴛ

Reputation: 2999

You cannot directly get a nested parameter. you have to get the parent key and you will get all the content as an array

$nachoImageConfig = $this->getParameter('nacho_image');
$nachoImageUpload = $nachoImageConfig['upload'];

From the doc (http://symfony.com/doc/current/service_container/parameters.html):

The used . notation is just a Symfony convention to make parameters easier to read. Parameters are just flat key-value elements, they can't be organized into a nested array

That is why in most config files, the entries under 'parameters:' are fully qualified like this:

parameters:

    ...

    nacho_image.upload: true
    nacho_image.progress: false 
    nacho_image.key: secret_id

Upvotes: 3

Related Questions