简体   繁体   English

Symfony2中的路由:可选参数zh一个路由的四个URL

[英]Routing in Symfony2: optional parameter en four urls for one route

In my Symfony2 application I would like to make four urls possible with one route: 在我的Symfony2应用程序中,我想用一条路线制作四个网址:

  1. a-lot-of-other-stuff/report/-20 (negative number) 很多其他东西/报告/ -20 (负数)
  2. a-lot-of-other-stuff/report/40 (positive number) 很多其他东西/报告/ 40 (正数)
  3. a-lot-of-other-stuff/report/ (no number) 很多其他的东西/报告/ (没有号码)
  4. a-lot-of-other-stuff/report (no number and no / ) 很多其他东西/报告(没有数字,没有/)

My route currently looks like this: 我的路线目前看起来像这样:

report:
    pattern:  /report/{days}
    defaults: { _controller: "AppReportBundle:Report:dayReport", days = null }

The action is defined as: 该行动定义为:

public function dayReportAction($days = null)
{
    // my code here
}

This currently makes url 1 and 2 working but in the case of url 3 and 4, I get an error 这当前使url 1和2工作,但在url 3和4的情况下,我收到错误

Route not found 路线未找到

How can I make the parameter "days" optional? 如何使参数“days”可选?
And if the parameter is not provided, how can I allow the / to be omitted as well? 如果没有提供参数,我怎么能同时省略/

Here's a way to do this 这是一种方法

routing.yml 使用routing.yml

report:
    pattern: /report/{days}
    defaults: { _controller: "AppReportBundle:Report:dayReport", days: null }
    requirements:
        days: -?\d+

report_reroute:
    pattern: /report/
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route: report
        permanent: true

Since requirements is a regexp pattern it lets you have a negative number. 由于需求是正则表达式模式,因此您可以使用负数。

The reroute section forces the route /report/ to redirect on /report 重新路由部分强制路由/report/重定向/report
You can read about this on: Cookbok Entry - Elnur's Answer 你可以在上面读到: Cookbok Entry - Elnur的答案

With such behaviour, you would have: 有了这样的行为,你会有:

Route       | Action                 | Parameters
------------|------------------------|-------------
/report     | dayReportAction        | $days = null
/report/    | 301 to /report         |
/report/60  | dayReportAction        | $days = 60
/report/-4  | dayReportAction        | $days = -4
/report/foo | 404                    |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM