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

前端 未结 7 828
眼角桃花
眼角桃花 2020-12-07 13:49

I have put a couple of custom variables in my app/config/parameters.yml.

parameters:
    api_pass: apipass
    api_user: apiuser

I need to

相关标签:
7条回答
  • 2020-12-07 14:23

    The Clean Way - 2018+, Symfony 3.4+

    Since 2017 and Symfony 3.3 + 3.4 there is much cleaner way - easy to setup and use.

    Instead of using container and service/parameter locator anti-pattern, you can pass parameters to class via it's constructor. Don't worry, it's not time-demanding work, but rather setup once & forget approach.

    How to set it up in 2 steps?

    1. app/config/services.yml

    # config.yml
    
    # config.yml
    parameters:
        api_pass: 'secret_password'
        api_user: 'my_name'
    
    services:
        _defaults:
            autowire: true
            bind:
                $apiPass: '%api_pass%'
                $apiUser: '%api_user%'
    
        App\:
            resource: ..
    

    2. Any Controller

    <?php declare(strict_types=1);
    
    final class ApiController extends SymfonyController
    {
        /**
         * @var string 
         */
        private $apiPass;
    
        /**
         * @var string
         */
        private $apiUser;
    
        public function __construct(string $apiPass, string $apiUser)
        {
            $this->apiPass = $apiPass;
            $this->apiUser = $apiUser;
        }
    
        public function registerAction(): void
        {
            var_dump($this->apiPass); // "secret_password"
            var_dump($this->apiUser); // "my_name"
        }
    }
    

    Instant Upgrade Ready!

    In case you use older approach, you can automate it with Rector.

    Read More

    This is called constructor injection over services locator approach.

    To read more about this, check my post How to Get Parameter in Symfony Controller the Clean Way.

    (It's tested and I keep it updated for new Symfony major version (5, 6...)).

    0 讨论(0)
提交回复
热议问题