4

我正在尝试设置不同的组以根据上下文实现我的实体的不同类型的序列化。

我的配置如下所示:

My\FooBundle\Entity\Asset:
    exclusion_policy: ALL
    access_type: public_method
    properties:
        id:
            access_type: property
            expose: true
            groups: [fnord]
        name:
            expose: true
        path:
            expose: true
        isInQuarantine:
            expose: true
            groups: [baz]

我希望除非设置了组,否则不应公开具有属性的组。

我正在尝试通过以下方式在我的控制器中设置组:

    $view->setSerializationContext(SerializationContext::create()->setGroups(array('fnord')));

然而,对于暴露的和不暴露的没有影响。即使我不尝试更改SerializationContextgroups选项似乎总是被忽略。

我知道我的配置正在运行,因为我可以通过公开标志切换属性。

然而我在这里做错了什么?

4

1 回答 1

2

我知道这个问题有点老了,但它可能对其他人有所帮助。我遇到了类似的问题。这是因为我的控制器(扩展了 FOSRestControler)中有一个方法可以多次调用

$this->getView()

你必须注意到这个方法创建了一个新的 View 对象。

这意味着,如果您调用多个 getView 方法,上下文将被重置。

查看适用于我的应用的以下代码:

use FOS\RestBundle\Controller\FOSRestController as Controller;    
class RestController extends Controller
{
   public function getUserAction($username)
    {
        $view = $this->view();
        $view->setSerializationContext(SerializationContext::create()->setGroups(array('Product')));

        $user = $this->getDoctrine()->getManager()->getRepository('VendorUserBundle:User')->findOneByUsername($username);
        if(!is_object($user))
        {
            throw $this->createNotFoundException();
        }
        $view->setData($user);
        return $view;
    }
}

在 Model.User.yml 文件中:

FOS\UserBundle\Model\User:
    exclusion_policy: ALL
    properties:
        username:
            expose: true
            groups: [fnord]
        email:
            expose: true
            groups: [Product]
        enabled:
            expose: true
            groups: [Product]
        roles:
          expose: true
          groups: [Product]

给出以下输出:

{"email":"guiguiboy@xxx.com","enabled":true,"roles":["ROLE_XXX"]}

我没有任何与缓存相关的问题(使用了开发环境)。

于 2014-12-17T10:32:23.637 回答