10

我正在尝试在 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 做到这一点?

4

3 回答 3

16

您可以在两条路线中定义它,以确保只有 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

请注意,您可能必须根据您的确切需求更改定义参数的正则表达式。你可以看看这个。复杂的正则表达式必须被". (示例myvar : "[A-Z]{2,20}"

于 2013-03-08T20:07:26.153 回答
4

要详细说明@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 }
于 2015-02-20T11:51:02.273 回答
0

根据文档:

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

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

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

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

于 2017-04-06T09:15:07.997 回答