Conditions

Slim lets you assign conditions to route parameters. If the specified conditions are not met, the route is not run.For example, if you need a route with a second segment that must be a valid 4-digit year, you could enforcethis condition like this:

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/archive/:year', function ($year) {
  4. echo "You are viewing archives from $year";
  5. })->conditions(array('year' => '(19|20)\d\d'));

Invoke the Route object’s conditions() method. The first and only argument is an associative array with keys thatmatch any of the route’s parameters and values that are regular expressions.

Application-wide route conditions

If many of your Slim application Routes accept the same parameters and use the same conditions, you can definedefault application-wide Route conditions like this:

  1. <?php
  2. \Slim\Route::setDefaultConditions(array(
  3. 'firstName' => '[a-zA-Z]{3,}'
  4. ));

Define application-wide route conditions before you define application routes. When you define a route, the routewill automatically be assigned any application-wide Route conditions defined with \Slim\Route::setDefaultConditions().If for whatever reason you need to get the application-wide default route conditions, you can fetch them with\Slim\Route::getDefaultConditions(). This static method returns an array exactly as the default route conditionswere defined.

You may override a default route condition by redefining the route’s condition when you define the route, like this:

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/hello/:firstName', $callable)
  4. ->conditions(array('firstName' => '[a-z]{10,}'));

You may append new conditions to a given route like this:

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/hello/:firstName/:lastName', $callable)
  4. ->conditions(array('lastName' => '[a-z]{10,}'));