我刚刚通过composer安装了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找不到的错误,但是我现在可以通过浏览器访问端点时收到以下致命错误和注意事项:
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
在同一行上。对这里可能出什么问题有任何想法吗?
您可以尝试以下代码吗?
细节
$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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句