I've done some looking and can't seem to figure out how to have an optional parameter in a URL segment in Silex. So I have this route currently:
/{controller}/{method}/{param}
The param wildcard is what I'd like to be optional. So this pattern would pick up URLs like
"Controller1/Method1" and "Controller2/Method2/Param"
Suggestions?
Just set up the processor for the longest URL possible (having all the parts, including optional ones), like this:
$app->get('/controller/{method}/{param}',
function($method, $param) {
// called both by `/controller/some-method/some-param-string`,
// `/controller/some-other-method`, and even `/controller`
});
By default, empty strings are assigned as values of the params that correspond to the omitted URL parts. But you can override this explicitly, as described in the doc:
$app->get('/page/{pageName}', function($pageName) {
// ...
})->value('pageName', 'index');
Now, when /page
is accessed, $pageName
is set to 'index'
.
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