Symfony2 路由 - 路由子域

2022-08-30 17:26:23

有没有办法在Symfony2中设置基于主机名的路由?

我在官方文档中没有找到有关此主题的任何内容。
http://symfony.com/doc/2.0/book/routing.html

我想根据给定的主机名路由请求:
foo.example.com
bar.example.com
{{subdomain}}.example.com

因此,从本质上讲,控制器将获得作为参数传递的当前子域。

与Zend解决方案类似:
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));

我希望这是可能的,我只是以某种方式错过了它。
提前致谢!


答案 1

只是为了指出,这现在被添加到Symfony v2.2中 - http://symfony.com/doc/master/components/routing/hostname_pattern.html

mobile_homepage:
    path:     /
    host:     m.{domain}
    defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }
    requirements:
        domain: %domain%

homepage:
    path:  /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

答案 2

这是我的解决方案:

在内部应用程序目录中添加以下行:config.yml

services:
   kernel.listener.subdomain_listener:
       class: Acme\DemoBundle\Listener\SubdomainListener
       tags:
           - { name: kernel.event_listener, event: kernel.request, method: onDomainParse }

然后将类创建为:SubdomainListener.php

<?php

namespace Acme\DemoBundle\Listener;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;

class SubdomainListener
{
   public function onDomainParse(Event $event)
   {
       $request = $event->getRequest();
       $session = $request->getSession();

       // todo: parsing subdomain to detect country

       $session->set('subdomain', $request->getHost());
   }
}

推荐