How to access an application parameters from a service?

后端 未结 9 817
梦如初夏
梦如初夏 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:35

    @richsage is correct (for Symfony 3.?) but it did not work for my Symfony 4.x. So here is for Symfony 4.

    in services.yaml file

    parameters:
        param1: 'hello'
    
    Services:
        App\Service\routineCheck:
                arguments:
                    $toBechecked: '%param1%'  # argument must match in class constructor
    

    in your service class routineCheck.php file do constructor like so

    private $toBechecked;
    
    public function __construct($toBechecked)
    {
        $this->toBechecked = $toBechecked;
    }
    
    public function echoSomething()
    {
        echo $this->toBechecked;
    }
    

    Done.

提交回复
热议问题