How to access an application parameters from a service?

后端 未结 9 743
梦如初夏
梦如初夏 2020-12-23 10:49

From my controllers, I access the application parameters (those in /app/config) with

$this->container->getParameter(\'my_param\')
<         


        
相关标签:
9条回答
  • 2020-12-23 11:38

    With Symfony 4.1 the solution is quite simple.

    Here is a snippet from the original post:

    // src/Service/MessageGenerator.php
    // ...
    
    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');
            // ...
        }
    }
    

    Link to the original post: https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service

    0 讨论(0)
  • 2020-12-23 11:41

    In symfony 4, we can access the parameters by means of dependency injection:

    Services:

       use Symfony\Component\DependencyInjection\ContainerInterface as Container;
    
       MyServices {
    
             protected $container;
             protected $path;
    
             public function __construct(Container $container)
             {
                 $this->container = $container;
                 $this->path = $this->container->getParameter('upload_directory');
             }
        }
    

    parameters.yml:

    parameters:
         upload_directory: '%kernel.project_dir%/public/uploads'
    
    0 讨论(0)
  • 2020-12-23 11:42

    There is a very clean new way to achieve it since symfony 4.1

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

    source : https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service.

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