【问题标题】:Multiple pattern in single symfony routing单个 symfony 路由中的多个模式
【发布时间】:2012-07-06 23:10:33
【问题描述】:

如何在单个 Symfony 路由中创建多个模式?

通常我们有一个路由

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

是否可以有两种路由模式?

有点像

blog:
    #Below pattern to match with '/' or '/index'    
    pattern:   {/ , /index}  
    defaults:  { _controller: AcmeBlogBundle:Blog:index, page: 1 }

【问题讨论】:

    标签: php symfony routing


    【解决方案1】:

    你在使用 Symfony2 吗?如果您现在并且可以使用注释而不是 yml 或 xml 来为您的路由使用注释,那么可以按照以下方式定义多个路由:

    /**
    * @Route("/");
    * @Route("/home");
    */
    

    那么你就不需要复制action方法了。

    【讨论】:

    • 现在是 2017 年:是否有 Symfony3 的方式来使用 routing.yaml 做到这一点?
    【解决方案2】:

    最简单的方法是复制块并制作2条路线。

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

    因此,如果需要,您可以在路径中同时使用它们。

    Here 你可以看到另一篇文章如何在你的路由中使用正则表达式。也许您可以编写一个简单的正则表达式,它检查是否设置了 index

    编辑:

    如果您使用我更喜欢的注释,那么您可以在控制器的 Action 方法上编写多个路由。像这样的:

    /**
    * @Route("/");
    * @Route("/home");
    */
    

    【讨论】:

    • 它是否适用于不同的参数?如果是怎么办?
    【解决方案3】:

    使用 YAML 路由时,您还可以使用 node anchors 表达式语法来引用现有路由定义。

    & 指定第一次出现的锚点,* 指定要引用的锚点,<< 告诉Symfony yaml parser 合并指定节点。

    blog: &blog
      path: /
      defaults:  { _controller: AcmeBlogBundle:Blog:index, page: 1 }
    
    blog_index:
      <<: *blog
      path: /index
    
    blog_page:
      <<: *blog
      path: /blog
    

    或者,您可以在 route attribute value 上使用锚点。

    blog:
      path: /
      defaults: &blog_defaults
        _controller: AcmeBlogBundle:Blog:index
        page: 1
    
    blog_index:
      path: /index
      defaults: *blog_defaults
    
    blog_page:
      path: /blog
      defaults: *blog_defaults
    

    但为防止内容重复导致 SEO 不佳,建议改用redirect

    blog:
      path: /
      defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
    
    blog_index:
      path: /index
      defaults: &blog_redirect
        _controller: FrameworkBundle:Redirect:redirect
        route: blog
        permanent: true
    
    blog_page:
      path: /blog
      defaults: *blog_redirect
    

    【讨论】:

    • 很好......在这篇文章之前不知道锚点。
    • @LeeviGraham 也算我一个:D
    【解决方案4】:

    只是为了补充约翰的答案:

    我在 FOSJsRoutingBundle 中经常使用它:

    /**
     * @Route("/", name="route_name_1", options={"expose"=true})
     * @Route("/{id}", name="route_name_2", options={"expose"=true})
     * @Method("GET")
     * @Template()
     */
    

    这样我有一个方法和两个路线。

    记得设置默认的 $id 值:

    public function indexAction($id = null)
    {
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 2020-04-20
      • 2012-01-11
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2014-11-23
      相关资源
      最近更新 更多