Boh*_*ohr 140 symfony symfony-2.3
我在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)
这样做的正确方法是什么?
Vit*_*ian 290
在Symfony 2.6和更早版本中,要在控制器中获取参数 - 您应首先获取容器,然后获取所需参数.
$this->container->getParameter('api_user');
Run Code Online (Sandbox Code Playgroud)
本文档章节对此进行了解释
虽然$this->get()控制器中的方法将加载服务(doc)
在Symfony 2.7及更高版本中,要在控制器中获取参数,可以使用以下命令:
$this->getParameter('api_user');
Run Code Online (Sandbox Code Playgroud)
Tom*_*uba 19
自2017年以来,Symfony 3.3 + 3.4有更清洁的方式 - 易于设置和使用.
您可以通过它的构造函数将参数传递给类,而不是使用容器和服务/参数定位器反模式.别担心,这不是时间要求很高的工作,而是设置一次忘记方法.
如何分两步设置?
app/config/services.yml# config.yml
# config.yml
parameters:
api_pass: 'secret_password'
api_user: 'my_name'
services:
_defaults:
autowire: true
bind:
$apiPass: '%api_pass%'
$apiUser: '%api_user%'
App\:
resource: ..
Run Code Online (Sandbox Code Playgroud)
Controller<?php declare(strict_types=1);
final class ApiController extends SymfonyController
{
/**
* @var string
*/
private $apiPass;
/**
* @var string
*/
private $apiUser;
public function __construct(string $apiPass, string $apiUser)
{
$this->apiPass = $apiPass;
$this->apiUser = $apiUser;
}
public function registerAction(): void
{
var_dump($this->apiPass); // "secret_password"
var_dump($this->apiUser); // "my_name"
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用旧方法,您可以使用Rector自动化它.
这称为服务定位器方法的构造函数注入.
要阅读更多相关信息,请查看我的文章如何在Symfony控制器中以干净的方式获取参数.
(经过测试,我保持更新为新的Symfony主要版本(5,6 ...)).
小智 10
我给你发了一个swiftmailer的例子:
recipients: [email1, email2, email3]
Run Code Online (Sandbox Code Playgroud)
your_service_name:
class: your_namespace
arguments: ["%recipients%"]
Run Code Online (Sandbox Code Playgroud)
protected $recipients;
public function __construct($recipients)
{
$this->recipients = $recipients;
}
Run Code Online (Sandbox Code Playgroud)
在Symfony 4中,您可以使用ParameterBagInterface:
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');
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
并在app/config/services.yaml:
parameters:
locale: 'en'
dir: '%kernel.project_dir%'
Run Code Online (Sandbox Code Playgroud)
它适用于控制器类和表单类。可以在Symfony博客中找到更多详细信息。