5

在我的 Symfony2 应用程序中,我想通过一条路线使四个 url 成为可能:

  1. 很多其他东西/报告/-20 (负数)
  2. a-lot-of-other-stuff/report/40 (正数)
  3. 很多其他的东西/报告/ (没有数字)
  4. 很多其他的东西/报告(没有数字和没有 / )

我的路线目前看起来像这样:

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

动作定义为:

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

这目前使 url 1 和 2 工作,但在 url 3 和 4 的情况下,我得到一个错误

找不到路线

如何使参数“days”可选?
如果没有提供参数,我怎么能允许/省略呢?

4

1 回答 1

15

这是一种方法

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

由于需求是一个正则表达式模式,它让你有一个负数。

重新路由部分强制路由/report/重定向/report
您可以在以下位置阅读:Cookbok Entry-Elnur's Answer

有了这种行为,您将拥有:

Route       | Action                 | Parameters
------------|------------------------|-------------
/report     | dayReportAction        | $days = null
/report/    | 301 to /report         |
/report/60  | dayReportAction        | $days = 60
/report/-4  | dayReportAction        | $days = -4
/report/foo | 404                    |
于 2013-06-12T08:16:55.713 回答