如何在路由执行前后修改slim v3响应体?

时间:2016-10-25 15:17:00

标签: php slim

我无法在苗条v3中得到反应体,而且它总是空白。我的代码是:

<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\App as Slim;

require 'vendor/autoload.php';

$config['determineRouteBeforeAppMiddleware'] = true;

$app = new Slim(['settings' => $config]);

$mw = (function (Request $request, Response $response, callable $next) {
    $response = $response->withStatus(200)->write(' before ');
    $response = $next($request, $response);
    $body = $response->getBody()->getContents();
    $response = $response->withJson(array('data' => $body)); // output should be {"data":" Hello, User  seq1  seq2 "}
    return $response;
});

$mw1 = (function (Request $request, Response $response, callable $next) {
    $response = $next($request, $response);
    $response = $response->withStatus(200)->write(' seq1 ');
    return $response;
});

$mw2 = (function (Request $request, Response $response, callable $next) {
    $response = $next($request, $response);
    $response->withStatus(200)->write(' seq2 ');
    return $response;

});

$app->add($mw);

$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write(" Hello, $name ");
    return $response;
})->add($mw1)->add($mw2);

$app->run();

我想做的是以下内容:

  • 我不想在每条路径的末尾添加withJson()来编码我的json并输出到客户端(浏览器)。我希望中间件在(任何)路由执行结束后为我处理。
  • 我想得到最终的主体并将其分配给数组,如$ data [&#39; data&#39;] = $ body,然后json对其进行编码并返回修改后的响应。

P.S。 Slim v2比Slim v3容易得多。

3 个答案:

答案 0 :(得分:5)

尝试在中间件getContents()更改__toString()的{​​{1}}。应该在mw上进行另一项更改:您必须返回创建的新响应。

查看完整代码:

mw2

我希望它可以帮到你。

PS:我更喜欢Slim 3:D

答案 1 :(得分:2)

您也可以通过这种方式获取内容

方法#1

$streamBody = $response->getBody();
$streamBody->rewind();
$content = $streamBody->getContents();

方法#2

$streamBody = $response->getBody();
$streamBody->rewind();
$content = $streamBody->read($streamBody->getSize());

答案 2 :(得分:0)

  

我无法在苗条的v3中获得响应体,而且它总是空白。

我有同样的问题而且无法弄清楚为什么会得到空体反应,所以我最终将json_encode($my_value)添加到我的返回变量中,这就是魔法。现在我可以继续买一条新狗并可能结婚了。希望这有助于某人。

/**
 * method - GET
 */
$app->get('/posts[/]', function ($request, $response, $args) {
    $db = new DbHandler();
    // fetching all
    $result = $db->getAllPosts();
    return json_encode($result);
});

另一方面

/**
     * GetPosts
     */
    public function getAllPosts() {
    // Instantiate DBH
    // make a connection to mysql here
    $db = new PDO_Wrapper();
    $db->query("SELECT * FROM all_posts WHERE post_status = :Publish AND post_type = :Post ORDER BY post_date DESC");
    $binding_array = array(":Publish" => "publish", ":Post" => "post");
    $db->bindArray($binding_array);
    $results = $db->resultset();
    return $results;
    }
}