Symfony2的路由:两个可选参数 - 至少一个需要
我试图建立在Symfony2的部分航线以下模式: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有没有办法做到这一点?
您可以在两条路线中定义它,以确保只有一个斜线。
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 2013-03-08 20:14:10
@marty很高兴我可以帮忙!为了提供更多的信息,第一条路线与你的2个第一类型相匹配。第二种是第三种。 (oops我忘了从第一个路由中删除'customerNumber:null',否则它会接受没有任何参数的路由,我已经更新以反映这一点!) – 2013-03-08 20:15:40
为了详细说明@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 }
按照文档:
http://symfony.com/doc/current/routing/optional_placeholders.html
设置可选参数的默认值在控制器的注释中:
/**
* @Route("/blog/{page}", defaults={"page" = 1})
*/
public function indexAction($page)
{
// ...
}
这样你只需要routing.yml中的一条路由
params是怎么样的?他们有长度特异性还是数字?只是信件?字母和数字?因为如果他们都是只有数字的任何长度,这是不可能的,因为你不知道哪个是哪个。 – 2013-03-08 20:02:33
customerNumber是一个数字,invoiceNumber是一个字符串 – marty 2013-03-08 20:04:35