简体   繁体   English

向PHP Slim 3响应添加状态

[英]Adding a status to PHP Slim 3 response

I have a piece of middleware in Slim 3 that validates a session for each route. 我在Slim 3中有一块中间件,可以验证每个路由的会话。 If validation fails, it returns a JSON object with { 'status' : false, 'error': 'failed validation' } . 如果验证失败,则返回带有{ 'status' : false, 'error': 'failed validation' }的JSON对象。 If validation passes, it adds 'status' : true to the response JSON object. 如果验证通过,它将'status' : true到响应JSON对象。

How do I insert an object property into the $response? 如何将对象属性插入$ response?

$app->add(function($request, $response, $next) {
    $valid = doExternalValidation();
    if ($valid == false) {
        return $response->withJSON(
            [ 'status' => false, 'errors' => 'failed validation' ]
        );
    }
    $response = $next($request, $response);
    $response->jsonBody['status'] = true;  // THIS IS WHAT I WANT TO DO
    return $response;
});

$app->get('/test', function ($request, $response, $args) {
    $data = [ "foo" => "bar" ];
    return $response->withJSON([ 'data' => $data ]);
});

How can I alter the middleware function so that I get { "status" : true, "data" : { "foo" : "bar" } } ? 如何更改中间件功能,以便获得{ "status" : true, "data" : { "foo" : "bar" } }

Solution: 解:

1) Rewind the Body, as on the back-side of the middleware the cursor of the body is at the end of the stream 1)倒回正文,因为在中间件的背面,正文的光标位于流的末尾

2) Decode the Body (rewind resets the cursor to the head of the message) 2)解码正文(倒带将光标重置为消息的开头)

3) Mutate the Entity 3)改变实体

4) Re-insert the Entity with withJson 4)用withJson重新插入实体

5) Return the new Json Response 5)返回新的Json Response

Sample code: 样例代码:

$app->add(function($request, $response, $next) {
    $valid = doExternalValidation();
    if ($valid == false) {
        return $response->withJSON(
            [ 'status' => false, 'errors' => 'failed validation' ]
        );
    }
    $response = $next($request, $response);

    $response->getBody()->rewind();
    $object = json_decode($response->getBody());
    $object['status'] = true;
    return $response->withJson($object);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM