Skip to content

序列化模块 ​

Kuiper 框架的序列化模块提供了强大的对象序列化和反序列化功能,支持类型安全的 PHP 对象与 JSON/数组之间的相互转换。基于反射系统实现,提供严格的类型检查和灵活的配置选项。

特性 ​

  • 类型安全: 基于反射系统实现严格的类型检查和转换,支持 PHP 8 类型和 PHPDoc 注解
  • 高性能: 类元数据缓存(默认文件缓存,可回退内存缓存),避免重复反射
  • 灵活配置: 支持环境变量、配置文件、配置类多种配置方式
  • 安全控制: 反序列化白名单、严格模式、危险类黑名单,防止反序列化攻击
  • 内置支持: 经依赖注入获取的序列化器自动注册 DateTime、枚举、异常等 normalizer
  • 属性注解: 支持 #[SerializeName] 和 #[SerializeIgnore] 控制序列化行为

快速开始 ​

基本使用 ​

在 Kuiper 框架中,序列化器可通过依赖注入获取:

php
<?php

declare(strict_types=1);

namespace App\Service;

use kuiper\serializer\SerializerInterface;

class UserService
{
    public function __construct(
        private readonly SerializerInterface $serializer
    ) {
    }

    public function serializeUser(User $user): string
    {
        // 序列化为 JSON
        return $this->serializer->toJson($user);
    }

    public function deserializeUser(string $json): User
    {
        // 从 JSON 反序列化
        return $this->serializer->fromJson($json, User::class);
    }
}

简单对象序列化 ​

php
<?php

declare(strict_types=1);

use kuiper\serializer\Serializer;

class User
{
    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {
    }
}

$serializer = new Serializer();
$user = new User('Alice', 30);

// 标准化为数组
$array = $serializer->normalize($user);
// ['name' => 'Alice', 'age' => 30]

// 序列化为 JSON
$json = $serializer->toJson($user);
// '{"name":"Alice","age":30}'

手动创建与依赖注入的区别

裸 new Serializer() 不注册任何内置 normalizer,DateTime、枚举、异常会按普通对象展开成数组。通过依赖注入获取的 SerializerInterface 已在 SerializerConfiguration 中注册 DateTimeNormalizer、PhpEnumNormalizer、ExceptionNormalizer 和 BinaryStringNormalizer;手动创建实例时需要显式传入,详见标准化器指南。

对象反序列化 ​

php
<?php

declare(strict_types=1);

use kuiper\serializer\Serializer;

class User
{
    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {
    }
}

$serializer = new Serializer();

// 从 JSON 恢复对象
$json = '{"name":"Bob","age":25}';
$user = $serializer->fromJson($json, User::class);

echo $user->name; // Bob
echo $user->age;  // 25

复杂类型支持 ​

php
<?php

declare(strict_types=1);

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

enum Status: string
{
    case PENDING = 'pending';
    case COMPLETED = 'completed';
}

class OrderItem
{
    public function __construct(
        public readonly string $productId,
        public readonly int $quantity,
        public readonly float $price
    ) {
    }
}

class Order
{
    public function __construct(
        public readonly string $id,
        public readonly \DateTimeImmutable $createdAt,
        public readonly Status $status,
        public readonly array $items
    ) {
    }
}

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

$order = new Order(
    id: 'ORD-001',
    createdAt: new \DateTimeImmutable('2024-01-15 10:30:00', new \DateTimeZone('UTC')),
    status: Status::PENDING,
    items: [
        new OrderItem('PROD-1', 2, 29.99),
        new OrderItem('PROD-2', 1, 49.99),
    ]
);

$json = $serializer->toJson($order, JSON_PRETTY_PRINT);
echo $json;

输出结果:

json
{
    "id": "ORD-001",
    "createdAt": "2024-01-15T10:30:00+00:00",
    "status": "PENDING",
    "items": [
        {
            "productId": "PROD-1",
            "quantity": 2,
            "price": 29.99
        },
        {
            "productId": "PROD-2",
            "quantity": 1,
            "price": 49.99
        }
    ]
}

架构概览 ​

数据流向说明:

  1. 应用层: 业务类通过依赖注入获取 SerializerInterface
  2. 序列化器层: Serializer 实现完整的序列化/反序列化逻辑,包含类型验证和安全控制
  3. 标准化层: ObjectNormalizer 负责对象与数组的转换,ClassMetadataFactory 管理类结构元数据
  4. 元数据层: ClassMetadata 存储类的 getter、setter、构造函数参数等信息,Field 描述单个字段
  5. Normalizer 注册表: 内置和自定义的 Normalizer 处理特殊类型(DateTime、枚举、异常等),内置项由 SerializerConfiguration 通过依赖注入注册

序列化流程 ​

核心概念 ​

标准化 vs JSON 序列化 ​

Kuiper 序列化器提供两个层面的操作:

标准化(Normalization):将 PHP 对象转换为 PHP 数组

php
// normalize: object → array
$array = $serializer->normalize($user);
// ['name' => 'Alice', 'age' => 30]

JSON 序列化:在标准化的基础上进行 JSON 编码

php
// toJson: object → array → JSON
$json = $serializer->toJson($user);
// '{"name":"Alice","age":30}'

区别和用途:

操作输入输出用途
normalize()任意类型PHP 数组/标量数据处理、缓存存储
toJson()任意类型JSON 字符串API 响应、数据交换
denormalize()PHP 数组对象从缓存恢复、数据处理
fromJson()JSON 字符串对象API 请求处理

类型系统 ​

Serializer 依赖 reflection 模块进行类型解析,支持:

PHP 8 原生类型:

php
class Product
{
    public function __construct(
        public readonly string $name,           // 字符串
        public readonly int $price,             // 整数
        public readonly float $weight,          // 浮点数
        public readonly bool $available,        // 布尔值
        public readonly ?string $description,   // 可空类型
        public readonly array $tags             // 数组
    ) {
    }
}

PHPDoc 类型注解:

php
class Order
{
    /** @var OrderItem[] */
    public array $items;

    /** @var array<string, mixed> */
    public array $metadata;

    /** @var string|null */
    public ?string $note;
}

支持的类型语法:

  • 基础类型: string, int, float, bool, array
  • 数组类型: string[], int[], array&lt;int&gt;
  • 多维数组: int[][]
  • Map 类型: array&lt;string, int&gt;
  • 联合类型: string|int, string|null
  • 泛型风格: array&lt;int, User&gt;

元数据缓存 ​

类结构解析是性能敏感操作,Serializer 会把解析结果缓存起来避免重复反射。

通过依赖注入获取的序列化器由 CacheConfiguration 的 metadataCache Bean 提供元数据缓存:

  • 文件缓存(默认启用):元数据持久化到磁盘,可跨请求共享
  • 内存缓存:application.cache.metadata.enabled 为 false 时回退到进程内内存缓存
配置键(application.cache.metadata)环境变量默认值说明
enabledCACHE_METADATA_ENABLEDtrue是否启用文件缓存
dirCACHE_METADATA_FILE_DIRsys_get_temp_dir()/kuiper-metadata-cache文件缓存目录
ttlCACHE_METADATA_FILE_TTL3600缓存有效期(秒)

手动创建的序列化器默认没有元数据缓存

不传 ClassMetadataFactory 时,new Serializer() 会创建一个不带缓存的默认工厂。需要缓存时请通过依赖注入获取序列化器,或自行构造并传入带缓存的 ClassMetadataFactory。

使用指南 ​

简单对象 ​

对于简单的数据对象,只需定义公共属性和构造函数:

php
<?php

declare(strict_types=1);

class User
{
    public function __construct(
        public readonly string $name,
        public readonly int $age,
        public readonly ?string $email = null
    ) {
    }
}

$serializer = new \kuiper\serializer\Serializer();

// 序列化
$user = new User('Alice', 30, 'alice@example.com');
$json = $serializer->toJson($user);
// '{"name":"Alice","age":30,"email":"alice@example.com"}'

// 反序列化
$restored = $serializer->fromJson($json, User::class);

复杂对象 ​

支持嵌套对象。序列化时递归超过 256 层会抛出异常,可防止循环引用导致栈溢出:

php
<?php

declare(strict_types=1);

class Address
{
    public function __construct(
        public readonly string $city,
        public readonly string $street,
        public readonly string $zipCode
    ) {
    }
}

class Company
{
    public function __construct(
        public readonly string $name,
        public readonly Address $address
    ) {
    }
}

class Employee
{
    public function __construct(
        public readonly string $name,
        public readonly Company $company,
        public readonly ?Employee $manager = null
    ) {
    }
}

$serializer = new \kuiper\serializer\Serializer();

$company = new Company(
    name: 'Tech Corp',
    address: new Address('Beijing', 'Tech Street', '100000')
);

$manager = new Employee('John', $company);
$employee = new Employee('Jane', $company, $manager);

$json = $serializer->toJson($employee, JSON_PRETTY_PRINT);

数组和集合 ​

支持数组类型注解和嵌套数组:

php
<?php

declare(strict_types=1);

class Team
{
    /** @var Employee[] */
    public array $members;

    /** @var array<string, string> */
    public array $metadata;

    public function __construct(
        public readonly string $name,
        array $members = [],
        array $metadata = []
    ) {
        $this->members = $members;
        $this->metadata = $metadata;
    }
}

$team = new Team(
    name: 'Development',
    members: [
        new Employee('Alice', $company),
        new Employee('Bob', $company),
    ],
    metadata: ['department' => 'Engineering', 'floor' => '3F']
);

$json = $serializer->toJson($team);

枚举类型 ​

支持 PHP 8 枚举(UnitEnum 和 BackedEnum):

php
<?php

declare(strict_types=1);

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

// 纯枚举
enum Priority
{
    case LOW;
    case MEDIUM;
    case HIGH;
}

// 有值枚举
enum Status: string
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';
}

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

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

$task = new Task('Review code', Priority::HIGH, Status::DRAFT);
$json = $serializer->toJson($task);
// '{"title":"Review code","priority":"HIGH","status":"DRAFT"}'

枚举输出的是名称

PhpEnumNormalizer 输出枚举的 case 名称(如上例的 DRAFT),而不是背后值 draft。反序列化时名称和值都接受。

DateTime 处理 ​

DateTimeNormalizer 把 DateTimeInterface 序列化为 RFC3339 格式:

php
<?php

declare(strict_types=1);

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

class Event
{
    public function __construct(
        public readonly string $name,
        public readonly \DateTimeImmutable $startTime,
        public readonly ?\DateTime $endTime = null,
        public readonly \DateTimeInterface $createdAt = new \DateTimeImmutable()
    ) {
    }
}

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

$event = new Event(
    name: 'Conference',
    startTime: new \DateTimeImmutable('2024-06-15 09:00:00', new \DateTimeZone('UTC')),
    endTime: new \DateTime('2024-06-15 17:00:00', new \DateTimeZone('UTC'))
);

$json = $serializer->toJson($event);
// {"name":"Conference","startTime":"2024-06-15T09:00:00+00:00","endTime":"2024-06-15T17:00:00+00:00",...}

属性注解 ​

#[SerializeName] ​

自定义序列化后的字段名称:

php
<?php

declare(strict_types=1);

use kuiper\serializer\attribute\SerializeName;
use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;

class Product
{
    public function __construct(
        public readonly string $name,

        #[SerializeName('product_id')]
        public readonly string $id,

        #[SerializeName('created_at')]
        public readonly \DateTimeImmutable $createdAt
    ) {
    }
}

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

$product = new Product('Laptop', 'PROD-001', new \DateTimeImmutable());
$json = $serializer->toJson($product);
// '{"name":"Laptop","product_id":"PROD-001","created_at":"2024-..."}'

#[SerializeIgnore] ​

排除字段不参与序列化:

php
<?php

declare(strict_types=1);

use kuiper\serializer\attribute\SerializeIgnore;
use kuiper\serializer\Serializer;

class User
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,

        #[SerializeIgnore]
        public readonly string $passwordHash,

        #[SerializeIgnore]
        public readonly string $internalCode
    ) {
    }
}

$serializer = new Serializer();

$user = new User('Alice', 'alice@example.com', 'secret_hash', 'INT-001');
$json = $serializer->toJson($user);
// '{"name":"Alice","email":"alice@example.com"}'
// passwordHash 和 internalCode 被排除

组合使用 ​

php
<?php

declare(strict_types=1);

use kuiper\serializer\attribute\SerializeName;
use kuiper\serializer\attribute\SerializeIgnore;

class ApiResponse
{
    public function __construct(
        public readonly bool $success,
        public readonly mixed $data,

        #[SerializeName('error_message')]
        public readonly ?string $errorMessage = null,

        #[SerializeIgnore]
        public readonly ?\Exception $exception = null,

        #[SerializeName('request_id')]
        public readonly string $requestId = ''
    ) {
    }
}

最佳实践 ​

性能优化 ​

1. 启用元数据缓存

php
// src/config.php
return [
    'application' => [
        'cache' => [
            'metadata' => [
                'enabled' => true,
                'dir' => '/var/cache/kuiper/metadata',
                'ttl' => 3600,
            ],
        ],
    ],
];

2. 使用依赖注入

避免重复创建 Serializer 实例,通过依赖注入共享:

php
// 推荐:依赖注入
class UserService
{
    public function __construct(
        private readonly SerializerInterface $serializer
    ) {
    }
}

// 避免:手动创建多个实例
$serializer1 = new Serializer();
$serializer2 = new Serializer(); // 重复创建,浪费资源

3. 合理使用 readonly 属性

PHP 8.1+ 的 readonly 属性可以减少不必要的 setter 调用:

php
// 推荐:使用 readonly
class User
{
    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {
    }
}

安全注意事项 ​

1. 生产环境启用严格模式

严格模式由 allowedClasses 非空触发,Serializer 构造器没有 strictMode 参数。推荐通过配置启用:

php
// src/config.php
return [
    'application' => [
        'serializer' => [
            'security' => [
                'strict_mode' => true,
                // 必须是逗号分隔的字符串,数组会被忽略
                'allowed_classes' => 'App\Entity\User,App\Entity\Order,App\Entity\Product',
            ],
        ],
    ],
];

手动创建实例时直接传入白名单:

php
$serializer = new Serializer(
    allowedClasses: [User::class, Order::class, Product::class]
);

2. 配置反序列化白名单

php
// 白名单非空即视为严格模式
$serializer->addAllowedClasses([
    User::class,
    Order::class,
    // 只允许这些类被反序列化
]);

3. 敏感数据使用 #[SerializeIgnore]

php
class User
{
    #[SerializeIgnore]
    public string $passwordHash;

    #[SerializeIgnore]
    public string $apiSecret;
}

4. 限制 JSON 大小

Serializer::fromJson() 的输入限制为 10MB(Serializer::MAX_JSON_SIZE 常量),防止内存耗尽攻击。该限制是常量,目前不可通过配置调整;如需更小的限制,应在应用层先校验请求体大小。

5. 递归深度限制

序列化(normalize()/toJson())递归深度上限为 256 层(Serializer::MAX_RECURSION_DEPTH 常量),超过后抛出 SerializeException,防止循环引用导致栈溢出。该限制是常量,不可通过配置调整。

文档导航 ​

相关资源 ​

基于 MIT 许可发布