2016-06-20 5 views
2

난 작곡가를 통해 슬림하게 설치했으며 간단한 REST API를 만들려고합니다. 나는 액세스하려고하면 나는 통과 할 수 있었다 약간 슬림 찾을 수없는 오류를했다Slim 3 Framework - 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

Claudio, 코드를 변경하십시오. $ app-> response() -> setStatus (404); ~ $ app-> response-> setStatus (404); –

+0

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

0

슬림 3를 사용하면 더 이상 $response->setStatus(200);를 호출하지 않습니다. 마찬가지로 Valdek 상태 200이 기본값이므로 다시 설정하지 않아도됩니다.

당신이 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(); 
관련 문제