You can run code before and after your Wiggum application to manipulate the Request and Response objects as you see fit. This is called middleware. Why would you want to do this? Perhaps you want to protect your app from cross-site request forgery. Maybe you want to authenticate requests before your app runs. Middleware is perfect for these scenarios.

What is middleware?

Technically speaking, a middleware is a callable that accepts three arguments:

  • \wiggum\http\Request
  • \wiggum\http\Response
  • callable - The next middleware callable

It can do whatever is appropriate with these objects. The only hard requirement is that a middleware MUST return an instance of \Psr\Http\Message\ResponseInterface. Each middleware SHOULD invoke the next middleware and pass it Request and Response objects as arguments.

How do I write middleware?

Middleware is a callable that accepts three arguments: a Request object, a Response object, and the next middleware. Each middleware MUST return an instance of \Psr\Http\Message\ResponseInterface.

<?php
/**
 * Example middleware closure
 *
 * @param  \wiggum\http\Request $request 
 * @param  \wiggum\http\Response $response
 * @param  callable $next     Next middleware
 *
 * @return \wiggum\http\Response
 */
function ($request, $response, $next) {
    echo 'BEFORE';
    $response = $next($request, $response);
	echo 'AFTER';

    return $response;
};
?>

How do I add middleware?

All of the middleares for the Wiggum framework are stored in the middleware file usally stored in app/boot/middleware.php.

Middleware is invoked for every incoming HTTP request. Add application middleware with the Wiggum application instance’s addMiddleware() method:

<?php
$app->addMiddleware(function ($request, $response, $next) {
	echo 'BEFORE';
	$response = $next($request, $response);
	echo 'AFTER';

	return $response;
});
?>