Skip to content

标准化器使用指南 ​

标准化器 (Normalizer) 是 Kuiper 序列化模块的核心组件,负责将 PHP 对象转换为数组格式,以及从数组还原为对象。本文档介绍如何使用内置的标准化器以及如何创建自定义标准化器。

目录 ​


标准化器概述 ​

什么是 Normalizer ​

Normalizer(标准化器)是实现了 NormalizerInterface 接口的类,用于处理特定类型的对象序列化和反序列化:

php
interface NormalizerInterface
{
    /**
     * 将对象标准化为数组或标量
     */
    public function normalize(mixed $object): mixed;

    /**
     * 将数据反标准化为对象
     */
    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed;
}

标准化 vs JSON 序列化 ​

JSON 序列化 (json_encode) 直接将对象转换为 JSON 字符串,但存在以下限制:

  • 只能序列化 public 属性
  • 无法控制输出格式
  • 反序列化时无法自动创建对象实例
  • 不支持类型安全的转换

标准化 提供了更强大的对象转换能力:

  • 通过 getter/setter 方法访问属性
  • 支持复杂类型(DateTime、Enum、嵌套对象)
  • 类型安全的反序列化
  • 可自定义转换逻辑
php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;

// 显式注册内置 normalizer;通过 DI 获取的序列化器已自动注册
$serializer = new Serializer(normalizers: [
    \DateTimeInterface::class => new DateTimeNormalizer(),
]);

// 标准化:对象 → 数组
$array = $serializer->normalize($user);
// ['name' => 'Alice', 'createdAt' => '2024-01-15T10:30:00+00:00']

// JSON 序列化:数组 → JSON
$json = $serializer->toJson($user);
// '{"name":"Alice","createdAt":"2024-01-15T10:30:00+00:00"}'

// 反序列化:JSON → 对象
$user = $serializer->fromJson($json, User::class);

裸 new Serializer() 不带内置 normalizer

不传 normalizers 时,DateTime 会展开成数组、枚举会展开成名称/值数组。手动创建实例时务必传入需要的 normalizer,或通过依赖注入获取框架注册好的 SerializerInterface。


内置标准化器 ​

SerializerConfiguration 会为依赖注入的序列化器注册四个内置 normalizer:DateTimeNormalizer、PhpEnumNormalizer、ExceptionNormalizer 和 BinaryStringNormalizer(把 kuiper\serializer\BinaryString 序列化为 base64)。下面介绍最常用的三个。

DateTimeNormalizer ​

DateTimeNormalizer 处理 DateTimeInterface 类型的序列化和反序列化。

序列化格式 ​

DateTime 对象被序列化为 RFC3339 格式字符串:

php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;

class Event
{
    public function __construct(
        public readonly string $name,
        public readonly \DateTimeImmutable $startTime
    ) {}
}

$serializer = new Serializer(normalizers: [
    \DateTimeInterface::class => new DateTimeNormalizer(),
]);

$event = new Event('Conference', new \DateTimeImmutable('2024-03-15 10:00:00', new \DateTimeZone('UTC')));

$json = $serializer->toJson($event);
// 输出: {"name":"Conference","startTime":"2024-03-15T10:00:00+00:00"}

反序列化支持 ​

支持从字符串或数组反序列化:

php
// 从 RFC3339 字符串反序列化
$json = '{"name":"Meeting","startTime":"2024-03-15T14:30:00+08:00"}';
$event = $serializer->fromJson($json, Event::class);

// 从数组反序列化(兼容 PHP DateTime 数组格式)
$data = [
    'name' => 'Workshop',
    'startTime' => [
        'date' => '2024-03-15 14:30:00.000000',
        'timezone' => 'Asia/Shanghai'
    ]
];
$event = $serializer->denormalize($data, Event::class);

时区处理 ​

  • 序列化时保留原始时区信息
  • 反序列化时自动识别时区
  • 默认使用 DateTimeImmutable(推荐)或 DateTime
php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;

$serializer = new Serializer(normalizers: [
    \DateTimeInterface::class => new DateTimeNormalizer(),
]);

// 使用 DateTimeImmutable(默认)
$dt = new \DateTimeImmutable('2024-03-15 10:00:00', new \DateTimeZone('Asia/Shanghai'));
$json = $serializer->toJson(['time' => $dt]);
// {"time":"2024-03-15T10:00:00+08:00"}

PhpEnumNormalizer ​

PhpEnumNormalizer 处理 PHP 8 枚举类型的序列化和反序列化,支持 UnitEnum 和 BackedEnum。

UnitEnum 处理 ​

对于无值枚举,序列化为枚举名称:

php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\PhpEnumNormalizer;

enum Status: string
{
    case PENDING = 'pending';
    case APPROVED = 'approved';
    case REJECTED = 'rejected';
}

enum Priority
{
    case LOW;
    case MEDIUM;
    case HIGH;
}

class Task
{
    public function __construct(
        public readonly string $title,
        public readonly Status $status,
        public readonly Priority $priority
    ) {}
}

$serializer = new Serializer(normalizers: [
    \UnitEnum::class => new PhpEnumNormalizer(),
]);
$task = new Task('Review', Status::PENDING, Priority::HIGH);

$json = $serializer->toJson($task);
// 输出: {"title":"Review","status":"PENDING","priority":"HIGH"}

输出名称而非值

PhpEnumNormalizer 返回 $object->name,因此有值枚举 Status::PENDING(值 pending)会输出 "PENDING"。这与 Valinor 适配器的行为不同:Valinor 对 BackedEnum 输出的是枚举值。

BackedEnum 反序列化 ​

反序列化时支持名称和值两种方式:

php
// 通过名称反序列化
$json1 = '{"title":"Task 1","status":"PENDING","priority":"HIGH"}';
$task1 = $serializer->fromJson($json1, Task::class);

// 通过值反序列化(仅 BackedEnum)
$json2 = '{"title":"Task 2","status":"approved","priority":"MEDIUM"}';
$task2 = $serializer->fromJson($json2, Task::class);

枚举使用最佳实践 ​

php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;
use kuiper\serializer\normalizer\PhpEnumNormalizer;

// 1. 优先使用 BackedEnum(支持数据库存储)
enum OrderStatus: string
{
    case CREATED = 'created';
    case PAID = 'paid';
    case SHIPPED = 'shipped';
    case COMPLETED = 'completed';
}

// 2. 在 DTO 中使用枚举类型
class OrderDto
{
    public function __construct(
        public readonly string $orderId,
        public readonly OrderStatus $status,
        public readonly ?\DateTimeImmutable $paidAt = null
    ) {}
}

$serializer = new Serializer(normalizers: [
    \DateTimeInterface::class => new DateTimeNormalizer(),
    \UnitEnum::class => new PhpEnumNormalizer(),
]);

// 3. 序列化后可直接用于 API 响应
$order = new OrderDto(
    'ORD-001',
    OrderStatus::PAID,
    new \DateTimeImmutable('2024-03-15 10:30:00', new \DateTimeZone('UTC'))
);
echo $serializer->toJson($order);
// {"orderId":"ORD-001","status":"PAID","paidAt":"2024-03-15T10:30:00+00:00"}

ExceptionNormalizer ​

ExceptionNormalizer 处理异常对象的标准化,将异常转换为可序列化的格式。

异常序列化 ​

异常被序列化为 base64 编码的 JSON 字符串:

php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\ExceptionNormalizer;

$serializer = new Serializer(normalizers: [
    \Exception::class => new ExceptionNormalizer(),
]);

try {
    throw new \RuntimeException('Something went wrong', 500);
} catch (\Exception $e) {
    // 标准化异常
    $normalized = $serializer->normalize($e);
    // 输出: base64 编码的字符串,解码后为:
    // {"class":"RuntimeException","message":"Something went wrong","code":500}
}

不输出文件路径

ExceptionNormalizer 只保留 class、message、code,不会输出 file/line,避免在 RPC 响应中泄露服务器绝对路径。

在 DTO 中使用 ​

适用于错误响应对象:

php
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;
use kuiper\serializer\normalizer\ExceptionNormalizer;

class ErrorResponse
{
    public function __construct(
        public readonly bool $success = false,
        public readonly ?\Exception $error = null,
        public ?\DateTimeImmutable $timestamp = null
    ) {
        $this->timestamp ??= new \DateTimeImmutable();
    }
}

$serializer = new Serializer(normalizers: [
    \DateTimeInterface::class => new DateTimeNormalizer(),
    \Exception::class => new ExceptionNormalizer(),
]);

// 创建错误响应
$error = new ErrorResponse(
    error: new \InvalidArgumentException('Invalid parameter: userId')
);

$json = $serializer->toJson($error);
// {"success":false,"error":"<base64>","timestamp":"2024-..."}

反序列化异常 ​

支持从标准化数据重建异常对象:

php
// 假设 $data 是标准化后的异常数据
$exception = $serializer->denormalize($data, \RuntimeException::class);

// 或使用通用 Exception 类型
$exception = $serializer->denormalize($data, \Exception::class);

注意:反序列化后的异常是新的实例,不包含原始堆栈跟踪信息。


自定义标准化器 ​

当内置标准化器无法满足需求时,可以实现自定义标准化器。

实现 NormalizerInterface ​

以下是一个处理 Money 值对象的自定义标准化器示例:

php
<?php

declare(strict_types=1);

namespace App\Serializer;

use kuiper\reflection\ReflectionTypeInterface;
use kuiper\serializer\NormalizerInterface;

/**
 * 金额对象
 */
class Money
{
    public function __construct(
        public readonly int $amount,      // 以分为单位
        public readonly string $currency  // ISO 货币代码
    ) {}

    public function toString(): string
    {
        $major = intdiv($this->amount, 100);
        $minor = abs($this->amount % 100);
        return sprintf('%s %d.%02d', $this->currency, $major, $minor);
    }
}

/**
 * Money 标准化器
 */
class MoneyNormalizer implements NormalizerInterface
{
    /**
     * 将 Money 对象标准化为数组
     */
    public function normalize(mixed $object): mixed
    {
        if (!$object instanceof Money) {
            throw new \InvalidArgumentException('Expected Money object');
        }

        return [
            'amount' => $object->amount,
            'currency' => $object->currency,
            'formatted' => $object->toString()
        ];
    }

    /**
     * 将数据反标准化为 Money 对象
     */
    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed
    {
        if (!is_array($data)) {
            throw new \InvalidArgumentException('Expected array data');
        }

        if (!isset($data['amount'], $data['currency'])) {
            throw new \InvalidArgumentException('Missing amount or currency');
        }

        return new Money(
            amount: (int) $data['amount'],
            currency: (string) $data['currency']
        );
    }
}

使用自定义标准化器 ​

php
use kuiper\serializer\Serializer;
use App\Serializer\Money;
use App\Serializer\MoneyNormalizer;

class Product
{
    public function __construct(
        public readonly string $name,
        public readonly Money $price
    ) {}
}

// 创建序列化器并注册自定义标准化器
$serializer = new Serializer(
    normalizers: [
        Money::class => new MoneyNormalizer()
    ]
);

// 使用
$price = new Money(1999, 'CNY');
$product = ['name' => 'Book', 'price' => $price];

echo $serializer->toJson($product);
// 输出: {"name":"Book","price":{"amount":1999,"currency":"CNY","formatted":"CNY 19.99"}}

// 反序列化
$json = '{"name":"Book","price":{"amount":2999,"currency":"USD"}}';
$data = $serializer->fromJson($json, Product::class);
// $data->price 是 Money 对象

更多自定义示例 ​

处理敏感数据(脱敏) ​

php
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\serializer\NormalizerInterface;

class Phone
{
    public function __construct(
        private readonly string $number,
        private readonly string $countryCode = '+86'
    ) {}

    public function getNumber(): string
    {
        return $this->number;
    }

    public function getCountryCode(): string
    {
        return $this->countryCode;
    }
}

class PhoneNormalizer implements NormalizerInterface
{
    public function normalize(mixed $object): mixed
    {
        if (!$object instanceof Phone) {
            return $object;
        }

        $number = $object->getNumber();
        // 脱敏处理:138****8888
        $masked = substr($number, 0, 3) . '****' . substr($number, -4);

        return [
            'number' => $masked,
            'countryCode' => $object->getCountryCode()
        ];
    }

    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed
    {
        return new Phone($data['number'], $data['countryCode'] ?? '+86');
    }
}

处理复杂嵌套对象 ​

php
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\serializer\NormalizerInterface;

class GeoPoint
{
    public function __construct(
        private readonly float $latitude,
        private readonly float $longitude
    ) {}

    public function getLatitude(): float
    {
        return $this->latitude;
    }

    public function getLongitude(): float
    {
        return $this->longitude;
    }
}

class GeoPointNormalizer implements NormalizerInterface
{
    public function normalize(mixed $object): mixed
    {
        if (!$object instanceof GeoPoint) {
            return $object;
        }

        // 序列化为 GeoJSON 格式
        return [
            'type' => 'Point',
            'coordinates' => [$object->getLongitude(), $object->getLatitude()]
        ];
    }

    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed
    {
        if (isset($data['coordinates']) && is_array($data['coordinates'])) {
            return new GeoPoint($data['coordinates'][1], $data['coordinates'][0]);
        }

        return new GeoPoint($data['latitude'], $data['longitude']);
    }
}

标准化器注册与优先级 ​

注册方式 ​

自定义标准化器通过 Serializer 构造函数或 addObjectNormalizer 方法注册:

php
use kuiper\serializer\Serializer;

// 方式 1:构造函数注册
$serializer = new Serializer(
    normalizers: [
        Money::class => new MoneyNormalizer(),
        Phone::class => new PhoneNormalizer(),
        GeoPoint::class => new GeoPointNormalizer(),
    ]
);

// 方式 2:方法注册
$serializer = new Serializer();
$serializer->addObjectNormalizer(Money::class, new MoneyNormalizer());
$serializer->addObjectNormalizer(Phone::class, new PhoneNormalizer());

类型匹配规则 ​

标准化器按照注册顺序进行类型匹配检查:

php
$serializer = new Serializer(
    normalizers: [
        // 先检查是否匹配 Money
        Money::class => new MoneyNormalizer(),
        // 再检查是否匹配 GeoPoint
        GeoPoint::class => new GeoPointNormalizer(),
    ]
);

匹配规则使用 instanceof 检查:

php
foreach ($this->normalizers as $className => $normalizer) {
    if ($object instanceof $className) {
        return $normalizer->normalize($object);
    }
}

继承关系处理 ​

标准化器按注册顺序做 instanceof 匹配,因此父类 normalizer 必须先于子类注册时才安全;推荐始终先注册具体类型:

php
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\serializer\NormalizerInterface;

class Animal {}
class Dog extends Animal {}

class AnimalNormalizer implements NormalizerInterface
{
    public function normalize(mixed $object): mixed
    {
        return ['kind' => 'animal'];
    }

    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed
    {
        return new Animal();
    }
}

class DogNormalizer extends AnimalNormalizer
{
    public function normalize(mixed $object): mixed
    {
        return ['kind' => 'dog'];
    }
}

// 先注册具体类型,再注册父类
$serializer = new Serializer();
$serializer->addObjectNormalizer(Dog::class, new DogNormalizer());
$serializer->addObjectNormalizer(Animal::class, new AnimalNormalizer());
// Dog 匹配 DogNormalizer;其他 Animal 子类匹配 AnimalNormalizer

注册顺序决定匹配结果

如果把 Animal::class 注册在 Dog::class 之前,Dog 对象会先命中 AnimalNormalizer(因为 Dog instanceof Animal)。父类 normalizer 不是兜底选项,而是按顺序参与匹配。

优先级最佳实践 ​

  1. 具体类型优先:先注册具体类,后注册父类
php
// 假设已定义 PremiumCustomer、Customer、User 及其 normalizer
$serializer = new Serializer(
    normalizers: [
        // 具体类型在前
        PremiumCustomer::class => new PremiumCustomerNormalizer(),
        Customer::class => new CustomerNormalizer(),
        // 通用类型在后
        User::class => new UserNormalizer(),
    ]
);
  1. 常用类型优先:将频繁使用的标准化器放在前面,减少匹配次数
php
// 假设已定义 DateRange、ComplexEntity 及其 normalizer
$serializer = new Serializer(
    normalizers: [
        // 高频使用
        Money::class => new MoneyNormalizer(),
        DateRange::class => new DateRangeNormalizer(),
        // 低频使用
        ComplexEntity::class => new ComplexEntityNormalizer(),
    ]
);
  1. 避免重复注册:同一类只注册一个标准化器,后注册的会覆盖先注册的
php
$serializer = new Serializer();
$serializer->addObjectNormalizer(Money::class, new MoneyNormalizerV1());
$serializer->addObjectNormalizer(Money::class, new MoneyNormalizerV2());
// 最终只有 MoneyNormalizerV2 生效

与依赖注入集成 ​

框架的 SerializerConfiguration 已经注册了 SerializerInterface Bean(按返回类型命名),并内置注册 DateTime、枚举、异常、二进制字符串 normalizer。如需替换默认实现,定义返回类型同为 SerializerInterface 的 Bean(后加载的配置会覆盖先加载的同名 Bean):

php
<?php

declare(strict_types=1);

namespace App\Config;

use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use kuiper\serializer\Serializer;
use kuiper\serializer\SerializerInterface;
use kuiper\serializer\normalizer\DateTimeNormalizer;
use kuiper\serializer\normalizer\PhpEnumNormalizer;
use App\Serializer\Money;
use App\Serializer\MoneyNormalizer;

#[Configuration]
class CustomSerializerConfiguration
{
    #[Bean]
    public function serializer(): SerializerInterface
    {
        // 覆盖框架默认注册后,内置 normalizer 需要自行补齐
        return new Serializer(
            normalizers: [
                \DateTimeInterface::class => new DateTimeNormalizer(),
                \UnitEnum::class => new PhpEnumNormalizer(),
                Money::class => new MoneyNormalizer(),
            ]
        );
    }
}

总结 ​

标准化器是 Kuiper 序列化系统的核心扩展点:

  • 内置标准化器:经依赖注入的序列化器自动注册 DateTime、Enum、Exception、BinaryString 等 normalizer
  • 自定义标准化器:通过实现 NormalizerInterface 处理特定业务类型
  • 注册机制:通过数组键值对注册,支持继承关系匹配
  • 优先级控制:注册顺序决定匹配优先级

合理使用标准化器,可以实现类型安全、格式统一的数据序列化,为 API 开发、消息队列、缓存存储等场景提供可靠的数据转换能力。

基于 MIT 许可发布