middlewares / request-handler

PSR-15 middleware to execute request handlers
MIT License
46 stars 4 forks source link

Route specific middleware #10

Open mtvbrianking opened 5 years ago

mtvbrianking commented 5 years ago

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(),
    new AuraRouter($routerContainer),
    new RequestHandler($requestContainer),
]);

$response = $dispatcher->dispatch($request);
oscarotero commented 5 years ago

The array you're providing is not callable. A way to use an array of routes as a single callable is as the following:

$map->get('index', '/', new Dispatcher([
    new SampleRouteMiddleware(),
    'App\Http\Controllers\HomeController::index'
]));

As you can see, Dispatcher implements also RequestHandlerInterface so you can use it to group a list of callables in a single request handler instance.