2016-06-20 53 views
2

我剛剛通過作曲者安裝了slim,我試圖構建一個簡單的REST API。Slim 3框架 - setStatus上的致命錯誤

我當前的代碼如下:

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(); 

我有一些不修身發現錯誤,我是能夠通過,但現在我得到以下致命錯誤和通知時,我嘗試訪問端點上我的瀏覽器:

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 

在同一行。任何想法在這裏可能是錯誤的?

回答

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(); 
+0

與您的代碼,我取消的通知,但我仍然得到致命錯誤:調用未定義的方法Slim \ Http \ Response :: setStatus()。 –

+0

克勞迪奧,請更改代碼$ app-> response() - > setStatus(404);到$ app-> response-> setStatus(404); –

+0

http://docs.slimframework.com/response/status/ –

0

採用纖薄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();