How to use

Use the Slim application’s add() instance method to add new middleware to a Slim application. New middleware willsurround previously added middleware, or the Slim application itself if no middleware has yet been added.

Example Middleware

This example middleware will capitalize the Slim application’s HTTP response body.

  1. <?php
  2. class AllCapsMiddleware extends \Slim\Middleware
  3. {
  4. public function call()
  5. {
  6. // Get reference to application
  7. $app = $this->app;
  8. // Run inner middleware and application
  9. $this->next->call();
  10. // Capitalize response body
  11. $res = $app->response;
  12. $body = $res->getBody();
  13. $res->setBody(strtoupper($body));
  14. }
  15. }

Add Middleware

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->add(new \AllCapsMiddleware());
  4. $app->get('/foo', function () use ($app) {
  5. echo "Hello";
  6. });
  7. $app->run();

The Slim application’s add() method accepts one argument: a middleware instance. If the middleware instance requiresspecial configuration, it may implement its own constructor so that it may be configured before it is added to theSlim application.

When the example Slim application above is run, the HTTP response body will be an enthusiastic “HELLO”;