Middlewares for Apitte (opens new window).

Transform and validate request or early return response before it is handled by dispatcher.

# Content

# Setup

First of all, setup core (opens new window) and contributte/middlewares (opens new window) packages.

Install and register middlewares plugin

composer require apitte/middlewares
1
api:
    plugins:
        Apitte\Middlewares\DI\MiddlewaresPlugin:
1
2
3

In index.php replace Apitte\Core\Application\IApplication with Contributte\Middlewares\Application\IApplication.

# Configuration

TracyMiddleware (opens new window) (with priority 100) and AutoBasePathMiddleware (opens new window) (with priority 200) are registered by default, but you could disable them if you want.

api:
    plugins:
        Apitte\Middlewares\DI\MiddlewaresPlugin:
            tracy: true
            autobasepath: true
1
2
3
4
5

Apitte\Middlewares\ApiMiddleware which run whole Apitte application is registered with priority 500. Make sure there is no middleware with higher priority.

# Middlewares

If you want to add another middleware, just register a class with appropriate tags.

services:
    m1:
        factory: App\Api\Middleware\ExampleMiddleware
        tags: [middleware: [priority: 10]]
1
2
3
4
namespace App\Api\Middleware;

use Contributte\Middlewares\IMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class ExampleMiddleware implements IMiddleware
{

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
    {
    	// Call next middleware in a row
        $response = $next($request, $response);
        // Return response
        return $response;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

See contributte/middlewares (opens new window) documentation for more info and useful middlewares