考慮以下對 Symfony 控制器的請求:
http http://127.0.0.1:8000/index x-token:1000
#[Route('/index', name: 'index')]
public function index(HttpClientInterface $client, Request $request): Response
{
$client->request('GET', 'http://0.0.0.0:3001', ['headers' => ['x-token' => $request->headers->get('x-token')]]);
return new JsonResponse();
}
此代碼片段是在控制器中使用的最小示例。控制器接受請求,并使用x-token標頭對 3rd Party Api(此處:localhost:3001)進行身份驗證。
有沒有辦法讓這個程序自動化?所以基本上 - 偵聽傳入的請求并將x-token標頭注入特定的Scoped Client或Symfony 中的默認客戶端。
目標是,不是在每次使用 Http 客戶端時都這樣做,而是配置一個客戶端服務。
客戶端將在整個代碼庫中使用,而不僅僅是在這個最小示例中的控制器中。
我知道我可以使用服務裝飾并擴展使用中的客戶端。我不知道如何連接點并使其作業。
uj5u.com熱心網友回復:
您是否嘗試過使用symfony 內核事件?
首先,如果您正在呼叫某些 3rd-party api,我建議您在基礎設施層創建一個單獨的類,例如MyApiProvider. 直接從控制器使用 HttpClient 并不聰明,因為您可能還想調整某些內容(例如 api 主機等)。所以它看起來像這樣:
<?php
namespace App\Infrastructure\Provider;
class MyApiProvider
{
// Of course, this also be better configurable via your .env file
private const HOST = 'http://0.0.0.0:3001';
private HttpClientInterface $client;
private ?string $token = null;
public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}
public function setToken(string $token): void
{
$this->token = $token;
}
public function getSomething(): array
{
$response = $this->client->request(
'GET',
self::HOST,
['headers' => $this->getHeaders()]
);
return $response->toArray();
}
private function getHeaders(): array
{
$headers = [];
if ($this->token !== null) {
$headers['x-token'] = $this->token;
}
return $headers;
}
}
然后你需要使用 symfony 的kernel.request事件從請求中向你的提供者注入令牌:
<?php
namespace App\Event;
use Symfony\Component\HttpKernel\Event\KernelEvent;
class RequestTokenEventListener
{
private MyApiProvider $provider;
public function __construct(MyApiProvider $provider)
{
$this->provider = $provider;
}
public function onKernelController(KernelEvent $event): void
{
$request = $event->getRequest();
$token = $request->headers->get('x-token');
if ($token !== null) {
$this->provider->setToken($token);
}
}
}
最后你的控制器:
#[Route('/index', name: 'index')]
public function index(MyApiProvider $provider): Response
{
$provider->getSomething();
return new JsonResponse();
}
因此,如果傳遞了令牌,則您的提供者將在每個請求期間擁有令牌背景關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380549.html
