在我的 Symfony 應用程式(Symfony 5.3)中,我必須使用屬于多個應用程式背景關系(即自己的防火墻和自己的控制器,有時也共享控制器)的多個主機/域來支持以下場景:
main-domain.tld -> main_context
main-domain2.tld -> main_context
service.main-domain.tld -> service_context
service.main-domain2.tld -> service_context
service.maybe-several-other-brand-domains.tld -> service_context
admin.main-domain.tld -> admin_context
admin.main-domain2.tld -> admin_context
admin.maybe-several-other-brand-domains.tld -> admin_context
它是如何開始的
在我們擁有多個品牌/域之前,我們有兩個主要的應用程式背景關系,它們由它們自己的主機名尋址。所以我們做了這樣的事情來將控制器分配給背景關系:
#[Route(
path: '/',
requirements: ['domain' => '%app.public_hostname_context1%'],
defaults: ['domain' => '%app.public_hostname_context1%'],
host: '{domain}',
)]
# where app.public_hostname_context1 is a hostname configured in the .env.local
進展如何
這很有效,直到我們決定為其中一種背景關系設定多個有效主機,實際上與品牌需求一樣多。所以我做了一些研究并遇到了問題,我無法訪問defaults配置中的當前主機名,因此必須在我生成的每個 url 上明確設定域。
問題是
你會如何解決這個需求?
uj5u.com熱心網友回復:
我發布了我的第一種解決方案作為直接答案,所以請討論它或使用更好的方法。也許,我已經監督了一些東西,我有一種輕微的感覺,那個解決方案可能不是最好的。對于遇到相同要求的其他人,整個問題將記錄至少一種解決方案。:)
首先,defaults從路由定義中洗掉并為背景關系的幾個有效域提供模式:
#[Route(
path: '/',
requirements: ['domain' => '%app.public_hostnames_context1_pattern%'],
host: '{domain}',
)]
# app.public_hostname_context1_pattern is a pattern configured in the .env.local
# containing all possible hostnames for that context like
# PUBLIC_HOSTNAME_CONTEXT1_PATTERN=(?:service\.main-domain\.tld|service\.main-domain2\.tld)
要將當前主機名設定為所有路由的域引數的默認值,我有一個 RequestListener靈感來自 2012 年的這個答案,在 RouterListener 開始作業之前設定它。
在我的 services.yaml 中:
# must be called before the RouterListener (with priority 32) to load the domain
App\EventListener\RequestListener:
tags:
- { name: kernel.event_listener, event: kernel.request, priority: 33 }
和請求監聽器:
<?php
declare(strict_types=1);
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
class RequestListener
{
public function __construct(
private RouterInterface $router,
){}
public function onKernelRequest(RequestEvent $event)
{
if (false === $this->router->getContext()->hasParameter('domain')) {
$this->router->getContext()->setParameter('domain', $event->getRequest()->getHost());
}
}
}
這樣做的好處是,我仍然可以在domain創建 URL 時覆寫引數。但我看到的一個缺點是:當我為另一個背景關系生成一個 URL 并且沒有明確設定域時,將引發錯誤,因為現在當前請求的主機被用作另一個背景關系的域,即要求內的模式不允許。我可以忍受這一點。你?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/366254.html
