Reputation: 1699
I just installed slim through composer and I'm trying to build a simple REST API.
My current code is the following:
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();
I had some Slim not found errors that I was able to pass, but now I'm getting the following Fatal Error and Notice when I try to access the endpoint on my browser:
Notice: Undefined property: Slim\App::$response in C:\xampp\htdocs\api\index.php on line 47 - the first setStatus
and
Fatal error: Call to a member function setStatus() on null in C:\xampp\htdocs\api\index.php on line 47
On the same line. Any idea on what might be wrong here?
Upvotes: 2
Views: 2574
Reputation: 337
Could you try the following code?
Details
$app = new \Slim\App();
twice. It is not right.$app
variable inside your code. The variable $response
has the instance to the Response
object.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();
Upvotes: 1
Reputation: 2666
With Slim 3 you will not call $response->setStatus(200);
anymore. Like Valdek already mentioned status 200 is the default so there's no need to set it again.
To return another status code (like in your catch branch) you have to use the withStatus
method:
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();
Upvotes: 0