自定义类中的自定义响应代码超薄框架3

时间:2018-01-01 02:43:58

标签: php slim

嘿,我已经尝试了几天,我现在能够制作简单的API

$app->get('/articles/getcategories', function (Request $request, Response $response, array $args) {
(new Category) -> getCategories($response);
});

一个问题是当我想从我的班级向我的终点发送自定义响应代码时,在这种情况下类别类它不起作用,我能够使用这种方法发送响应:

$response -> getBody() -> write(json_encode($this -> makeObject(704, 'Something went wrong!')));

但是当我查看文档时:

$newResponse = $response->withStatus(302);
$data = array('name' => 'Rob', 'age' => 40);
$newResponse = $oldResponse->withJson($data, 201);

或者像这样:

return $response->withStatus(xxx);

它不起作用,这是我的自定义类

 public function getCategories($response){

    $dbconn = (new db())->connect();
        //start db connection
    try {
        $stmt = $dbconn->prepare("SELECT category_id, category_name, category_description, category_type FROM article_category");

        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $response->getBody()->write(json_encode($categories));

    } catch (PDOException $e){
        $response -> getBody() -> write(json_encode($this -> makeObject(704, 'Something went wrong!')));
    }

}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您的makeObject - 方法不会设置响应代码,它可能只会将其添加到响应对象。

您还需要设置http状态代码,然后返回响应because it is immutable

try {
    $stmt = $dbconn->prepare("SELECT category_id, category_name, category_description, category_type FROM article_category");

    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $response->getBody()->write(json_encode($categories));
    return $response; // uses default 200 response code (not needed but encouraged because without the return it can lead to problems later
} catch (PDOException $e){
    $response -> getBody() -> write(json_encode($this -> makeObject(704, 'Something went wrong!')));
    return $response->withStatus(704);
}

您还需要调整将新响应对象传递给Slim的路由

$app->get('/articles/getcategories', function (Request $request, Response $response, array $args) {
    return (new Category)->getCategories($response);
});

注意:你可以使用控制器,那么你只需要写一行而不是上面的3行,see this answer