[英]Symfony2 Routing - route subdomains
有没有办法在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));
我希望这是可能的,而我只是以某种方式错过了它。
提前致谢!
只是要指出,现在已在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 }
这是我的解决方案:
在应用程序目录中的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());
}
}
我假设symfony2中的子域路由是根据主机名的子域部分选择定义的控制器的过程,会话变量无助于解析定义的控制器。
我在内核侦听器中设置请求属性:_controller,如下所示
$request->attributes->set('_controller','AcmeBundle:Demo:main');
这有助于路由到已定义的控制器,但是我在开发环境中丢失了调试分析器,但仍然无法检测到原因
或者在控制器中获取主机名:
class DefaultController extends PowmaController {
/**
* @Route("/test")
*/
public function testAction() {
return new Response( 'Hostname ' . $this->getRequestHostnameString() );
}
function getRequestHostnameString() {
return $this->getRequest()->getHost();
}
这是处理多个域站点的捆绑包: https : //github.com/AppVentus/MultiDomainBundle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.