2017-02-26 60 views
1

我創建了一個OneToMany關係的小型垃圾回收系統,並且還想創建一個小型API。Symfony API控制器必須返回響應

我產生了新的ApiBundle並添加1個控制器爲我的實體1,看起來像這樣:

<?php 

namespace ApiBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use FOS\RestBundle\Controller\Annotations as Rest; 
use FOS\RestBundle\Controller\FOSRestController; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use FOS\RestBundle\View\View; 
use DataBundle\Entity\Job; 

class JobController extends FOSRestController 
{ 
    public function getAction() 
    { 
     $result = $this->getDoctrine()->getRepository('DataBundle:Job')->findAll(); 

     if ($result === null) { 
      return new View("There are no jobs in the database", Response::HTTP_NOT_FOUND); 
     } 

     return $result; 
    } 

    public function idAction($id) 
    { 
     $result = $this->getDoctrine()->getRepository('DataBundle:Job')->find($id); 

     if($result === null) { 
      return new View("Job not found", Response::HTTP_NOT_FOUND); 
     } 

     return $result; 
    } 

} 

但是,當我撥打電話到/ API /工作我得到以下錯誤:

Uncaught PHP Exception LogicException: "The controller must return a response (Array(0 => Object(DataBundle\Entity\Job), 1 => Object(DataBundle\Entity\Job)) given)."

任何人都知道我在做什麼錯在這裏?

任何幫助表示讚賞!

很多感謝:)

+1

https://symfony.com/doc/current/controller.html –

回答

0

你可以試試這個:

$view = $this->view($result, Response::HTTP_OK); 
return $view; 

讓我們知道,如果工程。

0

該錯誤告訴您要返回響應。事情是這樣的:

return new Response(
     'There are no jobs in the database', 
     Response::HTTP_OK 
    ); 

,或者如果你想有一個JSON響應,你可以做這樣的事情

return new JsonResponse(
     [ 
      'message' => 'There are no jobs in the database', 
     ] 
     Response::HTTP_OK 
    ); 
0

控制器必須返回一個Response對象,你返回$結果。

相關問題