Symfony API控制器必须返回响应

时间:2017-02-26 16:05:25

标签: php api symfony

我创建了一个具有OneToMany关系的小crud系统,并且想要创建一个小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 / jobs时,我收到以下错误:

  

未捕获的PHP Exception LogicException:“控制器必须返回一个   响应(数组(0 =&gt;对象(DataBundle \ Entity \ Job),1 =&gt;   对象(DataBundle \ Entity \ Job))给出)。“

任何人都知道我在这里做错了什么?

感谢任何帮助!

非常感谢提前:)

3 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

如果有效,请告诉我们。

答案 1 :(得分: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
    );

答案 2 :(得分:0)

Controller必须返回一个Response对象,你将返回$ result。