php - slim/twig-view Won't Work With Additional Route Middleware
one text
I've been using slim/twig-view, documented here: https://notes.enovision.net/slim/composer-package-documentation/slim_twig-view. The recommended way to handle a route, render a view is:
$app->get('/hello/{name}', function ($request, $response, $args) {
$view = Twig::fromRequest($request);
return $view->render($response, 'profile.html', [
'name' => $args['name']
]);
})
Problem is, if you try to add any route based middleware to run afterwards, it fails
$app->get('/hello/{name}', function ($request, $response, $args) {
$view = Twig::fromRequest($request);
return $view->render($response, 'profile.html', [
'name' => $args['name']
]);
})->add(function(Request $request, RequestHandler $handler){
$response = $handler->handle($request);
return $response;
});
With an error like this:
Type: TypeError
Code: 0
Message: Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, int returned
File: /var/www/html/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php
Line: 43
I see this is because I'm not returning a response from the route handler, so I rewrite the route handler to return the $response:
$view = Twig::fromRequest($request);
$view->render($response, 'profile.html', [
'name' => $args['name']
]);
return $response;
Still the same error.
I can work around this, but it's a greenfield project and it would be nice to have access to route middleware. Any ideas?
Source