【问题标题】:Symfony 3 FOS Rest + JMS Serializer groupsSymfony 3 FOS Rest + JMS 序列化程序组
【发布时间】:2016-12-14 01:37:42
【问题描述】:

我的composer.json(部分):

{
    "require": {
        "symfony/symfony": "3.1.*",
        "jms/serializer-bundle": "^1.1",
        "friendsofsymfony/rest-bundle": "^2.1"
    }
}

我有一些实体,我想为列表操作返回部分数据并为查找操作完成。为此,我有这些文件:

产品.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
* @ORM\Entity
* @ORM\Table(name="represented")
* @JMS\ExclusionPolicy("ALL")
*/
class Product
{
    /**
    * @var integer
    * @ORM\Column(type="integer", nullable=false, options={"unsigned"=true})
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @var string
    * @ORM\Column(type="string", nullable=false, length=48)
    */
    protected $name;

    /**
    * @var Group
    * @ORM\ManyToOne(targetEntity="Group", inversedBy="products")
    * @ORM\JoinColumn(name="group_id", referencedColumnName="id")
    */
    protected $group;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setGroup(Group $group)
    {
        $this->group = $group;
    }

    public function getGroup()
    {
        return $this->group;
    }
}

ProductController.php

<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;

class ProductController extends FOSRestController
{
    /**
    * @Get("/product", name="list_products")
    */
    public function listAction()
    {
        $products = $this->getDoctrine()
            ->getRepository('AppBundle:Product')
            ->findBy([], [ 'name' => 'ASC' ]);

        $view = $this->view($products);

        return $this->handleView($view);
    }

    /**
    * @Get("/product/{id}", requirements={"id" = "\d+"}, name="get_product")
    */
    public function getAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $product = $em->getRepository('AppBundle:Product')
            ->find($id);

        if ( ! $product) {
            $error = [
                'error' => 'Product not found'
            ];

            $view = $this->view($error, 404);
        } else {
            $view = $this->view($product);
        }

        return $this->handleView($view);
    }
}

我希望能够不在列表结果中显示group 属性。为此,我尝试了一些方法,主要是与组。

  1. 只需为我要显示的属性配置组名 在我的名单上Groups({"List"}) 并在 控制器@View(serializerGroups={"List"})。但这并没有 影响,因为所有属性都是可见的。
  2. 没有为整个实体配置@ExclusionPolicy("all") 也可以工作。
  3. 除了 ExclusionPolicy,@Expose 到我想要的所有属性 显示在部分或所有组中,但这使得所有属性都被标记 显示出来。

我还尝试了这些的更多变体,但没有改变结果。

【问题讨论】:

    标签: php symfony fosrestbundle jmsserializerbundle


    【解决方案1】:

    你的控制器动作的结束不应该只是:

    return $this->handleView($view);
    

    但是要让一个或多个组正常工作,您需要激活它们。在类之上,您需要添加 FOSRest 上下文,而不是 JMS 上下文:

    use FOS\RestBundle\Context\Context;
    

    并在返回视图之前的控制器操作中:

    $view = $this->view($products, 200);
    $context = new Context();
    $context->setGroups(['list']);
    $view->setContext($context);
    
    return $this->handleView($view);
    

    这适用于 Symfony 3.2 和 FOSRest 2.1 和 2.0。

    FOSRest 升级文档的链接: https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md

    【讨论】:

      【解决方案2】:

      如果您使用@Exclude,那么这应该可以。我使用的另一个选项是对config.yml 做一个小补充:

      fos_rest:
          serializer:
              groups: ['Default']
      

      这要求实体属性在组Default 中才能被序列化。如果属性上没有@Groups 注释,那么它将在Default 中,但是一旦添加@Groups 注释,它将不再在Default 组中(除非您专门添加它。 )

      这允许默认序列化过程包括所有实体字段,除了带有@Groups 注释的那些字段,然后如果我希望包含所有内容,我可以在其他地方同时使用Default 和我选择的其他组进行序列化。

      // Function in the Controller class
      public function getAction(MyEntity $me) {
          // Use automatic serializer, only things in 'Default' group are included
          return $me;
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 2013-05-23
        相关资源
        最近更新 更多