问题
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