0

I've managed to use the request-handler combined with aura-router with a single router handler.

Am trying to implement route specific middleware, as opposed to the 'global' application middleware.

$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();

// Works fine...
$map->get('index', '/', 'App\Http\Controllers\HomeController::index');

// Error: Invalid request handler: array
$map->get('index', '/', [
    new SampleRouteMiddleware(),
    'App\Http\Controllers\HomeController::index'
]);

$request = ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);

$requestContainer = new RequestHandlerContainer();

$dispatcher = new Dispatcher([
    new SampleAppMiddleware(), // applies to all routes...
    new AuraRouter($routerContainer),
    new RequestHandler($requestContainer),
]);

$response = $dispatcher->dispatch($request);
bmatovu
  • 3,756
  • 1
  • 35
  • 37

1 Answers1

0

You cannot do what you want to with the PSR-15 implementation you are using. Your only option would to be write a Middleware with the following structure:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;

class SampleMiddleware implements Middlware
{
    public function process(Request $request, Handler $handler): Response
    {
        if ($this->supports($request)) {
             // Do something specific to your middleware
        }

        return $handler->handle($request);
    }

    public function supports(Request $request): bool
    {
        // Write the conditions that make the SampleMiddleware take action. i.e.,
        return $request->getPath() === "/sample";
    }

}

Only requests whose path is "/sample" will be processed by this middleware.

delolmo
  • 96
  • 8