其中 app.public_hostname_context1 是在 .env.local 文件中配置的域名。
然而,當(dāng)需要為一個上下文支持多個域名時,問題就出現(xiàn)了。無法在 defaults 配置中訪問當(dāng)前的域名,因此需要在每次生成URL時顯式地設(shè)置域名。
一種解決方案是創(chuàng)建一個 RequestListener,在路由之前動態(tài)設(shè)置域名參數(shù)。
首先,從路由定義中刪除 defaults,并為每個上下文的有效域名提供一個模式:
use Symfony\Component\Routing\Annotation\Route; #[Route( path: '/', requirements: ['domain' => '%app.public_hostnames_context1_pattern%'], host: '{domain}', )]
app.public_hostnames_context1_pattern 是在 .env.local 文件中配置的模式,包含該上下文的所有可能域名,例如:
PUBLIC_HOSTNAME_CONTEXT1_PATTERN=(?:service\.main-domain\.tld|service\.main-domain2\.tld)
接下來,創(chuàng)建一個 RequestListener,在 RouterListener 之前執(zhí)行,以設(shè)置默認(rèn)的域名參數(shù)。
在 services.yaml 中配置 RequestListener:
services: # 必須在 RouterListener (優(yōu)先級 32) 之前調(diào)用,以加載域名 App\EventListener\RequestListener: tags: - { name: kernel.event_listener, event: kernel.request, priority: 33 }
創(chuàng)建 RequestListener 類:
<?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()); } } }
該 RequestListener 檢查路由上下文中是否已存在 domain 參數(shù)。如果不存在,則將當(dāng)前請求的 Hostname 設(shè)置為 domain 參數(shù)。
這種解決方案提供了一種在 Symfony 路由中支持多個動態(tài) Host 的方法。然而,需要權(quán)衡其優(yōu)缺點(diǎn),并根據(jù)實(shí)際情況進(jìn)行調(diào)整。特別是需要注意以下幾點(diǎn):
總而言之,該方案提供了一個可行的起點(diǎn),但需要根據(jù)具體需求進(jìn)行定制和優(yōu)化。通過仔細(xì)考慮路由策略和潛在的陷阱,可以構(gòu)建一個健壯且可維護(hù)的 Symfony 應(yīng)用。
以上就是Symfony路由中支持多個動態(tài)Host的解決方案的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
路由優(yōu)化大師是一款及簡單的路由器設(shè)置管理軟件,其主要功能是一鍵設(shè)置優(yōu)化路由、屏廣告、防蹭網(wǎng)、路由器全面檢測及高級設(shè)置等,有需要的小伙伴快來保存下載體驗(yàn)吧!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號