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

前端 未结 7 873
眼角桃花
眼角桃花 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:18

    In Symfony 4, you can use the ParameterBagInterface:

    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class MessageGenerator
    {
        private $params;
    
        public function __construct(ParameterBagInterface $params)
        {
            $this->params = $params;
        }
    
        public function someMethod()
        {
            $parameterValue = $this->params->get('parameter_name');
            // ...
        }
    }
    

    and in app/config/services.yaml:

    parameters:
        locale: 'en'
        dir: '%kernel.project_dir%'
    

    It works for me in both controller and form classes. More details can be found in the Symfony blog.

提交回复
热议问题