symfony SerializerInterface 序列化器参数

symfony SerializerInterface serializer argument

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

我正在尝试 return 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

config.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

之前死去

但同样的错误

谢谢

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

/**
 * @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, []);
}

希望对您有所帮助

它的发生只是因为我在 services.yml

上没有这个
  AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller/*'
        public: true
        tags: ['controller.service_arguments']