[英]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.