Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Route Params in Silex

Tags:

php

routing

silex

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?

like image 556
Walter Cecil Worsley IV Avatar asked Apr 02 '14 04:04

Walter Cecil Worsley IV


1 Answers

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'.

like image 53
raina77ow Avatar answered Sep 22 '22 04:09

raina77ow