【问题标题】:Custom response code in custom class | Slim Framework 3自定义类中的自定义响应代码 |超薄框架 3
【发布时间】:2018-01-02 01:07:50
【问题描述】:

嘿,我已经尝试 slim 好几天了,现在我可以像这样制作简单的 API

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

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

$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!')));
    }

}

我在这里做错了什么?

【问题讨论】:

  • 您尝试return try/catch 块中的新响应对象吗?
  • 你在哪里设置响应码?

标签: php slim


【解决方案1】:

您的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

【讨论】:

  • 我最终使用了您所说的控制器,因为它更清洁,我一开始并没有使用它,因为我认为它更清洁、更容易。所以我会接受你的回答。
猜你喜欢
  • 2023-03-21
  • 2021-01-30
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多