承接 consistence/consistence-jms-serializer 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

consistence/consistence-jms-serializer

Composer 安装命令:

composer require consistence/consistence-jms-serializer

包简介

Integration of Consistence library with JMS Serializer

README 文档

README

This library provides integration of Consistence value objects for JMS Serializer so that you can use them in your serialization mappings.

For now, the only integration which is needed is for Enums, see the examples below.

Usage

Enums represent predefined set of values and of course, you will want to serialize and deserialize these values as well. Since Enums are objects and you only want to (de)serialize represented value, there has to be some mapping.

You can see it in this example where you want to (de)serialize sex for your Users:

<?php

namespace Consistence\JmsSerializer\Example\User;

class Sex extends \Consistence\Enum\Enum
{

	public const FEMALE = 'female';
	public const MALE = 'male';

}

Now you can use the Sex enum in your User object. Type for (de)serialization is specified as enum<Your\Enum\Class>:

<?php

namespace Consistence\JmsSerializer\Example\User;

use JMS\Serializer\Annotation as JMS;

class User extends \Consistence\ObjectPrototype
{

	// ...

	/**
	 * @JMS\Type("enum<Consistence\JmsSerializer\Example\User\Sex>")
	 * @var \Consistence\JmsSerializer\Example\User\Sex|null
	 */
	private $sex;

	// ...

	public function __construct(
		// ...
		Sex $sex = null
		// ...
	)
	{
		// ...
		$this->sex = $sex;
		// ...
	}

}

Now everything is ready to be used, when you serialize the object, only female will be returned as the value representing the enum:

<?php

namespace Consistence\JmsSerializer\Example\User;

/** @var \JMS\Serializer\Serializer $serializer */
$user = new User(Sex::get(Sex::FEMALE));
var_dump($serializer->serialize($user, 'json'));

/*

{
   "sex": "female"
}

*/

And when you deserialize the object, you will receive the Sex enum object again:

<?php

namespace Consistence\JmsSerializer\Example\User;

/** @var \JMS\Serializer\Serializer $serializer */
var_dump($serializer->deserialize('{
   "sex": "female"
}', User::class, 'json'));

/*

class Consistence\JmsSerializer\Example\User\User#46 (1) {
  private $sex =>
  class Consistence\JmsSerializer\Example\User\Sex#5 (1) {
    private $value =>
    string(6) "female"
  }
}

*/

This means that the objects API is symmetrical (you get the same type as you set) and you can start benefiting from Enums advantages such as being sure, that what you get is already a valid value and having the possibility to define methods on top of the represented values.

Nullable by default

Both serialization and deserialization will accept null values, there is no special mapping for that (by Jms Serializers convention), so if you are expecting a non-null value you have to enforce this by other means - either by restricting this in the API of your objects or by validation (needed especially for deserialization).

Invalid values

While serializing, there should be no invalid values, because Enums guarantee that the instance contains only valid values.

While deserializing, there can be an invalid value given, an exception will be thrown:

<?php

namespace Consistence\JmsSerializer\Example\User;

/** @var \JMS\Serializer\Serializer $serializer */
var_dump($serializer->deserialize('{
   "sex": "FOO"
}', User::class, 'json'));

// \Consistence\Enum\InvalidEnumValueException: FOO [string] is not a valid value, accepted values: female, male

If you are using this in an API, make sure you will catch this exception and send the consumer a response detailing this error, you can also write a custom message, the available values are listed in InvalidEnumValueException::getAvailableValues().

XML support

Unlike in JSON, in XML value types cannot be inferred directly from the values. So if you need to deserialize XML, you have to provide this type manually. You can do this by writing the type in the type definition - for the above example it would be string:

<?php

namespace Consistence\JmsSerializer\Example\User;

use JMS\Serializer\Annotation as JMS;

class User extends \Consistence\ObjectPrototype
{

	// ...

	/**
	 * @JMS\Type("enum<Consistence\JmsSerializer\Example\User\Sex, string>")
	 * @var \Consistence\JmsSerializer\Example\User\Sex|null
	 */
	private $sex;

	// ...

}

Special support for mapped MultiEnums

Since the (de)serialization works only with the value the enum is representing, then in case of MultiEnums this would mean outputting the value of the internal bit mask. This could be useful if both the client and server use the same Enum objects, but otherwise this breaks the abstraction and is less readable for a human consumer as well.

If you are using a MultiEum mapped to a single Enum there is a handy solution provided, if you add to your mapping enum<Your\Enum\Class, as_single> - notice the new as_single parameter, then the value of MultiEnum will be serialized as a collection of single Enum values:

<?php

namespace Consistence\JmsSerializer\Example\User;

use Consistence\Type\ArrayType\ArrayType;

use JMS\Serializer\Annotation as JMS;

class RoleEnum extends \Consistence\Enum\Enum
{

	public const USER = 'user';
	public const EMPLOYEE = 'employee';
	public const ADMIN = 'admin';

}

class RolesEnum extends \Consistence\Enum\MultiEnum
{

	/** @var int[] format: single Enum value (string) => MultiEnum value (int) */
	private static $singleMultiMap = [
		RoleEnum::USER => 1,
		RoleEnum::EMPLOYEE => 2,
		RoleEnum::ADMIN => 4,
	];

	public static function getSingleEnumClass(): string
	{
		return RoleEnum::class;
	}

	/**
	 * Converts value representing a value from single Enum to MultiEnum counterpart
	 *
	 * @param string $singleEnumValue
	 * @return int
	 */
	protected static function convertSingleEnumValueToValue($singleEnumValue): int
	{
		return ArrayType::getValue(self::$singleMultiMap, $singleEnumValue);
	}

	/**
	 * Converts value representing a value from MultiEnum to single Enum counterpart
	 *
	 * @param int $value
	 * @return string
	 */
	protected static function convertValueToSingleEnumValue(int $value): string
	{
		return ArrayType::getKey(self::$singleMultiMap, $value);
	}

}

class User extends \Consistence\ObjectPrototype
{

	// ...

	/**
	 * @JMS\Type("enum<Consistence\JmsSerializer\Example\User\RolesEnum, as_single>")
	 * @var \Consistence\JmsSerializer\Example\User\RolesEnum
	 */
	private $roles;

	// ...

	public function __construct(
		// ...
		RolesEnum $roles
		// ...
	)
	{
		// ...
		$this->roles = $roles;
		// ...
	}

}

$user = new User(RolesEnum::getMultiByEnums([
	RoleEnum::get(RoleEnum::USER),
	RoleEnum::get(RoleEnum::ADMIN),
]));

/** @var \JMS\Serializer\Serializer $serializer */
var_dump($serializer->serialize($user, 'json'));

/*

{
   "roles": [
      "user",
      "admin"
   ]
}

*/

Deserialization then again works symmetrically - giving an array of single Enum values will produce a MultiEnum instance:

<?php

namespace Consistence\JmsSerializer\Example\User;

/** @var \JMS\Serializer\Serializer $serializer */
var_dump($serializer->deserialize('{
   "roles": [
      "user",
      "admin"
   ]
}', User::class, 'json'));

/*

class Consistence\JmsSerializer\Example\User\User#48 (1) {
  private $roles =>
  class Consistence\JmsSerializer\Example\User\RolesEnum#37 (1) {
    private $value =>
    int(5)
  }
}

*/

Installation

If you are using Symfony, you can use consistence/consistence-jms-serializer-symfony, which will take care of the integration.

  1. Install package consistence/consistence-jms-serializer with Composer:
composer require consistence/consistence-jms-serializer
  1. Register serialization handler:
<?php

use Consistence\JmsSerializer\Enum\EnumSerializerHandler;

use JMS\Serializer\Handler\HandlerRegistry;
use JMS\Serializer\SerializerBuilder;

$serializer = SerializerBuilder::create()
	->configureHandlers(function (HandlerRegistry $registry) {
		$registry->registerSubscribingHandler(new EnumSerializerHandler());
	})
	->build();

That's all, you are good to go!

consistence/consistence-jms-serializer 适用场景与选型建议

consistence/consistence-jms-serializer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 107.32k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2017 年 01 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 4
  • Watchers: 2
  • Forks: 11
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-01-17