Parameters

You can embed parameters into route resource URIs. In this example, I have two parameters in myroute URI, “:one” and “:two”.

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/books/:one/:two', function ($one, $two) {
  4. echo "The first parameter is " . $one;
  5. echo "The second parameter is " . $two;
  6. });

To create a URL parameter, prepend “:” to the parameter name in the route URI pattern. When the route matches thecurrent HTTP request, the values for each route parameter are extracted from the HTTP request URI and are passedinto the associated callback function in order of appearance.

Wildcard route parameters

You may also use wildcard route parameters. These will capture one or many URI segments that correspond to the routepattern’s wildcard parameter into an array. A wildcard parameter is identified by a “+” suffix; it otherwise actsthe same as normal route parameters shown above. Here’s an example:

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/hello/:name+', function ($name) {
  4. // Do something
  5. });

When you invoke this example application with a resource URI “/hello/Josh/T/Lockhart”, the route callback’s $nameargument will be equal to array('Josh', 'T', Lockhart').

Optional route parameters

Heads Up! Optional route segments are experimental. They should only be used in the manner demonstrated below.

You may also have optional route parameters. These are ideal for using one route for a blog archive. To declareoptional route parameters, specify your route pattern like this:

  1. <?php
  2. $app = new Slim();
  3. $app->get('/archive(/:year(/:month(/:day)))', function ($year = 2010, $month = 12, $day = 05) {
  4. echo sprintf('%s-%s-%s', $year, $month, $day);
  5. });

Each subsequent route segment is optional. This route will accept HTTP requests for:

  • /archive
  • /archive/2010
  • /archive/2010/12
  • /archive/2010/12/05If an optional route segment is omitted from the HTTP request, the default values in the callback signature areused instead.

Currently, you can only use optional route segments in situations like the example above where each route segment issubsequently optional. You may find this feature unstable when used in scenarios different from the example above.