gpt4 book ai didi

php - 如何防止 doctrine2 返回某些字段

转载 作者:行者123 更新时间:2023-12-02 01:02:00 27 4
gpt4 key购买 nike

我编写的代码是与 Doctrine 的一对多关系

一个用户--->有很多通知

这是我获取数据的方式

/**
* @Route("/test")
*/
public function testRoute()
{
//get the user notifications
$notifications = $this->getUser()->getNotifications();

//return json response
$serializer = $this->get('serializer');
$json = $serializer->serialize($notifications, 'json');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}

这是 Controller 返回的内容

    [
{
"id": 1,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2I==",
"email": "ga@ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"salt": "Lqch0N84UH1QmFI5O",
"form_token": "sO6NgWd",
"is_active": true,
"registration_confirmation": "success",
"secret_confirmation_id": "qTwNGm4CSKHzJOe8ry9DcXavt",
"socket_token": "KuMlxYHa"
},
"created_at": "2014-12-16T13:36:20+0100",
"link_to": "#test"
},
{
"id": 2,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2IYX1DONLA/70a8hzMUQ==",
"email": "ga@ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"profile_rank": "Beginner", (...)
},
"created_at": "2014-12-16T13:36:24+0100",
"link_to": "#test"
}
]

我想你明白了,它返回某个用户的通知,没关系,我还需要用户的某些字段,如姓氏和名字,以便返回的数据在应用程序中可用。但 doctrine 还会返回散列密码和盐以及用户不需要知道的 token 和信息。

我如何告诉 doctrine 不要返回这些字段或不要从一开始就获取它们?

最佳答案

这与 Doctrine 无关,这是默认的 Serializer,它会尝试获取并返回所有可用的值。

看看 Serializer component documentation了解如何忽略属性。基本上,您必须将规范化程序传递到序列化程序的构造函数中:

<?php
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

$normalizer = new GetSetMethodNormalizer();
$normalizer->setIgnoredAttributes(array('age'));
$encoder = new JsonEncoder();

$serializer = new Serializer(array($normalizer), array($encoder));
$serializer->serialize($person, 'json');

此外,我强烈建议切换到 JMSSerializer和/或使用 FOSRestBundle ,因为它为序列化提供了更多的灵 active 。属性列表是根据上下文配置的,并且具有基本的排除策略。这样,您只需要列出要公开的属性,而不是排除:

AppBundle\Entity\Car:
exclusion_policy: all
properties:
id:
expose: true
vendor:
expose: true
title:
expose: true

在给定的示例中,所有未列出的属性都将被排除。

关于php - 如何防止 doctrine2 返回某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27523492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com