我使用的是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
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之前死掉
但同样的错误
谢谢
发布于 2017-06-23 22:51:18
action方法可以通过请求转换请求属性或参数(您需要的服务应该从容器中检索),因此请尝试以下代码:
/**
* @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-23 23:09:59
它的发生只是因为我在services.yml上没有这个
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller/*'
public: true
tags: ['controller.service_arguments']
https://stackoverflow.com/questions/44724202
复制相似问题