Symfony2, FOSRestBundle. How to use group with JMSSerializerBundle?

╄→гoц情女王★ 提交于 2019-11-29 04:09:18

As reminder, Groups in JMSSerializer are used as exclusion strategy.

An exclusion strategy consists to a specific approach used to expose/exclude properties depending on condition/context.

In order to use them correctly, the first thing you have to do is exclude all properties of your entity :

// ...
use JMS\Serializer\Annotation as JMS;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @JMS\ExclusionPolicy("all")
 */
class User extends BaseUser

Now, you have explicitly expose properties depending on Groups :

/**
 * @ORM\Column(type="string", length=255, nullable=true, unique=false)
 * @JMS\Groups({"default"}) // Idem for all properties you want render in group "default"
 */
protected $name;

/**
 * @ORM\Column(type="string", length=255, nullable=true, unique=false)
 * @JMS\Groups({"notification"})
 */
protected $deviceId;

Then, you have to define the used Group in your controller action :

/**
 * Get list of Admins
 * @Annotations\Get("/api/v1/admins", name="list_of_admins")
 * @Annotations\View(serializerGroups={"default", "notification"}) // Here set the Group used
 * @return \FOS\RestBundle\View\View
 */
public function getAdminsAction()
{
    if(!$this->isGranted('ROLE_ADMIN')){
        throw new AccessDeniedException('Only for Admin');
    }

    $admins = $this->getDoctrine()->getRepository('AppBundle:User')->findByRole('ROLE_ADMIN');

    return $this->view(['data' => $admins], Codes::HTTP_OK);
}

Now, $admins contains only the properties exposed to the group default and notification.

You can also do it manually instead of use an annotation :

$view = $this->view($admins, 200);
$view->setSerializerGroups(array('default', 'notification'));

return $this->handleView($view);

For more informations, see Exclusion strategies .

I hope it's clear for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!