
其中 app.public_hostname_context1 是在 .env.local 文件中配置的域名。
然而,当需要为一个上下文支持多个域名时,问题就出现了。无法在 defaults 配置中访问当前的域名,因此需要在每次生成URL时显式地设置域名。
一种解决方案是创建一个 RequestListener,在路由之前动态设置域名参数。
首先,从路由定义中删除 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)
接下来,创建一个 RequestListener,在 RouterListener 之前执行,以设置默认的域名参数。
在 services.yaml 中配置 RequestListener:
services:
# 必须在 RouterListener (优先级 32) 之前调用,以加载域名
App\EventListener\RequestListener:
tags:
- { name: kernel.event_listener, event: kernel.request, priority: 33 }创建 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 参数。如果不存在,则将当前请求的 Hostname 设置为 domain 参数。
这种解决方案提供了一种在 Symfony 路由中支持多个动态 Host 的方法。然而,需要权衡其优缺点,并根据实际情况进行调整。特别是需要注意以下几点:
总而言之,该方案提供了一个可行的起点,但需要根据具体需求进行定制和优化。通过仔细考虑路由策略和潜在的陷阱,可以构建一个健壮且可维护的 Symfony 应用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号