Symfony2创建基于域名的路由相关示例

2019-05-02 15:00:16王冬梅

你还可以为这些占位符设置条件和默认的选项。列如,如果你想匹配  m.example.com 和mobile.example.com你可以按照如下方式

YAML

mobile_homepage:
 path:  /
 host:  "{subdomain}.example.com"
 defaults:
  _controller: AcmeDemoBundle:Main:mobileHomepage
  subdomain: m
 requirements:
  subdomain: m|mobile
homepage:
 path:  /
 defaults: { _controller: AcmeDemoBundle:Main:homepage }

XML

<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://symfony.com/schema/routing
  http://symfony.com/schema/routing/routing-1.0.xsd">
 <route id="mobile_homepage" path="/" host="{subdomain}.example.com">
  <default key="_controller">AcmeDemoBundle:Main:mobileHomepage</default>
  <default key="subdomain">m</default>
  <requirement key="subdomain">m|mobile</requirement>
 </route>
 <route id="homepage" path="/">
  <default key="_controller">AcmeDemoBundle:Main:homepage</default>
 </route>
</routes>

PHP

use SymfonyComponentRoutingRouteCollection;
use SymfonyComponentRoutingRoute;
$collection = new RouteCollection();
$collection->add('mobile_homepage', new Route('/', array(
 '_controller' => 'AcmeDemoBundle:Main:mobileHomepage',
 'subdomain' => 'm',
), array(
 'subdomain' => 'm|mobile',
), array(), '{subdomain}.example.com'));
$collection->add('homepage', new Route('/', array(
 '_controller' => 'AcmeDemoBundle:Main:homepage',
)));
return $collection;

你还可以使用服务参数,如果你不想将域名写死写法如下

YAML

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

XML

<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
 <route id="mobile_homepage" path="/" host="m.{domain}">
  <default key="_controller">AcmeDemoBundle:Main:mobileHomepage</default>
  <default key="domain">%domain%</default>
  <requirement key="domain">%domain%</requirement>
 </route>
 <route id="homepage" path="/">
  <default key="_controller">AcmeDemoBundle:Main:homepage</default>
 </route>
</routes>

PHP

use SymfonyComponentRoutingRouteCollection;
use SymfonyComponentRoutingRoute;
$collection = new RouteCollection();
$collection->add('mobile_homepage', new Route('/', array(
 '_controller' => 'AcmeDemoBundle:Main:mobileHomepage',
 'domain' => '%domain%',
), array(
 'domain' => '%domain%',
), array(), 'm.{domain}'));
$collection->add('homepage', new Route('/', array(
 '_controller' => 'AcmeDemoBundle:Main:homepage',
)));
return $collection;

								 
			 
相关文章 大家在看