2017-02-26 75 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对象,你返回$结果。

相关问题