概览

If your Slim Framework application does not have a route that matches the current HTTP request URI, the application invokes its Not Found handler and returns a HTTP/1.1 404 Not Found response to the HTTP client.

Default Not Found handler

Each Slim Framework application has a default Not Found handler. This handler sets the Response status to 404, it sets the content type to text/html, and it writes a simple explanation to the Response body.

Custom Not Found handler

A Slim Framework application’s Not Found handler is a Pimple service. You can substitute your own Not Found handler by defining a custom Pimple factory method with the application container.

  1. $app['notFoundHandler'] = function ($c) {
  2. return function ($request, $response) use ($c) {
  3. return $c['response']->withStatus(404)
  4. ->withHeader('Content-Type', 'text/html')
  5. ->write('Page not found');
  6. };
  7. };

In this example, we define a new notFoundHandler factory that returns a callable. The returned callable accepts two arguments:

  1. A \Psr\Http\Message\RequestInterface instance
  2. A \Psr\Http\Message\ResponseInterface instance

The callable MUST return an appropriate \Psr\Http\Message\ResponseInterface instance.