Home > Software engineering >  Symfony get values 4 times nested
Symfony get values 4 times nested

Time:08-30

So my parameters are structured like this

parameters:
    Adress:
        Shops:
            Europe: Road1
            Asia: Road2
        Headquarters:
            Europe: Streetname1
            Asia: Streetname2

If I would want to get a parameter in PHP, how would that work?

This should return me Road1 right?

$this->getParameter('adress');

parameter:
    adress: Road1

And this too.

$this->getParameter('adress')['shop'];

parameter:
    adress:
        shop: Road1

How do I get parameters from the example I showed at the beginning?

Answer:

$this->getParameter('adress')['shops']['europe'];

Thanks Toskan!

Thanks for the help in advance.

CodePudding user response:

symfony is CASE SENSITIVE

debug parameters

php bin/console debug:container --parameters

you will find Adress

install psysh to play around with it interactively

$ php bin/console psysh
Psy Shell v0.11.8 (PHP 8.1.2 — cli) by Justin Hileman
>>> $container->getParameter('Adress')
=> [
     "Shops" => [
       "Europe" => "Road1",
       "Asia" => "Road2",
     ],
     "Headquarters" => [
       "Europe" => "Streetname1",
       "Asia" => "Streetname2",
     ],
   ]

>>> $container->getParameter('Adress.Shop')
Symfony\Component\DependencyInjection\Exception\InvalidArgumentException with message 'The parameter "Adress.Shop" must be defined.'
>>> $container->getParameter('adress')
Symfony\Component\DependencyInjection\Exception\InvalidArgumentException with message 'The parameter "adress" must be defined.'
>>> $container->getParameter('Adress')
=> [
     "Shops" => [
       "Europe" => "Road1",
       "Asia" => "Road2",
     ],
     "Headquarters" => [
       "Europe" => "Streetname1",
       "Asia" => "Streetname2",
     ],
   ]
>>> $container->getParameter('Adress')['Shops']
=> [
     "Europe" => "Road1",
     "Asia" => "Road2",
   ]

>>> $container->getParameter('Adress')['Shops']['Europe']
=> "Road1"

so working result is $container->getParameter('Adress')['Shops']['Europe']

be sure to accept the answer

  • Related