【发布时间】:2020-04-10 23:08:31
【问题描述】:
我正在探索 Symfony API 平台。我想在获取产品列表时隐藏实体产品的一些属性。我已经创建了一个测试规范化器,但我的代码一直无视我。没有调用规范化器,所有数据都直接进入输出。请帮忙。
products.php
namespace App\Entity;
/**
* @ORM\Table(schema="new_api", name="products")
* @ORM\Entity(repositoryClass="App\Repository\ProductsRepository")
* @UniqueEntity("productName", message="The product name must be unique")
* @ApiResource(
* normalizationContext={"groups"={"get-product", "get-products"}},
* denormalizationContext={"groups"={"user", "user:write"}},
* collectionOperations={
* "get"={"security"="is_granted('ROLE_PRODUCTS')", },
* "post"={"security"="is_granted('ROLE_PRODUCTS_ADD')"}
* },
* itemOperations={
* "get"={"security"="is_granted('ROLE_PRODUCTS')"},
* "put"={"security"="is_granted('ROLE_PRODUCTS_EDIT')"},
* "patch"={"security"="is_granted('ROLE_PRODUCTS_EDIT')"},
* "delete"={"security"="is_granted('ROLE_PRODUCTS_EDIT')"},
* },
* )
*/
class Products
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue
* @Groups({"get-product", "get-products"})
*/
private $id;
/**
* @Groups({"get-product", "get-products"})
* @SerializedName("name")
* @ORM\Column(name="product_name", type="string", length=255, unique=true)
* @Assert\NotBlank(message="The product name cannot be empty")
*/
private $productName;
/**
* @Groups({"get-product"})
* @ORM\Column(name="description", type="text", length=65535, nullable=false)
*/
private $description;
}
services.yaml
'App\Serializer\ProductsNormalizer':
arguments: [ '@api_platform.serializer.normalizer.item' ]
tags: [ 'serializer.normalizer' ]
autoconfigure: false
【问题讨论】:
-
您不需要为此创建规范器。只需定义序列化组,并在该操作的规范化上下文中使用它们。没有其他事情可做。
-
您不需要像@yivi 所说的规范化器。但是你是否在 framework.yaml 文件中启用了序列化程序?
framework: serializer: enable_annotations: true
标签: php symfony serialization api-platform.com