suin/marshaller

在 JSON 和 PHP 类对象之间进行类型安全的映射。

1.0.1 2018-01-03 16:00 UTC

This package is auto-updated.

Last update: 2024-09-06 08:43:56 UTC


README

travis-ci-badge packagist-dt-badge license-badge release-version-badge php-version-badge

在 JSON 和 PHP 类对象之间进行类型安全的映射。

特性

  1. 将 JSON 转换为 PHP 类对象。
  2. 将 PHP 对象转换为 JSON。

它是如何工作的?

Marshaller 分析所有私有属性并将它们转换为 JSON。Unmarshaller 分析给定类的构造函数签名并将 JSON 转换为对象。

通过 Composer 安装

$ composer require suin/marshaller

使用方法

序列化和反序列化

这是 Marshaller 的最简单用法。

use Suin\Marshaller\JsonMarshaller;
use Suin\Marshaller\StandardProtocol;

// Transform an object to JSON.
$marshaller = new JsonMarshaller(new StandardProtocol);
$json = $marshaller->marshal(new Cat('Oliver'));
var_dump($json);
// Output:
// string(17) "{"name":"Oliver"}"

// Transform JSON to an object.
$cat = $marshaller->unmarshal($json, Cat::class);
var_dump($cat);
// Output:
// object(Cat)#%d (1) {
//   ["name":"Cat":private]=>
//   string(6) "Oliver"
// }

有关详细信息,请参阅 示例#01

协议

有时你可能希望以特殊的方式解码 JSON 值。在这种情况下,你也可以通过使用 ProtocolFormat 来定义 PHP 对象和 JSON 对象之间的转换规则。

Format 描述单个类或类型如何成为 JSON,反之亦然。所有 Format 必须遵循以下接口

interface Format<A, B> {
  public function read(A $jsonValue): B
  public function write(B $object): A
}

例如,Format 可以这样实现

class HealthFormat // naming rule: class name + "Format"
{
    // Define how transform a JSON value to a PHP object.
    public function read(string $health): Health
    {
        return new Health($health === 'healthy');
    }

    // Define how transform a PHP object to a JSON value.
    public function write(Health $health): string
    {
        return $health->isHealthy() ? 'healthy' : 'sick';
    }
}

此外,协议是一个包含多个 Format 的类。以下示例只有一个格式,但在实际使用中,这里可能包含更多的格式。

class HealthProtocol extends StandardProtocol
{
    public function __construct()
    {
        parent::__construct(
            new HealthFormat
        );
    }
}

要查看协议和格式的完整示例代码,请参阅 示例#02。还可以在 ./tests/ExampleModel/StudentProtocol.php 中看到复杂示例。

更新日志

有关更多详细信息,请参阅 更新日志

贡献

有关更多详细信息,请参阅 贡献