php slim3框架中间件怎么获取controller中返回的数据

接口想返回一个统一的结构,想在路由处设置中间件,截获返回的数据,整合成一个统一的结构,
像这样:
return [
data: '截获返回的数据',
code:'错误码',
time:'时间'
];
但是不知道怎么做。。

阅读 4.8k
2 个回答

你取响应的数据正常在res里面取啊

->add(function(Request $req, Response $res, callable $next) {
    $source = $res->getBody()->getContent();
    return $res->withJson([
        "data" => $source,
        "code" => "xxx",
        "time" => "xxx"
    ]);
});

上代码:

$app->get('/path/to/do',function($request,$response,$args){
    $data = [
        'time'=>time(),
        'code'=>0,
        'data'=>[]
    ];
    return $response->withJson($data);
})->add(function($request,$response,$next){
    $reponse = $next($request,$response);
    //这个$response中就包含你的数据;
    //通过$response->getBody()->getContent();取得
    return $reponse;
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题