jojo1981/jms-serializer-handlers

6.0.0 2023-02-06 09:46 UTC

This package is auto-updated.

Last update: 2024-09-06 13:05:49 UTC


README

Build Status Coverage Status Latest Stable Version Total Downloads License

作者:Joost Nijhuis <jnijhuis81@gmail.com>

这个库是 jms/serializer 包的扩展,包含自定义处理器,以支持与一些第三方库协同工作。有关 JMS Serializer Handlers 的更多信息,请参阅此处

该库支持

  • 来自 jojo1981/typed-collection 包的 Jojo1981\TypedCollection\Collection 实例。

安装

git clone https://github.com/jojo1981/jms-serializer-handlers.git

Composer

安装 PHP Composer

composer require jojo1981/jms-serializer-handlers

使用

<?php

use JMS\Serializer\Accessor\DefaultAccessorStrategy;
use JMS\Serializer\Construction\UnserializeObjectConstructor;
use JMS\Serializer\Handler\HandlerRegistry;
use JMS\Serializer\Naming\CamelCaseNamingStrategy;
use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
use JMS\Serializer\SerializerBuilder;
use Jojo1981\JmsSerializerHandlers\TypedCollectionAccessorStrategyDecorator;
use Jojo1981\JmsSerializerHandlers\TypedCollectionObjectConstructorDecorator;
use Jojo1981\JmsSerializerHandlers\TypedCollectionSerializationHandler;
use Jojo1981\JmsSerializerHandlers\TypedSetSerializationHandler;
use Jojo1981\JmsSerializerHandlers\UnionSerializationHandler;

require 'vendor/autoload.php';

$propertyNamingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
$accessorStrategy = new TypedCollectionAccessorStrategyDecorator(new DefaultAccessorStrategy());

$serializer = (new SerializerBuilder())
    ->setDebug(true)
    ->setCacheDir(__DIR__ . '/var/cache/serializer')
    ->setAccessorStrategy($accessorStrategy)
    ->setPropertyNamingStrategy($propertyNamingStrategy)
    ->addDefaultHandlers()
    ->configureHandlers(static function (HandlerRegistry $handlerRegistry): void {
        $handlerRegistry->registerSubscribingHandler(new TypedCollectionSerializationHandler());
        $handlerRegistry->registerSubscribingHandler(new TypedSetSerializationHandler());
        $handlerRegistry->registerSubscribingHandler(new UnionSerializationHandler());
    })
    ->setObjectConstructor(new TypedCollectionObjectConstructorDecorator(new UnserializeObjectConstructor()))
    ->build();