Symfony2 路由 - 路由子域 [英] Symfony2 Routing - route subdomains
问题描述
有没有办法在 Symfony2 中设置基于主机名的路由?
Is there a way to set up hostname based routing in Symfony2?
我在官方文档中没有找到有关此主题的任何信息.
http://symfony.com/doc/2.0/book/routing.html
I didn't find anything about this topic in the official documentation.
http://symfony.com/doc/2.0/book/routing.html
我想根据给定的主机名路由请求:
foo.example.com
bar.example.com
{{子域}}.example.com
I want to route the request based on the given hostname:
foo.example.com
bar.example.com
{{subdomain}}.example.com
所以本质上,控制器会将当前子域作为参数传递.
So in essence, the controller would get the current subdomain passed as a parameter.
类似于 Zend 的解决方案:
http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname
Similar to the Zend solution:
http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
':username.users.example.com',
array(
'controller' => 'profile',
'action' => 'userinfo'
)
);
$plainPathRoute = new Zend_Controller_Router_Route_Static('');
$router->addRoute('user', $hostnameRoute->chain($plainPathRoute));
我希望这是可能的,但我不知何故错过了.
提前致谢!
I hope that it's possible and I just missed it somehow.
Thanks in advance!
推荐答案
这是我的解决方案:
在应用目录内的 config.yml
中添加以下几行:
In the config.yml
inside app dir add the following lines:
services:
kernel.listener.subdomain_listener:
class: AcmeDemoBundleListenerSubdomainListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onDomainParse }
然后创建类 SubdomainListener.php
为:
<?php
namespace AcmeDemoBundleListener;
use SymfonyComponentEventDispatcherEventDispatcher;
use SymfonyComponentEventDispatcherEvent;
class SubdomainListener
{
public function onDomainParse(Event $event)
{
$request = $event->getRequest();
$session = $request->getSession();
// todo: parsing subdomain to detect country
$session->set('subdomain', $request->getHost());
}
}
这篇关于Symfony2 路由 - 路由子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!