Search code examples
phpiphonejsonsymfony1

Symfony Routing - Optional parameters


I'm creating a Symfony project that outputs JSON for consumption by an iPhone App.

I have a route set up:

notification_json:
  url: /notifications.json
  param: { module: notification, action: index, sf_format: json }

This currently lists all notifications (one of my models).

What I'd like to do is add some parameters to this, much like the Twitter API has 'since_id' - so if /notifications.json?since_id=3 was requested, only notifications with an ID higher than 3 would be shown.

I can't see me struggling with the action logic, but the routing for this kind of thing has me scratching my head a little!

Any help would be extremely appreciated.


Solution

  • If you don't specify any named parameters (eg :myparam) when defining a route in your routing.yml, then any parameters you add on when generating the route will be appended as normal GET variables. For example:

    notification_json:
      url: /notifications.json
      param: { module: notification, action: index, sf_format: json }
    

    used with:

    <?php echo url_for("@notification_json?since_id=3"); ?>
    

    will give you:

    /notifications.json?since_id=3
    

    If you add in named parameters into your route, then these will be substituted as normal, with any additional parameters tagged on the end as above, eg:

    notification_json_test:
      url: /:param1/notifications.json
      param: { module: notification, action: index, sf_format: json }
    

    used with:

    <?php echo url_for("@notification_json?param1=foo&since_id=3"); ?>
    

    will give you:

    /foo/notifications.json?since_id=3