symfony2의 컨트롤러에서 parameters.yml을 어떻게 읽습니까?
내 app / config / parameters.yml에 몇 가지 사용자 정의 변수를 넣었습니다.
parameters:
api_pass: apipass
api_user: apiuser
내 컨트롤러에서 이것들에 액세스하고 그것들을 가져 오려고했습니다.
$this->get('api_user');
내 컨트롤러 파일 내에서. 이것을 시도하면 다음과 같은 오류 메시지가 나타납니다.
You have requested a non-existent service "api_user".
이를 수행하는 올바른 방법은 무엇입니까?
에서 심포니 2.6 및 이전 버전 당신이 먼저 용기를 얻을해야하고, - -, 컨트롤러에 매개 변수를 얻기 위해 필요한 매개 변수를.
$this->container->getParameter('api_user');
이 문서 장에서 설명합니다.
$this->get()
컨트롤러의 메소드가 서비스를로드하는 동안 ( doc )
에서 심포니 2.7 이상 버전 , 다음을 사용할 수있는 컨트롤러에 매개 변수를 얻을 수 있습니다 :
$this->getParameter('api_user');
깨끗한 길
2017 및 Symfony 3.3 + 3.4 부터 설정 및 사용이 훨씬 더 깔끔한 방법이 있습니다.
컨테이너 및 서비스 / 매개 변수 로케이터 안티 패턴을 사용하는 대신 생성자를 통해 클래스에 매개 변수를 전달할 수 있습니다 . 걱정하지 마십시오. 시간이 많이 걸리는 작업이 아니라 한 번 설정하고 접근 방식을 잊어 버립니다 .
2 단계로 설정하는 방법은 무엇입니까?
1. 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: ..
2. 어떤 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"
}
}
즉시 업그레이드 준비!
이전 방식을 사용하는 경우 Rector로 자동화 할 수 있습니다 .
더 읽어보기
이를 서비스 로케이터 접근을 통한 생성자 주입 이라고 합니다.
이에 대한 자세한 내용은 내 게시물 Symfony Controller에서 매개 변수를 얻는 방법을 확인하십시오 .
(It's tested and I keep it updated for new Symfony major version (5, 6...)).
I send you an example with swiftmailer:
parameters.yml
recipients: [email1, email2, email3]
services:
your_service_name:
class: your_namespace
arguments: ["%recipients%"]
the class of the service:
protected $recipients;
public function __construct($recipients)
{
$this->recipients = $recipients;
}
In Symfony 4, you can use the 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');
// ...
}
}
and in app/config/services.yaml
:
parameters:
locale: 'en'
dir: '%kernel.project_dir%'
It works for me in both controller and form classes. More details can be found in the Symfony blog.
You can use:
public function indexAction()
{
dump( $this->getParameter('api_user'));
}
For more information I recommend you read the doc :
http://symfony.com/doc/2.8/service_container/parameters.html
In Symfony 4.3.1 I use this:
services.yaml
HTTP_USERNAME: 'admin'
HTTP_PASSWORD: 'password123'
FrontController.php
$username = $this->container->getParameter('HTTP_USERNAME');
$password = $this->container->getParameter('HTTP_PASSWORD');
You can also use:
$container->getParameter('api_user');
Visit http://symfony.com/doc/current/service_container/parameters.html
'Programing' 카테고리의 다른 글
정규식 일치 배열 만들기 (0) | 2020.06.21 |
---|---|
그룹당 여러 변수 집계 / 요약 (예 : 합계, 평균) (0) | 2020.06.21 |
신속한 사전 : 값을 배열로 가져옵니다 (0) | 2020.06.21 |
Mockito.any ()는 제네릭과 인터페이스를 전달합니다. (0) | 2020.06.21 |
bash에서 (공백이 아닌) 코드 줄 수 (0) | 2020.06.21 |