我正在探索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
不需要使用规范化器。
您已经为属性(get-product
和get-products
,)定义了序列化组。
现在,您只需要声明每个操作都在使用它们。或为资源定义默认的规范化上下文,并为应该使用其他序列化组的操作覆盖它。
例如:
/**
* @ApiResource(
* normalizationContext={"groups"={"get-product"}},
* denormalizationContext={"groups"={"user", "user:write"}},
* collectionOperations={
* "get"={
* "security"="is_granted('ROLE_PRODUCTS')",
* "normalization_context"={"groups"={"get-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')"},
* },
* )
*/
使用以上内容,默认情况下,您将使用get-product
序列化组进行响应,但使用GET
序列化组的集合get-products
操作除外。
((我通常不通过注释编写我的配置,因此希望我不会引入任何意想不到的错误,但是即使有错误的错别字,也应该打赌你去。)