Middleware

Slim enables you to associate middleware with a specific application route. When the given route matches the currentHTTP request and is invoked, Slim will first invoke the associated middleware in the order they are defined.

What is route middleware?

Route middleware is anything that returns true for is_callable. Route middleware will be invoked in the sequencedefined before its related route callback is invoked.

How do I add route middleware?

When you define a new application route with the Slim application’s get(), post(), put(), or delete() methodsyou must define a route pattern and a callable to be invoked when the route matches an HTTP request.

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

In the example above, the first argument is the route pattern. The last argument is the callable to be invoked whenthe route matches the current HTTP request. The route pattern must always be the first argument. The route callablemust always be the last argument.

You can assign middleware to this route by passing each middleware as a separate interior or… (ahem) middle…argument like this:

  1. <?php
  2. function mw1() {
  3. echo "This is middleware!";
  4. }
  5. function mw2() {
  6. echo "This is middleware!";
  7. }
  8. $app = new \Slim\Slim();
  9. $app->get('/foo', 'mw1', 'mw2', function () {
  10. //Do something
  11. });

When the /foo route is invoked, the mw1 and mw2 functions will be invoked in sequence before the route’s callableis invoked.

Suppose you wanted to authenticate the current user against a given role for a specific route. You could use someclosure magic like this:

  1. <?php
  2. $authenticateForRole = function ( $role = 'member' ) {
  3. return function () use ( $role ) {
  4. $user = User::fetchFromDatabaseSomehow();
  5. if ( $user->belongsToRole($role) === false ) {
  6. $app = \Slim\Slim::getInstance();
  7. $app->flash('error', 'Login required');
  8. $app->redirect('/login');
  9. }
  10. };
  11. };
  12. $app = new \Slim\Slim();
  13. $app->get('/foo', $authenticateForRole('admin'), function () {
  14. //Display admin control panel
  15. });

What arguments are passed into each route middleware callable?

Each middleware callable is invoked with one argument, the currently matched \Slim\Route object.

  1. <?php
  2. $aBitOfInfo = function (\Slim\Route $route) {
  3. echo "Current route is " . $route->getName();
  4. };
  5. $app->get('/foo', $aBitOfInfo, function () {
  6. echo "foo";
  7. });