Skip to content

Middleware

Pedro Faria edited this page Apr 14, 2017 · 5 revisions

Middlewares

Middleware is a mechanism to execute some code before or after request handler defined in your router.

Defining Middleware

With our LoggerMiddleware registered, now we have to write our middleware. Create a file app\Middlewares\LoggerMiddleware.php.

<?php
namespace App\Middlewares;

use Hope\Contracts\MiddlewareInterface;
use Monolog\Logger;
use \Closure;

class LoggerMiddleware implements MiddlewareInterface
{
    /**
     * @var Monolog\Logger
     */
    private $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function handle($request, Closure $next)
    {
        $this->logger->info($request->getMethod() . ': '. $request->getRequestUri());
        return $next($request);
    }
}

However, this middleware would perform its task after the request is handled by the application:

<?php
namespace App\Middlewares;

use Hope\Contracts\MiddlewareInterface;
use \Closure;

class MyMiddleware implements MiddlewareInterface
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        // Your code...
        return $response;
    }
}

Registering

$app->addMiddleware([
    'logger' => App\Middlewares\LoggerMiddleware::class
]);

$app->setRoute(function(Hope\Router\RouteColletor $route) {
    $route->get('/ping', function() { return ['pong' => true]; }, ['logger']);
});

Use the addMiddleware method to register all your middlewares.

CAUTION: This method must stay before bootstrap().

And that's it!

Now on every request to /ping URI, the LoggerMiddleware will be executed and write a info log.

Clone this wiki locally