【发布时间】: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!')));
}
}
我在这里做错了什么?
【问题讨论】:
-
您尝试
returntry/catch块中的新响应对象吗? -
你在哪里设置响应码?