【问题标题】:How to get groups working for JMSSerializerBundle and FOSRestBundle?如何让组为 JMSSerializerBundle 和 FOSRestBundle 工作?
【发布时间】:2014-01-28 17:55:36
【问题描述】:

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

我的配置如下所示:

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 选项似乎总是被忽略。

我知道我的配置工作正常,因为我可以通过公开标志切换属性。

但是我在这里做错了什么?

【问题讨论】:

  • 似乎我再次受到某种缓存问题的打击。我也有带有登录设置的 FOSUSerBundle,现在,登录后它就可以工作了,我不知道为什么。吓人。

标签: symfony serialization fosrestbundle jmsserializerbundle


【解决方案1】:

我知道这个问题有点老了,但它可能对其他人有所帮助。 我遇到了类似的问题。 这是因为我在我的控制器(扩展 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"]}

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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多