跳至正文

更新日志 1.9.0 — 2024 年 2 月 2 日

重要变更

JSON 规范化器

规范化器能够将数据结构规范化为 JSON,而无需使用本机json_encode()函数。

使用规范化器而不是本机json_encode()函数有一些好处:

  • 将使用默认转换对值进行递归规范化
  • 所有注册的变换器将在格式化之前应用于数据
  • JSON 可以以节省内存的方式流式传输到 PHP 资源

基本用法:

namespace My\App;

$normalizer = (new \CuyZ\Valinor\MapperBuilder())
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::json());

$userAsJson = $normalizer->normalize(
    new \My\App\User(
        name: 'John Doe',
        age: 42,
        country: new \My\App\Country(
            name: 'France',
            code: 'FR',
        ),
    )
);

// `$userAsJson` is a valid JSON string representing the data:
// {"name":"John Doe","age":42,"country":{"name":"France","code":"FR"}}

默认情况下,JSON 规范化器将返回一个表示所给数据的 JSON 字符串。可以将 JSON 数据流式传输到 PHP 资源,而不是获取字符串:

$file = fopen('path/to/some_file.json', 'w');

$normalizer = (new \CuyZ\Valinor\MapperBuilder())
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::json())
    ->streamTo($file);

$normalizer->normalize(/* … */);

// The file now contains the JSON data

将数据流式传输到 PHP 资源的另一个好处是,在使用生成器时,例如在查询数据库时,它可能会更加节省内存:

// In this example, we assume that the result of the query below is a
// generator, every entry will be yielded one by one, instead of
// everything being loaded in memory at once.
$users = $database->execute('SELECT * FROM users');

$file = fopen('path/to/some_file.json', 'w');

$normalizer = (new \CuyZ\Valinor\MapperBuilder())
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::json())
    ->streamTo($file);

// Even if there are thousands of users, memory usage will be kept low
// when writing JSON into the file.
$normalizer->normalize($users);

新功能

  • 引入 JSON 规范化器 ( 959740 )

错误修复

  • 为DateTimeZone添加默认变换器 ( acf097 )
  • 检测穿过对象的线性循环引用 ( 36aead )

其他

  • 重构特性定义以包括类定义 ( 4b8cf6 )