Php 自定义类| Slim Framework 3中的自定义响应代码
嘿,我已经尝试slim好几天了,现在我可以像这样制作简单的API了Php 自定义类| Slim Framework 3中的自定义响应代码,php,slim,Php,Slim,嘿,我已经尝试slim好几天了,现在我可以像这样制作简单的API了 $app->get('/articles/getcategories', function (Request $request, Response $response, array $args) { (new Category) -> getCategories($response); }); 一个问题是,当我想从我的类向我的端点发送自定义响应代码时,在这种情况下,Category类不起作用,我可以使用以下方法发送
$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!')));
}
}
我在这里做错了什么?您的
makeObject
-方法不会设置响应代码,它可能只是将其添加到响应对象中
您还需要设置http状态码,然后返回响应
您还需要调整路由,使其将新的响应对象传递给Slim
$app->get('/articles/getcategories', function (Request $request, Response $response, array $args) {
return (new Category)->getCategories($response);
});
注意:你可以使用控制器,那么你只需要写一行而不是上面的3行,你是否尝试在
try/catch
块中return
新的响应对象?你在哪里设置响应代码?我像你说的那样使用控制器,因为它更干净,我一开始没有用它,因为我觉得它更干净更容易。所以我会接受你的回答。
$app->get('/articles/getcategories', function (Request $request, Response $response, array $args) {
return (new Category)->getCategories($response);
});