问题描述
有没有办法在路由中间添加一个可选参数?
Is there any way to add an optional parameter in the middle of a route ?
示例路线:
/things/entities/
/things/1/entities/
我试过了,但它不起作用:
I tried this, but it does not work:
get('things/{id?}/entities', 'MyController@doSomething');
我知道我可以做到这一点...
I know I can do this...
get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');
...但我的问题是:我可以在路由中间添加一个可选参数吗?
推荐答案
没有.可选参数需要放在路由的末尾,否则 Router 将不知道如何将 URL 与路由匹配.您已经实施的是正确的做法:
No. Optional parameters need to go to the end of the route, otherwise Router wouldn't know how to match URLs to routes. What you implemented already is the correct way of doing that:
get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');
你可以尝试用一条路线来做:
You could try doing it with one route:
get('things/{id}/entities', 'MyController@doSomething');
并传递 * 或 0 如果您想获取所有事物的实体,但我将其称为 hack.
and pass * or 0 if you want to fetch entities for all things, but I'd call it a hack.
还有一些其他的 hack 可以让您为此使用一个路由,但这会增加您的代码的复杂性,而且真的不值得.
There are some other hacks that could allow you to use one route for that, but it will increase the complexity of your code and it's really not worth it.
这篇关于路由中间的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!