是否可以在路线中间添加可选参数?
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');...但是我的问题是:我可以在路线中间添加可选参数吗?
... but my question is: Can I add an optional parameter in the middle of a route?
推荐答案否.可选参数需要放在路由的末尾,否则路由器将不知道如何将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.
还有其他一些骇客可以让您使用一种途径,但这会增加代码的复杂性,这确实不值得.
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.
更多推荐
路线中间的可选参数
发布评论