首页 > 开发 > PHP > 正文

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

2024-05-04 22:51:11
字体:
来源:转载
供稿:网友

本文实例讲述了Symfony2创建基于域名的路由实现方法。分享给大家供大家参考,具体如下:

你可以匹配将要来到的请求以HTTP域名的方式

YAML方式

mobile_homepage: path:  / host:  m.example.com defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }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.example.com">  <default key="_controller">AcmeDemoBundle:Main:mobileHomepage</default> </route> <route id="homepage" path="/">  <default key="_controller">AcmeDemoBundle:Main:homepage</default> </route></routes>

PHP方式

use Symfony/Component/Routing/RouteCollection;use Symfony/Component/Routing/Route;$collection = new RouteCollection();$collection->add('mobile_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:mobileHomepage',), array(), array(), 'm.example.com'));$collection->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage',)));return $collection;

两个路由匹配相同的路径  / ,然而第一个将只有域名为m.example.com才匹配

使用占位符

这个域名选项使用占位符的路径匹配系统。这样就意味着你可以在你的域名中使用占位符匹配的域名。

YAML

projects_homepage: path:  / host:  "{project_name}.example.com" defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }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="projects_homepage" path="/" host="{project_name}.example.com">  <default key="_controller">AcmeDemoBundle:Main:mobileHomepage</default> </route> <route id="homepage" path="/">  <default key="_controller">AcmeDemoBundle:Main:homepage</default> </route></routes>

PHP

use Symfony/Component/Routing/RouteCollection;use Symfony/Component/Routing/Route;$collection = new RouteCollection();$collection->add('project_homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:mobileHomepage',), array(), array(), '{project_name}.example.com'));$collection->add('homepage', new Route('/', array( '_controller' => 'AcmeDemoBundle:Main:homepage',)));return $collection;            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表