1

我正在使用 symfony 3.3 的最新版本

我正在尝试返回 json,但出现错误

这是我的控制器:

<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;

class ApiController extends Controller{
    /**
     * @Route("home", name="api_home")
     */
    public function indexAction(SerializerInterface $serializer)
    {
        $entity = $this->getDoctrine()
            ->getRepository('AppBundle:User')
            ->findAll();
        $json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
        return new JsonResponse($json, 200, [], true);
    }
}

在 services.yml 上:

services:
  _defaults:
      public: false
      autowire: false
      autoconfigure: true

配置.yml

serializer:
    enabled: true
    enable_annotations: true

我收到错误:

Controller "AppBundle\Controller\ApiController::indexAction()" requires that you provide a value for the "$serializer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

我试着在 $json 之前死掉

但同样的错误

谢谢

4

2 回答 2

3

这只是因为我在 services.yml 上没有这个

  AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller/*'
        public: true
        tags: ['controller.service_arguments']
于 2017-06-23T15:09:58.910 回答
0

操作方法可以具有从请求转换的请求属性或参数(您需要从容器中检索的服务),因此请尝试以下代码:

/**
 * @Route("home", name="api_home")
 */
public function indexAction()
{
    $serializer = $this->get('serializer');
    $entity = $this->getDoctrine()
        ->getRepository('AppBundle:User')
        ->findAll();
    $json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
    return new JsonResponse($json, 200, []);
}

希望这有帮助

于 2017-06-23T14:51:17.867 回答