Symfony : Reading from parameter.yml from outside a controller

ⅰ亾dé卋堺 提交于 2021-02-08 09:15:49

问题


I Want to read a parameter from parameters.yml.

The solution is to extend the Controller but I got this error :

Error: Call to a member function getParameter() on null

I know that the container is null, but I don't know how to get the container.

class Configuration extends Controller
{
    public function __construct()
    {
        $this->tempFolderPath = sys_get_temp_dir();
        $parameter = $this->container->getParameter('a');
    }
}

Are there any solutions?


回答1:


In classes which extend Controller calling $this->container->getParameter('a') is possible because of Container being injected into such classes. When you are in other class you need to inject parameter you want by defining your class as a service.

Your service definition will look something like:

services:
    class: App\Your\FooClass
    arguments:
        - %a%

Note % - it's special character to inject parameters

Then your class will look like:

class FooClass
{
    protected $a;

    public function __construct($a)
    {
        $this->a = $a;
        //you have your "a" parameter value injected into constructor
    }
}



回答2:


This is not a good practice, but for me this is the only solution because in my code I have a static method that instantiates the whole class.

The solution is

public function __construct()
{
    $this->tempFolderPath = sys_get_temp_dir();
    global $kernel;
    $this->host = $kernel->getContainer()->getParameter('ws_host');
}


来源:https://stackoverflow.com/questions/42504382/symfony-reading-from-parameter-yml-from-outside-a-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!