Given this path: /page(/:pageID)
, how can I allow the following variations:
/page
and /page/
(even if the pageID part is missing./page/1
and /page/1/
Thank you.
You must define your route this way:
$app->get('/page(/:id/?)', function ($id = NULL) use ($app) {
; // your code
});
The answer provided by @inst would not work here (Slim 2.0.0 running on XAMPP): /page/ gives out a 404.
This works in all four cases though:
$app->get('/page(/)(:id/?)', function ($id = NULL) use ($app) {
echo 'success';
});
As stated in the documentation, optional segments may be unstable depending on the usage. For example, with the answer given by Fabien Snauwaert, and the following routes:
/:controller(/)(:action(/)(:overflow+/?)) /:controller(/)(:action(/:overflow+/?))
If not filled all the arguments, when obtain param values, these will be in a position to the right, resulting in action == controller
and overflow == action
.
To prevent this, a simple solution is to put the optional slash at the end of the route.
/:controller(/:action(/:overflow+))/? /:controller(/:action(/:overflow+))(/)
And it is more readable, isn't it?
I can not comment on others answers, so I write here a detail concerning the Igor response.
One "problem" with this approach is that if the user tries to access a page that does not exist, and also do with a trailing slash, will be a 301 redirect to display a 404 page. Maybe a little weird.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With