Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

php - Optional parameter in the middle of a route

Is there any way to add an optional parameter in the middle of a route ?

Example routes:

/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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...