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

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

    You can also use:

    $container->getParameter('api_user');
    

    Visit http://symfony.com/doc/current/service_container/parameters.html

    0 讨论(0)
  • 2020-12-07 14:07

    In Symfony 4.3.1 I use this:

    services.yaml

    HTTP_USERNAME: 'admin'
    HTTP_PASSWORD: 'password123'
    

    FrontController.php

    $username = $this->container->getParameter('HTTP_USERNAME');
    $password = $this->container->getParameter('HTTP_PASSWORD');
    
    0 讨论(0)
  • 2020-12-07 14:09

    You can use:

    public function indexAction()
    {
       dump( $this->getParameter('api_user'));
    }
    

    For more information I recommend you read the doc :

    http://symfony.com/doc/2.8/service_container/parameters.html

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 14:19

    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');
    
    0 讨论(0)
  • 2020-12-07 14:22

    I send you an example with swiftmailer:

    parameters.yml

    recipients: [email1, email2, email3]
    

    services:

    your_service_name:
            class: your_namespace
            arguments: ["%recipients%"]
    

    the class of the service:

    protected $recipients;
    
    public function __construct($recipients)
    {
        $this->recipients = $recipients;
    }
    
    0 讨论(0)
提交回复
热议问题