简体   繁体   English

Symfony ApiPlatform:在实体中作为序列化程序/组的角色是个好主意吗?

[英]Symfony ApiPlatform: Role as Serializer/Groups in Entity is good idea?

I have many roles in the app, incl.我在应用程序中有很多角色,包括。 super_admin, admin, user, moderator, editor ... I want to use apiPlatform and display appropriate fields in entities appropriately for roles, I also made additional classes converting roles into classes. super_admin, admin, user, moderator, editor ... 我想使用 apiPlatform 并在实体中为角色适当地显示适当的字段,我还制作了额外的类将角色转换为类。 everything works.一切正常。 However, it breaks the idea of groups in the serializer.但是,它打破了序列化程序中组的概念。 For example: I have several entities that are related to each other.例如:我有几个相互关联的实体。 When I am an admin and want to download entities, all properties with the "admin: read" group will download + all properties from the related classes also with the "admin: read" group, even if I do not use them.当我是管理员并且想要下载实体时,所有具有“admin: read”组的属性都将下载+来自相关类的所有属性以及“admin: read”组,即使我不使用它们。 Is it okay?没关系吗? Is it a good idea to use roles in entities?在实体中使用角色是个好主意吗? There is another better way?还有另一种更好的方法吗?

Example from https://api-platform.com/docs/core/serialization/来自https://api-platform.com/docs/core/serialization/ 的示例

Class Book课本

<?php
// api/src/Entity/Book.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource(normalizationContext: ['groups' => ['book']])]
class Book
{
    /**
     * @Groups({"book"})
     */
    public $name;

    /**
     * @Groups({"book"})
     */
    public $author;

    // ...
}

Class Person班级人物

<?php
// api/src/Entity/Person.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource]
class Person
{
    /**
     * ...
     * @Groups("book")
     */
    public $name;

    // ...
}

And result结果

{
  "@context": "/contexts/Book",
  "@id": "/books/62",
  "@type": "Book",
  "name": "My awesome book",
  "author": {
    "@id": "/people/59",
    "@type": "Person",
    "name": "Kévin Dunglas"
  }
}

So if instead of "book" you type "admin: read" it will always serialize everything that has a group "admin: read".因此,如果您键入“admin:read”而不是“book”,它将始终序列化具有“admin:read”组的所有内容。 I think it's getting unnecessary data.我认为它正在获取不必要的数据。 I want to emphasize that there are a lot of entities, not like in the example of two / several.我想强调的是,实体有很多,而不是像两个/几个的例子。

我认为在序列化中添加角色是个好主意,但是当您在序列化中添加角色时,您应该装饰 api_platform.serializer.context_builder 请参阅此部分https://api-platform.com/docs/core/serialization/#change - 动态序列化上下文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM