目錄
Symfony2学习笔记之系统路由详解,symfony2学习笔记
您可能感兴趣的文章:
首頁 後端開發 php教程 Symfony2学习笔记之系统路由详解,symfony2学习笔记_PHP教程

Symfony2学习笔记之系统路由详解,symfony2学习笔记_PHP教程

Jul 12, 2016 am 08:56 AM
symfony 手遊 路由

Symfony2学习笔记之系统路由详解,symfony2学习笔记

本文详细讲述了Symfony2的系统路由。分享给大家供大家参考,具体如下:

漂亮的URL绝对是一个严肃的web应用程序必须做到的,这种方式使index.php?article_id=57这类的丑陋URL被隐藏,由更受欢迎的像 /read/intro-to-symfony 来替代。

拥有灵活性更为重要,如果你要改变一个页面的URL,比如从/blog 到 /new 怎么办?

有多少链接需要你找出来并更新呢? 如果你使用Symfony的router,这种改变将变得很简单。

Symfony2 router让你定义更具创造力的URL,你可以map你的应用程序的不同区域。

创建复杂的路由并map到controllers并可以在模板和controllers内部生成URLs

从bundles(或者其他任何地方)加载路由资源

调试你的路由

路由活动

一个路径是一个从URL 模式到一个controller的绑定。

比如假设你想匹配任何像 /blog/my-post 或者 /blog/all-about-symfony的路径并把它们发送到一个controller在那里可以查找并渲染blog实体。

该路径很简单:

YAML格式:

# app/config/routing.yml
blog_show:
pattern: /blog/{slug}
defaults: {_controller: AcmeBlogBundle:Blog:show }

登入後複製

XML格式:

<!-- app/config/routing.xml -->
<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog_show" pattern="/blog/{slug}">
<default key="_controller">AcmeBlogBundle:Blog:show</default>
</route>
</routes>

登入後複製

PHP代码格式:

// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog_show', new Route('/blog/{slug}', array(
     '_controller' => 'AcmeBlogBundle:Blog:show',
)));

登入後複製

blog_show路径定义了一个URL模式,它像/blog/* 这里的通配符被命名为slug。对于URL/blog/my-blog-post,slug变量会得到值 my-blog-post。
_controller参数是一个特定的键,它告诉Symfogy当一个URL匹配这个路径时哪个controller将要被执行。
_controller字符串被称为逻辑名。它的值会按照特定的模式来指定具体的PHP类和方法。

// src/Acme/BlogBundle/Controller/BlogController.php
namespace Acme\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BlogController extends Controller
{
  public function showAction($slug)
  {
    $blog = // use the $slug variable to query the database
    return $this->render('AcmeBlogBundle:Blog:show.html.twig', array(
      'blog' => $blog,
    ));
  }
}

登入後複製

现在当你再访问/blog/my-post 时,showAction controller将被执行并且$slug变量的值为my-post

Symfogy2 的路由器目标:映射一个请求的URL到controller。

路由:内部的秘密

当一个请求发送到应用程序时,它包含一个客户端想要获取资源的地址。这个地址叫做URL或者URI。可能是/contact,/blog/read-me或者其它样式。

GET /blog/my-blog-post

Symfony2 路由系统的目标是解析这些URL并决定哪个controller应该被执行来回复该请求。

整个路由过程可以分为:

1.请求被Symfony2的前端控制器(app.php)处理。
2.Symfony2核心(kernel)要求路由器检查请求。
3.路由器匹配接收到的URL到一个特定的路径并返回有关信息,包括应该被执行的controller。
4.Symfony2核心执行该controller,该controller最终会返回一个Response对象。

路由器层就是一个把接收到的URL转换为要执行的特定controller的工具。

创建路由

Symfony会从一个单独的路由配置文件中加载你应用程序的所有路由。该文件通常为 app/config/routing.yml。 它可以被配置成包括XML或者PHP文件等文件。

YAML格式:

# app/config/config.yml
framework:
  # ...
  router:    { resource: "%kernel.root_dir%/config/routing.yml" }

登入後複製

XML格式:

<!-- app/config/config.xml -->
<framework:config ...>
  <!-- ... -->
  <framework:router resource="%kernel.root_dir%/config/routing.xml" />
</framework:config>

登入後複製

PHP代码格式:

// app/config/config.php
$container->loadFromExtension('framework', array(
  // ...
  'router'    => array('resource' => '%kernel.root_dir%/config/routing.php'),
));

登入後複製

基础路由配置

定义一个路由很简单,通常一个应用程序拥有很多路由。一个基础路由是由两部分组成:pattern部分和defaults数组部分。
比如:

YAML格式:

_welcome:
  pattern:  /
  defaults: { _controller: AcmeDemoBundle:Main:homepage }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="_welcome" pattern="/">
    <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('_welcome', new Route('/', array(
  '_controller' => 'AcmeDemoBundle:Main:homepage',
)));
return $collection;

登入後複製

该路由匹配首页(/)并映射到AcmeDemoBundle:Main:homepage controller。_controller字符串被Symfony2翻译成一个相应的PHP函数并被执行。

带占位符路由

当然,路由系统支持更多有趣的路由。许多路由会包含一个或者多个被命名的通配符占位符。

YAML格式:

blog_show:
  pattern:  /blog/{slug}
  defaults: { _controller: AcmeBlogBundle:Blog:show }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog_show" pattern="/blog/{slug}">
    <default key="_controller">AcmeBlogBundle:Blog:show</default>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog_show', new Route('/blog/{slug}', array(
  '_controller' => 'AcmeBlogBundle:Blog:show',
)));
return $collection;

登入後複製

该模式将匹配任何类似/blog/*形式的URL。匹配占位符{slug}的值将会在controller中被使用。换句话说,如果URL是/blog/hello-world,则$slug变量值是hello-world, 该值将能在controller中被使用。该模式不会匹配像/blog, 因为默认情况下所有的占位符都是必须的。 当然可以通过在defaults数组中给这些占位符赋来改变它。

必需和可选占位符

我们来添加一个新的路由,显示所有可用的blog列表。

YAML格式:

blog:
  pattern:  /blog
  defaults: { _controller: AcmeBlogBundle:Blog:index }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog" pattern="/blog">
    <default key="_controller">AcmeBlogBundle:Blog:index</default>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog', array(
  '_controller' => 'AcmeBlogBundle:Blog:index',
)));
return $collection;

登入後複製

到目前为止,我们的路由都是非常简单的路由模式。它们包含的非占位符将会被精确匹配。

如果你想该路由能够支持分页,比如让/blog/2 显示第二页的blog,那就需要为之前的路由添加一个新的{page}占位符。

YAML格式:

blog:
  pattern:  /blog/{page}
  defaults: { _controller: AcmeBlogBundle:Blog:index }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog" pattern="/blog/{page}">
    <default key="_controller">AcmeBlogBundle:Blog:index</default>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog/{page}', array(
  '_controller' => 'AcmeBlogBundle:Blog:index',
)));
return $collection;

登入後複製

跟之前的{slug}占位符一样{page}占位符将会在你的controller内部可用,它的值可以用于表示要显示的blog值的页码。但是要清楚,因为占位符默认情况下都是必需的,该路由也将不再匹配之前的/blog URL,这时候你如果还像看第一页的话,就必须通过/blog/1 URL来访问了。要解决该问题,可以在该路由的defaults数组中指定{page}的默认值。

YAML格式:

blog:
  pattern:  /blog/{page}
  defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog" pattern="/blog/{page}">
    <default key="_controller">AcmeBlogBundle:Blog:index</default>
    <default key="page">1</default>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog/{page}', array(
  '_controller' => 'AcmeBlogBundle:Blog:index',
  'page' => 1,
)));
return $collection;

登入後複製

通过添加page到defaults键, {page}占位符就不再是必需的。这时候 /blog将会被匹配并且page参数被设置为1,URL /blog/2 也会被匹配。

添加要求约束

看看下面这些路由:

YAML格式:

blog:
  pattern:  /blog/{page}
  defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
blog_show:
  pattern:  /blog/{slug}
  defaults: { _controller: AcmeBlogBundle:Blog:show }

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog" pattern="/blog/{page}">
    <default key="_controller">AcmeBlogBundle:Blog:index</default>
    <default key="page">1</default>
  </route>
  <route id="blog_show" pattern="/blog/{slug}">
    <default key="_controller">AcmeBlogBundle:Blog:show</default>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog/{page}', array(
  '_controller' => 'AcmeBlogBundle:Blog:index',
  'page' => 1,
)));
$collection->add('blog_show', new Route('/blog/{show}', array(
  '_controller' => 'AcmeBlogBundle:Blog:show',
)));
return $collection;

登入後複製

你发现问题了吗?注意这两个路由都能匹配像/blog/* 类型的URL。Symfony只会选择第一个与之匹配的路由。

换句话说,blog_show将永远不会被像/blog/* 类型的URL匹配。而像 /blog/my-blog-post这样的URL也会被blog路由匹配,并且page变量会获得my-blog-post这样的值。

这肯定不可以,那么怎么办呢?答案是给路由添加约束要求requirements。

在blog路由中占位符{page}理想状态下只匹配整数值。幸运的是正则表达可以很容易的满足这一要求。

YAML格式:

blog:
  pattern:  /blog/{page}
  defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
  requirements:
    page: \d+
登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="blog" pattern="/blog/{page}">
    <default key="_controller">AcmeBlogBundle:Blog:index</default>
    <default key="page">1</default>
    <requirement key="page">\d+</requirement>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog/{page}', array(
  '_controller' => 'AcmeBlogBundle:Blog:index',
  'page' => 1,
), array(
  'page' => '\d+',
)));
return $collection;

登入後複製

这里 \d+ 约束是一个正则表达式,它指定了{page}只接受整数。这样像/blog/my-blog-post就不再被匹配了。这时候,它才会被blog_show路由匹配。因为参数的约束都是正则表达式,所以其复杂程度和灵活性都有你来决定了。
假设home页使用两种语言则可以这样配置路由:

YAML格式:

homepage:
  pattern:  /{culture}
  defaults: { _controller: AcmeDemoBundle:Main:homepage, culture: en }
  requirements:
    culture: en|fr
登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="homepage" pattern="/{culture}">
    <default key="_controller">AcmeDemoBundle:Main:homepage</default>
    <default key="culture">en</default>
    <requirement key="culture">en|fr</requirement>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('homepage', new Route('/{culture}', array(
  '_controller' => 'AcmeDemoBundle:Main:homepage',
  'culture' => 'en',
), array(
  'culture' => 'en|fr',
)));
return $collection;

登入後複製

添加HTTP 方法约束

除了URL,你还可以匹配请求的方法(GET,HEAD,POST,PUT,DELETE等)。假设你有一个联系表单有两个controller,一个用于显示表单(使用GET请求)一个用于处理提交的表单(POST请求)。它的配置如下:

YAML格式:

contact:
  pattern: /contact
  defaults: { _controller: AcmeDemoBundle:Main:contact }
  requirements:
    _method: GET
contact_process:
  pattern: /contact
  defaults: { _controller: AcmeDemoBundle:Main:contactProcess }
  requirements:
    _method: POST

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="contact" pattern="/contact">
    <default key="_controller">AcmeDemoBundle:Main:contact</default>
    <requirement key="_method">GET</requirement>
  </route>
  <route id="contact_process" pattern="/contact">
    <default key="_controller">AcmeDemoBundle:Main:contactProcess</default>
    <requirement key="_method">POST</requirement>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('contact', new Route('/contact', array(
  '_controller' => 'AcmeDemoBundle:Main:contact',
), array(
  '_method' => 'GET',
)));
$collection->add('contact_process', new Route('/contact', array(
  '_controller' => 'AcmeDemoBundle:Main:contactProcess',
), array(
  '_method' => 'POST',
)));
return $collection;

登入後複製

尽管这两个路由拥有同一个URL模式定义(/contact),但是第一个路由只会匹配GET请求,而第二个只会匹配POST请求。这就意味着你可以通过同一个URL来显示表单并提交表单,而用不同的controller对他们进行处理。如果没有指定_method约束,那么该路由会匹配所有请求方法。跟其它约束一样,_method约束也接受正则表达式,如果只想匹配GET或者POST那么你可以用GET|POST

高级路由例子:

Symfony2中具备一切让你创建任何形式路由的条件。

YAML格式:

article_show:
 pattern: /articles/{culture}/{year}/{title}.{_format}
 defaults: { _controller: AcmeDemoBundle:Article:show, _format: html }
 requirements:
   culture: en|fr
   _format: html|rss
   year:   \d+

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="article_show" pattern="/articles/{culture}/{year}/{title}.{_format}">
    <default key="_controller">AcmeDemoBundle:Article:show</default>
    <default key="_format">html</default>
    <requirement key="culture">en|fr</requirement>
    <requirement key="_format">html|rss</requirement>
    <requirement key="year">\d+</requirement>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('homepage', new Route('/articles/{culture}/{year}/{title}.{_format}', array(
  '_controller' => 'AcmeDemoBundle:Article:show',
  '_format' => 'html',
), array(
  'culture' => 'en|fr',
  '_format' => 'html|rss',
  'year' => '\d+',
)));
return $collection;

登入後複製

上面的路由,在匹配时只会匹配{culture}部分值为en或者fr并且{year}的值为数字的URL。该路由还告诉我们,可以用在占位符之间使用区间代替斜线。

它能够匹配如下URL:

/articles/en/2010/my-post
/articles/fr/2010/my-post.rss

这其中有个特殊的路由参数 _format,在使用该参数时,其值变为请求格式。这种请求格式相当于Respose对象的Content-Type,比如json请求格式会翻译成一个Content-Type为application/json.该参数可以用于在controller中为每个_format渲染一个不同的模板。它是一个很强的方式来渲染同一个内容到不同的格式。

特殊的路由参数:

正如你所看到的,每一个路由参数或者默认值最终都是作为一个controller方法输入参数被使用。另外,有三个参数比较特别,它们每一个都在你的应用程序中增加一个唯一功能。

_controller: 这个参数决定了当路由匹配时,哪个controller被执行。
_format: 用于设置请求格式。
_locale: 用于在session上设置本地化。

Controller的命名模式:

每一个路由必须有一个_controller参数,它决定了当路由匹配时哪个controller应该被执行。该参数使用单一的字符串模式,被称为logical controller name。

通过它Symfony可以映射到一个特定的PHP方法和类。该模式有三部分,每一部分用冒号分割开:

bundle:controller:action

登入後複製

比如_controller 的值为 AcmeBlogBundle:Blog:show 意思是AcmeBlogBundle bundle中BlogController类里面的showAction方法。

// src/Acme/BlogBundle/Controller/BlogController.php
namespace Acme\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BlogController extends Controller
{
  public function showAction($slug)
  {
    // ...
  }
}

登入後複製

Symfony会自动把它们的添加相应的后缀,Blog=>BlogController, show => showAction。

你也可以使用它的完全限定名和方法来给_controller赋值,Acme\BlogBundle\Controller\BlogController::showAction 但一般为了简洁灵活而是用逻辑名称。另外除了上面两种形式外,Symfony还支持第三种方式只有一个冒号分割符,如service_name:indexAction来为_controller赋一个作为服务使用的controller。

路由参数和控制器参数

路由参数非常重要,因为每一个路由参数都会转变成一个控制器参数被在方法中使用。

public function showAction($slug)
{
 // ...
}

登入後複製

事实上,全部的defaults集合和表单的参数值合并到一个单独的数组中。这个数组中的每个键都会成为controller方法的参数。换句话说,你的controller方法的每一个参数,Symfony都会从路由参数中查找并把找到的值赋给给参数。上面例子中的变量 $culture, $year,$title,$_format,$_controller 都会作为showAction()方法的参数。因为占位符和defaults集合被合并到一起,即使$_controller变量也是一样。你也可以使用一个特殊的变量$_route 来指定路由的名称。

包括外部路由资源

所有的路由资源的都是通过一个单一的配置文件导入的。通常是app/config/routing.yml。当然你可能想从别处导入路由资源,比如你定义的bundle中的路由资源,你可以这样导入:

YAML格式:

# app/config/routing.yml
acme_hello:
  resource: "@AcmeHelloBundle/Resources/config/routing.yml"
登入後複製

XML格式:

<!-- app/config/routing.xml -->
<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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">
  <import resource="@AcmeHelloBundle/Resources/config/routing.xml" />
</routes>

登入後複製

PHP代码格式:

// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
$collection = new RouteCollection();
$collection->addCollection($loader->import("@AcmeHelloBundle/Resources/config/routing.php"));
return $collection;

登入後複製

在使用YAML导入资源时,键(比如acme_hello)是没有意义的,只是用来保证该资源唯一不被其它行覆盖。使用resources key加载给定的路由资源。在这个示例中资源是一个全路径文件,@AcmeHelloBundle是简写语法,它会被指向bundle路径。被导入的文件内容如下:

YAML格式:

# src/Acme/HelloBundle/Resources/config/routing.yml
acme_hello:
   pattern: /hello/{name}
   defaults: { _controller: AcmeHelloBundle:Hello:index }
登入後複製

XML格式:

<!-- src/Acme/HelloBundle/Resources/config/routing.xml -->
<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="acme_hello" pattern="/hello/{name}">
    <default key="_controller">AcmeHelloBundle:Hello:index</default>
  </route>
</routes>

登入後複製

PHP代码格式:

// src/Acme/HelloBundle/Resources/config/routing.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('acme_hello', new Route('/hello/{name}', array(
  '_controller' => 'AcmeHelloBundle:Hello:index',
)));
return $collection;

登入後複製

这个文件中的路由会被解析并跟主要的路由文件内容一起被加载。

给导入的路由资源添加前缀

你可以为导入的路由资源选择一个前缀,比如说假设你想acme_hello路由有一个这样的 匹配模式:/admin/hello/{name} 而不是直接的 /hello/{name}

那么你在导入它的时候可以为其指定prefix。

YAML格式:

# app/config/routing.yml
acme_hello:
  resource: "@AcmeHelloBundle/Resources/config/routing.yml"
  prefix:  /admin

登入後複製

XML格式:

<!-- app/config/routing.xml -->
<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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">
  <import resource="@AcmeHelloBundle/Resources/config/routing.xml" prefix="/admin" />
</routes>

登入後複製

PHP代码格式:

// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
$collection = new RouteCollection();
$collection->addCollection($loader->import("@AcmeHelloBundle/Resources/config/routing.php"), '/admin');
return $collection;

登入後複製

当该外部路由资源加载的时候字符串 /admin 将被插入到匹配模式的前面。

可视化并调试路由

当你添加和个性化路由时,能够看到它并能获取一些细节信息将是非常有用的。一个好的查看你应用程序的路由的方法是通过router:debug 命令行工具。

在你项目目录下执行如下命令:

$ php app/console router:debug

登入後複製

将会输出你应用程序的所有路由。你也可以在该命令后面添加某个路由的名字来获取单个路由信息

$ php app/console router:debug article_show

登入後複製

生成URL

一个路由系统应该也能用来生成URL。事实上,路由系统是一个双向的系统,映射URL到controller+parameters 和 回对应到 一个URL。可以使用match()和generate()方法来操作。比如:

$params = $router->match('/blog/my-blog-post');
// array('slug' => 'my-blog-post', '_controller' => 'AcmeBlogBundle:Blog:show')
$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
// /blog/my-blog-post

登入後複製

要生成一个URL,你需要指定路由的名称(比如 blog_show)和任意的通配符(比如:slug=my-blog-post)作为参数。通过这些信息,可以生成任意的URL。

class MainController extends Controller
{
  public function showAction($slug)
  {
   // ...
   $url = $this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));
  }
}

登入後複製

那么如何从模板内部来生成URL呢?如果你的应用程序前端使用了AJAX请求,你也许想能够基于你的路由配置在javascript中生成URL,通过使用

FOSJsRoutingBundle(https://github.com/FriendsOfSymfony/FOSJsRoutingBundle) 你可以做到:

var url = Routing.generate('blog_show', { "slug": 'my-blog-post'});

登入後複製

生成绝对路径的URL

默认的情况下,路由器生成相对路径的URL(比如 /blog).要生成一个绝对路径的URL,只需要传入一个true到generate方法作为第三个参数值即可。

$router->generate('blog_show', array('slug' => 'my-blog-post'), true);
// http://www.example.com/blog/my-blog-post

登入後複製

当生成一个绝对路径URL时主机是当前请求对象的主机,这个是基于PHP提供的服务器信息自动决定的。当你需要为运行子命令行的脚本生成一个绝对URL时,你需要在Request对象上手动设置期望的主机头。

$request->headers->set('HOST', 'www.example.com');
登入後複製

生成带有查询字符串的URL

generate()带有一个数组通配符值来生成URI。 但是如果你传入额外的值,它将被添加到URI作为查询字符串:

$router->generate('blog', array('page' => 2, 'category' => 'Symfony'));
// /blog/2&#63;category=Symfony

登入後複製

从模板中生成URL

最常用到生成URL的地方是从模板中链接两个页面时,这来需要使用一个模板帮助函数:

Twig格式:

<a href="{{ path('blog_show', { 'slug': 'my-blog-post' }) }}">
 Read this blog post.
</a>

登入後複製

PHP格式:

<a href="<&#63;php echo $view['router']->generate('blog_show', array('slug' => 'my-blog-post')) &#63;>">
  Read this blog post.
</a>

登入後複製

也可以生成绝对路径:

Twig格式:

<a href="{{ url('blog_show', { 'slug': 'my-blog-post' }) }}">
 Read this blog post.
</a>

登入後複製

PHP格式:

<a href="<&#63;php echo $view['router']->generate('blog_show', array('slug' => 'my-blog-post'), true) &#63;>">
  Read this blog post.
</a>

登入後複製

强制路由使用HTTPS或者HTTP

有时候为了安全起见,你需要你的站点必须使用HTTPS协议访问。这时候路由组件可以通过_scheme 约束来强迫URI方案。比如:

YAML格式:

secure:
  pattern: /secure
  defaults: { _controller: AcmeDemoBundle:Main:secure }
  requirements:
    _scheme: https

登入後複製

XML格式:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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="secure" pattern="/secure">
    <default key="_controller">AcmeDemoBundle:Main:secure</default>
    <requirement key="_scheme">https</requirement>
  </route>
</routes>

登入後複製

PHP代码格式:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('secure', new Route('/secure', array(
  '_controller' => 'AcmeDemoBundle:Main:secure',
), array(
  '_scheme' => 'https',
)));
return $collection;

登入後複製

上面的路由定义就是强迫secure路由使用HTTPS协议访问。

反之,当生成secure 的URL的时候,路由系统会根据当前的访问协议方案生成相应的访问协议。比如当前是HTTP,则会自动生成HTTPS访问;如果是HTTPS访问,那么就也会相应的生成HTTPS访问。

# 如果方案是 HTTPS
{{ path('secure') }}
# 生成 /secure
# 如果方案是 HTTP
{{ path('secure') }}
# 生成 https://example.com/secure

登入後複製

当然你也可以通过设置_scheme为HTTP,来强制使用HTTP访问协议。除了上面说的强迫使用HTTPS协议访问的设置方法外,还有一种用于站点区域设置

使用requires_channel 比如你想让你站点中/admin 下面的所有路由都必须使用HTTPS协议访问,或者你的安全路由定义在第三方bundle时使用。

总结:

路由系统是一个为将接收的请求URL映射到被调用来处理该请求的controller函数的系统。它既能够让你生成漂亮的URL同时又能保持你的应用程序功能跟这些URL解耦。路由系统是双向机制的,也就是说它们也可以用来生成URL。

希望本文所述对大家基于Symfony框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • Symfony2联合查询实现方法
  • Symfony2创建页面实例详解
  • symfony2.4的twig中date用法分析
  • Symfony2之session与cookie用法小结
  • Symfony2实现从数据库获取数据的方法小结
  • Symfony2框架学习笔记之表单用法详解
  • Symfony2学习笔记之插件格式分析
  • Symfony2学习笔记之控制器用法详解
  • Symfony2学习笔记之模板用法详解
  • Symfony2安装第三方Bundles实例详解
  • Symfony2函数用法实例分析

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1111333.htmlTechArticleSymfony2学习笔记之系统路由详解,symfony2学习笔记 本文详细讲述了Symfony2的系统路由。分享给大家供大家参考,具体如下: 漂亮的URL绝对是...
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

「搶先看」DNF手遊首發5大角色,9個小轉職預覽! 「搶先看」DNF手遊首發5大角色,9個小轉職預覽! Feb 16, 2024 am 09:12 AM

1.「男鬼劍」可轉職業有:紅眼、鬼泣(韓服已經推出了修羅和劍魂,估計會在第二批上線)2、「女格鬥」可轉職業有:散打、氣功3、 「男槍手」可轉職業有:漫遊、槍砲4、「女魔法」可轉職業有:元素、魔道學者5、「女聖職者」可轉職業有:聖騎士

網易首款! 5V5多英雄技能射擊手遊《天啟行動》預約開啟! 網易首款! 5V5多英雄技能射擊手遊《天啟行動》預約開啟! Mar 16, 2024 am 08:01 AM

自2月國產遊戲版號發布以來,網易的神秘射擊遊戲《天啟行動》吸引了不少玩家的好奇心。眾所周知,網易早年雖然也有一些射擊遊戲,但好像除了《明日之後》與《荒野行動》之外,沒有太多能打的作品。近幾年,網易旗下推出的作品勢頭很猛,在許多小眾賽道上都取得不斐的成績。先前從未曝光過的《天啟行動》被放在網易開年第一砲就足以讓人側目,這是網易要向射擊賽道發起進攻的信號?在玩家對射擊手遊新品的翹首以盼中,3月13日,這款由網易自研的5V5多英雄技能射擊手遊《天啟行動》,終於揭開了神秘面紗,正式發布了它的首個實機演

《永劫無間》手遊實機畫面首曝:操作邏輯簡化,保留端遊核心玩法 《永劫無間》手遊實機畫面首曝:操作邏輯簡化,保留端遊核心玩法 Mar 26, 2024 am 11:30 AM

3月25日,《永劫無間》手遊在拿到版號一個月之後進行前瞻直播,製作人關磊在直播中親自展示了遊戲實機畫面和核心玩法。這也是《永劫無間》手遊首次公開放出實機畫面。從放出的實機畫面來看,《永劫無間》手遊延續了端遊武俠吃雞的核心玩法,飛索、振刀、連招等機制與技巧也盡數還原。而為了適配行動端的操作,手遊對操作按鍵進行了大刀闊斧的改動,保留端遊核心玩法的同時簡化了行動端的操作,創新性地使用了「輪盤」操作的UI形式:點擊普攻、長按蓄力、左滑振刀、上劃升龍,多種攻擊形式透過一個按鍵的不同操作就能輕鬆完成,但仍保

旅程IPx經典動畫《西遊記》 西行旅程無畏無懼 旅程IPx經典動畫《西遊記》 西行旅程無畏無懼 Jun 10, 2024 pm 06:15 PM

穿越蒼茫征途,踏足西遊之境!今日,征途IP正式宣布將與央視動畫《西遊記》展開跨界合作,共同打造一場融合了傳統與創新的文化盛宴!此次攜手,不僅標誌著兩大國產經典品牌的深度合作,更彰顯了征途系列在弘揚中國傳統文化道路上的不懈努力與堅持。征途系列自誕生以來,便憑藉其深厚的文化底蘊和多元化的遊戲玩法,受到玩家們的喜愛。在文化傳承方面,征途系列更是始終保持著對中國傳統文化的敬意與熱愛,將傳統文化元素巧妙地融入遊戲,為玩家們帶來了更多的樂趣與啟發。而央視動畫《西遊記》則是陪伴了一代又一代人成長的經典之作,其

英雄聯盟手遊西部魔影肌膚全新上線! 英雄聯盟手遊西部魔影肌膚全新上線! Feb 24, 2024 am 11:00 AM

2024春節假期餘額不足,召喚師元氣見底?那怎麼行!2月23日起,《英雄聯盟手遊》全新版本正式上線,全新英雄「刀鋒之影泰隆」正式登入英雄聯盟手游峽谷,一同馳掣來襲的還有全新「西部魔影」系列皮膚,盧錫安、蕾歐娜、泰隆、莎彌拉、圖奇、卡特琳娜紛紛在系列中亮相。除此之外,「元氣計畫」系列活動也將於同日上線,輕鬆、簡單的活動任務,只要喊上三五好友登入遊戲,就能領取「三星守護靈-岩茶寶」、表情包等豐厚獎勵,助力玩家元氣出戰!惡獄馳擎,魔影再臨!西部魔影系列皮膚登錄手遊峽谷「西部魔影」系列皮膚品質的玩家口

國內科幻射擊卡牌手遊《代號:鐳閃》將於12月26日在TapTap開始預約 國內科幻射擊卡牌手遊《代號:鐳閃》將於12月26日在TapTap開始預約 Jan 13, 2024 pm 03:48 PM

【新遊速報】12月26日,國產輕科幻槍戰題材卡牌手遊《代號:鐳閃》於TapTap搶先開啟預約,這款遊戲由反射狐工作室研發,遊戲在題材和美術上展示出了強烈的寫實特色,快節奏即時槍戰策略玩法獨具創新。本作或於近期開啟首次測試。 《代號:鐳閃》TapTap預約期間,也舉辦了系列預約抽獎活動,提供包括華為mate60pro手機、華為WATCH4智慧手錶、Switch遊戲主機在內的預約獎勵,部分玩家在遊戲官網參與預約時也注意到了隱藏的解謎活動,規則顯示第一個輸入正確答案的玩家將直接獲得華為mate60pro

Java Apache Camel:打造靈活且有效率的服務導向架構 Java Apache Camel:打造靈活且有效率的服務導向架構 Feb 19, 2024 pm 04:12 PM

ApacheCamel是一個基於企業服務匯流排(ESB)的整合框架,它可以輕鬆地將不同的應用程式、服務和資料來源整合在一起,從而實現複雜的業務流程自動化。 ApacheCamel使用基於路由的設定方式,可以輕鬆定義和管理整合流程。 ApacheCamel的主要特點包括:靈活性:ApacheCamel可以輕鬆地與各種應用程式、服務和資料來源整合。它支援多種協議,包括Http、JMS、SOAP、FTP等。高效性:ApacheCamel非常高效,它可以處理大量的訊息。它使用非同步訊息傳遞機制,可以提高效能。可擴

永劫無間手遊測試服在哪裡玩 永劫無間手遊測試服在哪裡玩 Apr 02, 2024 am 10:52 AM

玩家可以參與永劫無間手遊測試服體驗遊戲,玩家需要在獲得測試資格後下載測試服,在測試開啟時獲得測試資格的玩家,會收到官方的下載安裝包地址。永劫無間手遊測試服在哪玩1、測試開啟時取得測試資格的玩家,會收到官方的下載安裝包位址。 2.參與永劫無間手遊測試服體驗遊戲,玩家需在取得測試資格後下載測試服。 3、玩家可以前往官網完成預約,填寫問卷後申請測試資格。 4.預約成功以後,用戶可以填寫遊戲問卷來搶先取得測試資格。 5.永劫無間手遊2024年4月1日開始首測。

See all articles