我使用分形包打包了一些API方法來輸出內容。當我調用特定資源時,所有內容都將返回空白。分形API調用不返回內容
要檢查一切是否正常,我執行了一些內容變量的打印。例如,如果我在索引函數中使用$ incidents變量,我會按照預期返回數據庫中的所有條目。
當我在API控制器的respondWithCollection方法中調用$ collection變量時也是如此。數據也可以在這裏找到。但瀏覽器的輸出僅僅是這樣的:
{
"data": {
"headers": {}
}
}
爲了簡單起見,這是顯示數據庫的所有結果的方法:
class ApiIncidentsController extends ApiController {
protected $incidentTransformer;
protected $fractal;
function __construct(IncidentTransformer $incidentTransformer){
$this->incidentTransformer = $incidentTransformer;
$this->beforeFilter('auth.basic', ['on' => 'post']);
$this->fractal = new Manager();
parent::__construct($this->fractal);
}
public function index()
{
$incidents = Incident::all();
if(! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
return $this->respond([
'data' => $this->respondWithCollection($incidents, new IncidentTransformer),
]);
}
}
的API控制器來管理這些電話是這樣的:
class ApiController extends Controller {
protected $statusCode = 200;
protected $fractal;
public function __construct(Manager $fractal) {
$this->fractal = $fractal;
}
public function getStatusCode() {
return $this->statusCode;
}
public function setStatusCode($statusCode) {
$this->statusCode = $statusCode;
return $this;
}
public function respond($data, $headers = []) {
return Response::json($data, $this->getStatusCode(), $headers);
}
protected function respondWithItem($item, $callback) {
$resource = new Item($item, $callback);
$rootScope = $this->fractal->createData($resource);
return $this->respondWithArray($rootScope->toArray());
}
protected function respondWithArray(array $array, array $headers = []) {
return Response::json($array, $this->statusCode, $headers);
}
protected function respondWithCollection($collection, $callback) {
$resource = new Collection($collection, $callback);
$rootScope = $this->fractal->createData($resource);
return $this->respondWithArray($rootScope->toArray());
}
更新1 這是IncidentTransformer:
use League\Fractal\TransformerAbstract;
class IncidentTransformer extends TransformerAbstract {
public function transform(Incident $incident) {
return [
'incidentReference' => $incident['incidentReference'],
'latitude' => $incident['latitude'],
'longitude' => $incident['longitude'],
'archived' => (boolean) $incident['incidentArchived']
];
}
}
更新2 我嘗試別的東西,通過移除respond
包裝。然後一切都很好。但我想使用我寫的摘要代碼的響應函數。這似乎是問題。當我將數據傳入函數時,沒有任何東西被返回。當我轉儲變量數據時,返回了一個JSON響應。但是其中的respondWithCollection方法返回一個數組。我不明白爲什麼會發生這種情況。這可能是問題嗎?
I adapted the method like this:
public function index()
{
$incidents = Incident::all();
if(! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
$data = $this->respondWithCollection($incidents, new IncidentTransformer);
return $this->respond([
'data' => $data
]);
}
}
但仍然輸出爲空。所以它必須是具有響應功能的東西。
那麼你的事件變壓器的樣子? – ryanwinchester
我編輯了這個問題 – sesc360