2016-12-14 4 views
1

composer.json (의 일부) :심포니 3 FOS 나머지 + JMS 시리얼 그룹

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

내가 찾기 작업에 대한 목록 작업 및 전체에 대한 부분적인 데이터를 반환하고 싶습니다 몇 가지 요소를 가지고있다.

Product.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 나는 목록 결과에 group 속성을 표시하지 수 있도록하고 싶습니다

<?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); 
    } 
} 

: 그래서, 나는이 파일이 있습니다. 이를 위해 나는 주로 그룹과 함께 몇 가지 접근 방식을 시도했다.

  1. 그냥 내가 Groups({"List"}) 내 목록에 을 보여 @View(serializerGroups={"List"})으로 컨트롤러에서이 그룹을 참조 할 특성에 대해 그룹 이름을 구성하십시오. 그러나 모든 속성을 볼 수 있으므로이 경우에는 의 영향이 없습니다.
  2. 전체 엔터티에 대해 @ExclusionPolicy("all")을 구성해도 이 작동하지 않았습니다.
  3. ExclusionPolicy 외에도 을 일부 또는 모든 그룹에 표시하려고했지만 모든 속성을 으로 표시하려면 모든 속성에 대해 @Expose을 표시해야합니다.

나는 또한 이들 중 몇 가지 변종을 시도했지만 그 결과는 변하지 않았습니다. 컨트롤러 액션의

답변

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); 

이 심포니 3.2을 위해 일 것이다 FOSRest 2.1 및 2.0 . FOSRest에 대한 업그레이드 문서에 대한

링크 : https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md

0

당신이 @Exclude를 사용하는 경우 다음이 작동합니다.

fos_rest: 
    serializer: 
     groups: ['Default'] 

이 엔티티의 속성을 직렬화하기 위해 그룹 Default에 있어야합니다 : 내가 사용했던 또 다른 옵션은 config.yml에 작은 추가하는 것입니다. 속성에 @Groups 주석이없는 경우 Default에 있지만, @Groups 주석을 추가하면 더 구체적으로 추가하지 않는 한 Default 그룹에 더 이상 포함되지 않습니다.)

주석을 제외한 모든 엔티티 필드를 기본 직렬화 프로세스에 포함시킨 다음 모든 항목을 포함 시키려면 Default과 다른 그룹을 선택하여 직렬화 할 수 있습니다.

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