Symfony2路由:两个可选参数 - 至少需要一个参数

时间:2013-03-08 19:12:25

标签: php symfony routing

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

3 个答案:

答案 0 :(得分:16)

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

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}"

答案 1 :(得分: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 }

答案 2 :(得分:0)

根据文件:

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

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

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

这样你在routing.yml

中只需要一个路由