1

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 ?

monkeyUser
  • 4,301
  • 7
  • 46
  • 95
  • So you want to provide the data in the controller but json decode it inside the middleware after the controller got executed? – jmattheis Jul 23 '16 at 08:48
  • @jmattheis exactly, I'd like to pass Response to Middleware and the middleware evaluate Response ( 200, 404, 500 ) and create the right Json Response. is it a good practice about middleware? Thanks ! – monkeyUser Jul 23 '16 at 12:04
  • I dont this this is a good practice, this should all be done inside the route. – jmattheis Jul 23 '16 at 12:19
  • @jmattheis What Can I handle with middleware? I can handle Authentication, but I Read that I can use middleware for Error Handling. how Can I do it if The exception is inside Controller? – monkeyUser Jul 23 '16 at 14:05
  • There are error handler inside slim see [documentation](http://www.slimframework.com/docs/handlers/error.html) – jmattheis Jul 23 '16 at 14:22
  • @jmattheisyes I know, error handler is only an example about middleware – monkeyUser Jul 24 '16 at 12:48

0 Answers0