Slim 3 Framework - setStatus 上的致命错误

Slim 3 Framework - Fatal Error on setStatus

我刚刚通过 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 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

在同一条线上。知道这里可能有什么问题吗?

你能试试下面的代码吗?

详情

  • 您有两次 $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();

使用 Slim 3,您将不会再调用 $response->setStatus(200);。就像 Valdek 已经提到的状态 200 是默认值,因此无需再次设置。

要 return 另一个状态代码(比如在你的 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();