
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
在只有一个域名的情况下,我们可以使用以下方式将控制器分配给特定的上下文:
```php
#[Route(
path: '/',
requirements: ['domain' => '%app.public_hostname_context1%'],
defaults: ['domain' => '%app.public_hostname_context1%'],
host: '{domain}',
)]其中 app.public_hostname_context1 是在 .env.local 文件中配置的主机名。
当需要支持多个域名时,defaults 配置无法访问当前主机名,因此需要在生成 URL 时显式设置域名。
一种解决方案是移除路由定义中的 defaults,并为每个上下文的有效域名提供一个模式。
#[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)
为了为所有路由的 domain 参数设置当前主机名作为默认值,我们可以创建一个 RequestListener,并在 RouterListener 之前执行它。
1. 配置 services.yaml:
services:
# 必须在 RouterListener (优先级 32) 之前调用,以加载域名
App\EventListener\RequestListener:
tags:
- { name: kernel.event_listener, event: kernel.request, priority: 33 }2. 创建 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());
}
}
}这段代码的作用是,如果路由上下文中没有 domain 参数,则将当前请求的主机名设置为 domain 参数的值。
优点:
缺点:
通过使用 RequestListener,我们可以方便地为 Symfony 路由中的 domain 参数设置默认值,从而支持多个动态主机。虽然存在一些潜在的缺点,但这种解决方案可以满足大多数多域名应用的需求。在使用时,需要注意在生成跨上下文的 URL 时显式设置域名,以避免出现错误。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号