我在app/config/parameters.yml中放了几个自定义变量.
parameters:
api_pass: apipass
api_user: apiuser
Run Code Online (Sandbox Code Playgroud)
我需要从我的控制器访问这些,并试图用它来获取它们
$this->get('api_user');
Run Code Online (Sandbox Code Playgroud)
从我的控制器文件中.当我尝试这个时,我收到此错误消息:
You have requested a non-existent service "api_user".
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
我开始使用Symfony4,在尝试运行服务器时遇到以下错误:无法自动装配服务“ App \ Controller \ CharacterInformation”:方法“ __construct()”的参数“ $ region”被类型提示“字符串”,则应显式配置其值。
我如何实例化课程:
/**
* @Route("/")
* @return Response
*/
function mainPage() {
$characterInformation = new CharacterInformation('eu');
return new Response($characterInformation->getCharacter());
}
Run Code Online (Sandbox Code Playgroud)
CharacterInformation的构造函数:
/**
* @var int
*/
public function __construct(string $region) {
$this->apiInformation = new ApiContent($region);
}
Run Code Online (Sandbox Code Playgroud)
ApiContent的构造函数:
public function __construct(string $region) {
$apiToken = new ApiToken($region);
$this->token = $apiToken->getToken();
$this->region = $apiToken->getRegion();
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
由于 Symfony 5.1 通过自动装配注入容器已Psr\Container\ContainerInterface被弃用,请参阅https://symfony.com/doc/current/service_container.html#public-versus-private-services
如果服务仍然需要访问容器,将来是否需要手动注入,或者是否有其他更方便的注入方式?
一种选择是使用按名称自动装配并注入它,只要有一个名为 的变量$container,但这感觉像是一种黑客攻击。
问题:如果在 Symfony 5.1+ 中服务仍然依赖于容器,那么授予服务访问容器的最佳实践是什么?