【问题标题】:Symfony2 Routing: Two optional parameters - at least one requiredSymfony2 路由:两个可选参数 - 至少需要一个
【发布时间】:2013-02-24 10:38:12
【问题描述】:

我正在尝试在 symfony2 中为以下模式设置一些路由:

www.myaweseomesite.com/payment/customer/{customernumber}/{invoicenumber}

这两个参数都是可选的 - 所以以下场景必须有效:

www.myaweseomesite.com/payment/customer/{customerNumber}/{invoiceNumber}
www.myaweseomesite.com/payment/customer/{customerNumber}
www.myaweseomesite.com/payment/customer/{invoiceNumber}

我根据symfony2 doc设置了我的routing.yml。

payment_route:
pattern:  /payment/customer/{customerNumber}/{invoiceNumber}
defaults: { _controller: PaymentBundle:Index:payment, customerNumber: null,  invoiceNumber: null }
requirements:
    _method:  GET

到目前为止效果很好。问题是,如果两个参数都丢失或为空,则路由不应该工作。所以

www.myaweseomesite.com/payment/customer/

应该不起作用。有什么办法可以用 Symfony2 做到这一点?

【问题讨论】:

  • 参数看起来如何?它们有长度特异性还是只有数字?只是字母?字母和数字?因为如果它们都是只有数字的任意长度,这是不可能的,因为你不知道哪个是哪个。
  • customerNumber 为数字,invoiceNumber 为字符串

标签: php symfony routing


【解决方案1】:

您可以在两条路线中定义它以确保只有 1 个斜线。

payment_route_1:
    pattern:  /payment/customer/{customerNumber}/{invoiceNumber}
    defaults: { _controller: PaymentBundle:Index:payment, invoiceNumber: null }
    requirements:
        customerNumber: \d+
        invoiceNumber: \w+
        _method:  GET

payment_route_2:
    pattern:  /payment/customer/{invoiceNumber}
    defaults: { _controller: PaymentBundle:Index:payment, customerNumber: null }
    requirements:
        invoiceNumber: \w+
        _method:  GET

请注意,您可能必须根据您的具体需求更改定义参数的正则表达式。你可以look at this。复杂的正则表达式必须被" 包围。 (例如myvar : "[A-Z]{2,20}"

【讨论】:

  • @marty 很高兴我能帮上忙!为了提供更多信息,第一条路线与您的前两种类型相匹配。第二种是第三种。 (哎呀,我忘了从第一条路由中删除customerNumber: null,否则它将接受不带任何参数的路由。我已经更新以反映这一点!)
【解决方案2】:

要详细说明@Hugo 的答案,请在带有注释的配置下方找到:

/**
 * @Route("/public/edit_post/{post_slug}", name="edit_post")
 * @Route("/public/create_post/{root_category_slug}", name="create_post", requirements={"root_category_slug" = "feedback|forum|blog|"})
 * @ParamConverter("rootCategory", class="AppBundle:Social\PostCategory", options={"mapping" : {"root_category_slug" = "slug"}})
 * @ParamConverter("post", class="AppBundle:Social\Post", options={"mapping" : {"post_slug" = "slug"}})
 * @Method({"PUT", "GET"})
 * @param Request $request
 * @param PostCategory $rootCategory
 * @param Post $post
 * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
 */
public function editPostAction(Request $request, PostCategory $rootCategory = null, Post $post = null)
{ Your Stuff }

【讨论】:

    【解决方案3】:

    根据文档:

    http://symfony.com/doc/current/routing/optional_placeholders.html

    在控制器的注解中为可选参数设置一个默认值:

    /**
    * @Route("/blog/{page}", defaults={"page" = 1})
    */
    public function indexAction($page)
    {
       // ...
    }
    

    这样你在routing.yml中只需要一个路由

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 2021-08-25
      • 1970-01-01
      • 2015-09-10
      • 2017-11-16
      相关资源
      最近更新 更多