我刚刚通过作曲家安装了slim,我正在尝试构建一个简单的REST API。
我目前的代码如下:
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/getPoiInitialList', function ($request, $response, $args) {
//$app = \Slim\Slim::getInstance();
$app = new \Slim\App();
try
{
$db = getDB();
$sth = $db->prepare("SELECT * FROM wikivoyage_pois LIMIT 50");
$sth->execute();
$poiList = $sth->fetchAll(PDO::FETCH_OBJ);
if($poiList) {
$app->response->setStatus(200);
$app->response()->headers->set('Content-Type', 'application/json');
echo json_encode($poiList);
$db = null;
} else {
throw new PDOException('No records found.');
}
} catch(PDOException $e) {
$app->response()->setStatus(404);
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
// Run app
$app->run();
我有一些Slim not found错误,我能够通过,但现在当我尝试在浏览器上访问端点时,我收到以下致命错误和通知:
Notice: Undefined property: Slim\App::$response in C:\xampp\htdocs\api\index.php on line 47 - the first setStatus
和
Fatal error: Call to a member function setStatus() on null in C:\xampp\htdocs\api\index.php on line 47
在同一条线上。对这里可能有什么问题有任何想法吗?
答案 0 :(得分:1)
您可以尝试以下代码吗?
<强>详情
$app = new \Slim\App();
两次。这不对。$app
变量。变量$response
具有Response
对象的实例。PHP
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/getPoiInitialList', function ($request, $response, $args) {
try
{
$db = getDB();
$sth = $db->prepare("SELECT * FROM wikivoyage_pois LIMIT 50");
$sth->execute();
$poiList = $sth->fetchAll(PDO::FETCH_OBJ);
if($poiList) {
$response->setStatus(200);
$response->headers->set('Content-Type', 'application/json');
echo json_encode($poiList);
$db = null;
} else {
throw new PDOException('No records found.');
}
} catch(PDOException $e) {
$response->setStatus(404);
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
// Run app
$app->run();
答案 1 :(得分:0)
使用Slim 3,您将不再致电$response->setStatus(200);
。像 Valdek 已经提到状态200是默认值,所以不需要再次设置它。
要返回另一个状态代码(例如在catch分支中),您必须使用withStatus
方法:
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/getPoiInitialList', function ($request, $response, $args) {
try
{
[...]
} catch(PDOException $e) {
return $response->withStatus(404, $e->getMessage());
}
});
// Run app
$app->run();