路由中间的可选参数

Optional parameter in the middle of a route(路由中间的可选参数)
本文介绍了路由中间的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在路由中间添加一个可选参数?

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.

这篇关于路由中间的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)