Im new in SLimV3, And I Want to use the middleWare to create Json Output.
My code is: Controller:
public function __invoke(Request $request, Response $response, $args) {
....
$out['message'] = "ok";
$out['code'] = 0;
$response->withJson($out);
}
my route:
$app->get('/foo', App\Action\Foo::class)->add(new foo\Middleware());
my middleware
class Middleware{
public function __invoke(RequestInterface $request, ResponseInterface $response,$next) {
$started = microtime(true);
$response = $response->withHeader('Content-type', 'application/json');
$response = $next($request, $response);
$json = json_decode( (string) $response->getBody(),true);
$json['execution_time'] = microtime(true) - $started;
$newResponse = $response->withJson($json);
return $newResponse;
}
}
my Output is Ok,
{
"message": "ok",
"code": 0,
"execution_time": 0.44862484931946
}
but I don't like to create Json in my controller, Json Decode in middleware, and again $newResponse = $response->withJson($json);
. I'd like to read Response and create the response in middleware, or read the status code and create the custom Response.
Can I Do It ?