Frage

I have defined a route like below in Silex. I assume it can be done in symfony2 with annotations (conceptually).

$app->get('/get/all/entities/page/{page}/limit/{limit}', function ($page, $limit) use ($app) {

    // Build response 
    return new Response($response);

})->value('page', 1)->value('limit', 20);

With default values like above, how the route can be used without specifying the page and limit?

For example, if I define something like below, I can just browse to http://www.exmpale.com/get/all/entities/page and everything would be fine and the default value for page will be 1:

$app->get('/get/all/entities/page/{page}', function ($page) use ($app) {

        // Build response 
        return new Response($response);

    })->value('page', 1);
War es hilfreich?

Lösung

I tried the following:

$app->get('/page/{page}/{limit}', function($page, $limit) use ($app) {
    return 'Page: ' . $page . ', limit: ' . $limit;
})->value('page', 1)->value('limit', 30);

Here are the outputs I get for different urls:

  • http://localhost:8888/playground/silex/web/page ---> Page: 1, limit: 30
  • http://localhost:8888/playground/silex/web/page/3 ---> Page: 3, limit: 30
  • http://localhost:8888/playground/silex/web/page/54/100 ---> Page: 54, limit: 100

So, everything is working as expected, the values are correctly set. The problem with your url is the static part between the parameters ...{page}/limit/{limit}. If you have a static part between your parameters everything works, except that you cannot call the url with a default first parameter, at least I am not aware of any possible ways to do that

Andere Tipps

In Symfony2 this can be done very easily. Default values for placeholders are set in a routing file:

http://symfony.com/doc/current/book/routing.html#required-and-optional-placeholders

UPDATE:

In your case, your entry in routing file would look like this (YAML):

your_route:
    path:      /get/all/entities/page/limit
    defaults:  { _controller: YourBundle:YourController:YourAction, page: 1, limit: 2 }

From symfony documentation:

Of course, you can have more than one optional placeholder (e.g. /blog/{slug}/{page}), but everything after an optional placeholder must be optional. For example, /{page}/blog is a valid path, but page will always be required (i.e. simply /blog will not match this route).

http://symfony.com/doc/current/book/routing.html#required-and-optional-placeholders

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top