Skip to content
On this page

Middleware

Forme supports PSR 15 Middleware for all route types as well as Template controllers.

Your middleware should implement Psr\Http\Server\MiddlewareInterface.

php
<?php
declare(strict_types=1);

namespace App\Foo\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class FooMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        \Forme\log()->info('hello world foo middleware');
        return $handler->handle($request);
    }
}

To avoid reinventing the wheel, there are many open source PSR 15 middleware libraries that you can use in your app.

Adding Middleware to Routes

You can use the addMiddleware method to add and chain middleware onto your routes.

php
// routes/routes.php
// add middleware can take either a class string or an instance
Router::get('foo/:bar', FooController::class)->addMiddleware(FooMiddleware::class);
// you can chain them to add more than one
Router::post('foo/:bar', FooController::class)->addMiddleware(FooMiddleware::class)->addMiddleware(BarMiddleware::class);

Adding Middleware to Template Controllers

Since template controllers rely on core WordPress routing rather than our defined routes, you can add middleware directly to the controller itself. There are two ways of doing this.

The preferred method is to set the $middlewareQueue property.

php
protected $middlewareQueue = [
        'App\\Foo\\Middleware\\FooMiddleware',
    ];

Alternatively you can also set middleware dynamically within the controller's __construct() method.

php
public function __construct()
{
    //...
    $this->addMiddleware(FooMiddleware::class);
}

First In First Out

The middleware is dispatched in "first in first out" order unlike some other implementations, which is a little easier to reason about - the order you see in the queue is exactly what you will get!

You can read more about the routing implementation here.

Code Generation

You can create an empty middleware class using the code generation cli.

bash
forme make middleware FooBar

Made by Moussa Clarke @ Sanders Web Works with ❤️