anzusystems/serializer-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

anzusystems/serializer-bundle

Composer 安装命令:

composer require anzusystems/serializer-bundle

包简介

Serializer bundle.

README 文档

README

A fast & light serializer bundle for symfony.

Install

composer require anzusystems/serializer-bundle

Usage

Simply inject AnzuSystems\SerializerBundle\Serializer via constructor, and then:

// Serialize object or iterable to json:
$this->serializer->serialize($dto);

// Deserialize json into object:
$this->serializer->deserialize($json, SerializerTestDto::class);

// Deserialize json into array of objects:
$this->serializer->deserialize($json, SerializerTestDto::class, []);

// Deserialize json into collection of objects:
$this->serializer->deserialize($json, SerializerTestDto::class, new ArrayCollection());

Default format for DateTimeInterface objects (de)serialization can be changed:

# config/packages/anzu_systems_serializer.yaml
anzu_systems_serializer:
  date_format: 'Y-m-d\TH:i:s.u\Z'

Attributes

To be able to (de)serialize objects, the property (or method) of that object must have AnzuSystems\SerializerBundle\Attributes\Serialize attribute.

    #[Serialize]
    private string $name;

    #[Serialize]
    private int $position;

    #[Serialize]
    private DummyDto $dummyDto;

    #[Serialize]
    private DateTimeImmutable $createdAt;

    // Custom date format used by `DateTime`. 
    #[Serialize(type: 'd.m.Y H:i:s')]
    private DateTimeImmutable $createdAtCustomFormat;

    // The valueObject must be an instance of `ValueObjectInterface`, to automatically (de)serialize.
    #[Serialize]
    private DummyValueObject $dummyValueObject;
    
    // The enum must be an instance of `EnumInterface`, to automatically (de)serialize.
    #[Serialize]
    private DummyEnum $dummyEnum;
    
    // Must be an instance of Symfony\Component\Uid\Uuid, to automatically (de)serialize.
    #[Serialize]
    private Uuid $docId;

    // Type (or discriminator map see below) must be provided for iterables in order to determine how to deserialize its items.
    #[Serialize(type: DummyDto::class)]
    private Collection $items;

    #[Serialize(type: DummyDto::class)]
    private array $itemsArray;

    // Serialize collection of entities as IDs ordered by position.
    #[Serialize(handler: EntityIdHandler::class, type: Author::class, orderBy: ['position' => Criteria::ASC])]
    protected Collection $authors;

    // Override type for deserialization based on provided "discriminator" field in json.
    #[Serialize(discriminatorMap: ['person' => Person::class, 'machine' => Machine::class])]
    private Collection $items;

    // Provide type via container parameter name. Example yaml config:
    // anzu_systems_serializer:
    //   parameter_bag:
    //     AnzuSystems\Contracts\Entity\AbstractUser: App\Entity\User
    #[Serialize(handler: EntityIdHandler::class, type: new ContainerParam(AbstractUser::class))]
    protected Collection $users;

    // (De)serialize a doctrine entity into/from IDs instead of (de)serializing whole object.
    #[Serialize(handler: EntityIdHandler::class)]
    private User $user;

    // Override the name of this property in json.
    #[Serialize(serializedName: 'stats')]
    private UserStats $decorated;

    // Serialize a virtual property (only serialization).
    #[Serialize]
    public function getViolations(): Collection

Built-in handlers

  • Auto-resolved handlers based on type:
    • BasicHandler (scalar values and null)
    • DateTimeHandler (date format configurable via settings)
    • EnumHandler (conversion between string and EnumInterface)
    • ObjectHandler (conversion of whole objects, i.e. embeds)
    • UuidHandler (conversion of Symfony Uuids)
  • Custom handlers:
    • EntityIdHandler (conversion of IDs into entities and back)
    • ArrayStringHandler (CSV into array: '1,2,3' or 'a, b,c' to [1, 2, 3] or ['a', 'b', 'c'])

To force a specific handler (override the auto-resolved handler), just specify the handler in the AnzuSerialize attribute.

#[Serialize(handler: ArrayStringHandler::class)]
private array $ids;

Custom handler.

To create a custom handler, simply extend the AnzuSystems\SerializerBundle\Handler\Handlers\AbstractHandler.

For instance in the following example a Geolocation class is converted to/from array:

use AnzuSystems\SerializerBundle\Context\SerializationContext;
use AnzuSystems\SerializerBundle\Handler\Handlers\AbstractHandler;

final class GeolocationHandler extends AbstractHandler
{
    /**
     * @param Geolocation $value
     */
    public function serialize(mixed $value, Metadata $metadata, SerializationContext $context): string): array
    {
        return [
            'lat' => $value->getLatitude(),
            'lon' => $value->getLongitude(),
        ];
    }

    /**
     * @param array $value
     */
    public function deserialize(mixed $value, Metadata $metadata): Geolocation
    {
        return new Geolocation(
            (float) $value['lat'],
            (float) $value['lon'],
        );
    }
}

Then just force the handler to be used for the property via attribute:

#[Serialize(handler: GeolocationHandler::class)]
private Geolocation $location;

In case you want always automatically all properties of the before-mentioned type Geolocation to be handled by the GeolocationHandler without forcing it via attribute, add following methods to the handler:

    public static function supportsSerialize(mixed $value): bool
    {
        return $value instanceof Geolocation;
    }

    public static function supportsDeserialize(mixed $value, string $type): bool
    {
        return is_a($type, Geolocation::class, true) && is_array($value);
    }

In case you want multiple automatic handlers that can both support the same thing, you can set priority with which the handler will be chosen. In that case, add the following method (higher priority will be chosen first):

public static function getPriority(): int
{
    return 3;
}

By default, all handlers have priority 0. Except: BasicHandler has highest priority (10) - this handles simple scalar values, so generally you want it to be first. ObjectHandler has lowest priority (-1) - this handles nested iterables/objects that no other handler supports.

Automatically generated API documentation via NelmioApiDocBundle

Model describer will be automatically registered if NelmioApiDocBundle is present. Symfony annotations are also supported/reflected in documentation. DocBlock titles are also added automatically as description for properties and methods.

In case you create a custom handler, you can override the generated description by adding the following method to the handler:

use AnzuSystems\SerializerBundle\Metadata\Metadata;
use OpenApi\Annotations\Property;

public function describe(string $property, Metadata $metadata): array
{
    $description = parent::describe($property, $metadata);
    $description['type'] = 'object';
    $description['title'] = 'Geolocation';
    $description['properties'] = [
        new Property([
            'property' => 'lon',
            'title' => 'Longitude',
            'type' => 'float',
            'minimum' => -180,
            'maximum' => 180,
        ]),
        new Property([
            'property' => 'lat',
            'title' => 'Latitude',
            'type' => 'float',
            'minimum' => -90,
            'maximum' => 90,
        ]),
    ];

    return $description;
}

Check out Property attribute for a list of supported description configuration options.
On top of that, you may want to add the NESTED_CLASS key to replace the description with a whole another classes' description:

$description[SerializerModelDescriber::NESTED_CLASS] = 'App\Entity\User';

In case you want to define an array of particular objects, then:

$description['items'][SerializerModelDescriber::NESTED_CLASS] = 'App\Entity\User';

It's best to have a look at the AnzuSystems\SerializerBundle\Handler\Handlers namespace for inspiration on how other handlers work.

Caveats/requirements/features

  • Iterables with keys will be automatically (de)serialized into an associative array or indexed collection.
  • Currently, only json format is supported.
  • Every property that you want to (de)serialize, must have a public getter and setter.
    • Setter name example for property $email: setEmail
    • Getter name example for property $email: getEmail
    • Getter name example for boolean properties: isEnabled
  • Constructor of an object that you want to (de)serialize cannot have required parameters.
    • You can also use public static functions to instantiate an object if you want required parameters. For instance:
public static function getInstance(Post $decorated): self
{
    return (new self())
        ->setDecorated($decorated)
    ;
}
  • Use SerializeParam to convert request body into desired object. Example:
#[Route('/topic', name: 'create', methods: [Request::METHOD_POST])]
public function create(#[SerializeParam] Topic $topic): JsonResponse
{
    return $this->createdResponse(
        $this->topicFacade->create($topic)
    );
}

anzusystems/serializer-bundle 适用场景与选型建议

anzusystems/serializer-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 26k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 11 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「anzusystems」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 anzusystems/serializer-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 anzusystems/serializer-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 anzusystems/serializer-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 26k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 4
  • 推荐数: 1

GitHub 信息

  • Stars: 0
  • Watchers: 6
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2022-11-24