Symfony 3.1.7 + FOSRestBundle 最新版本
<?php
namespace PM\ApiBundle\Controller;
...
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
class ArticlesController extends FOSRestController
{
/**
* @ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* @Rest\View(serializerGroups={"article"})
* @Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* @var $articles Article[] */
return $articles;
}
然后我在我的 Article 实体中添加了这个注释 @Groups({"article"}) 和正确的使用声明。
我得到的默认序列化程序:
[
[],
[]
]
我得到了 Whit JMS 序列化程序( bundle ):
{
"0": {},
"1": {}
}
(我在 db 中有两篇文章) 似乎无法识别“文章”组。当我使用没有此注释的默认序列化程序时,我得到一个循环错误。
怎么了?
[编辑] 与
相同的行为/**
* @ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* @Rest\View()
* @Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$context = new Context();
$context->addGroup('article');
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* @var $articles Article[] */
$view = $this->view($articles, 200);
$view->setContext($context);
return $view;
}
响应仍然是空的。
最佳答案
您可以保留 symfony 的默认序列化程序。不需要 JMSSerializer。
你可能忘记在 config.yml (https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations) 中激活序列化器的注解
#app/config/config.yml
framework:
....
serializer: { enable_annotations: true }
需要在config.yml中强制view_response_listener ( http://symfony.com/doc/master/bundles/FOSRestBundle/3-listener-support.html , http://symfony.com/doc/master/bundles/FOSRestBundle/view_response_listener.html )
#app/config/config.yml
fos_rest:
view:
view_response_listener: 'force'
应该可以!
关于php - 组注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999006/