Valinor 序列化适配器
概述
Valinor 序列化适配器是 Kuiper 框架提供的可选序列化引擎,它集成了 CuyZ/Valinor 库,为复杂的类型映射和详细的错误报告提供了强大的支持。
什么是 Valinor?
Valinor 是一个现代的 PHP 库,专注于将任意数据结构映射到强类型的 PHP 对象,并将 PHP 对象转换为原始数据。它提供:
- 强大的类型推断:支持复杂的 PHP 类型系统,包括联合类型、泛型风格语法等
- 详细的错误报告:提供树状的错误信息,帮助开发者快速定位问题
- 编译缓存:通过编译缓存优化映射性能
- 零依赖:轻量级实现,无额外依赖
优势与特点
与 Kuiper 内置的序列化器相比,Valinor 适配器具有以下优势:
- 更丰富的类型支持:支持更复杂的类型定义和边界情况处理
- 详细错误信息:当映射失败时,抛出的
SerializeException保留原始MappingError(通过getPrevious()获取),其中包含精确的位置和原因 - 编译性能:编译缓存使得重复映射操作更加高效
与 Kuiper 序列化器的差异
- Valinor 适配器不经过 Kuiper Normalizer:DateTime 由
NormalizerBuilder注册的 Transformer 处理,枚举和异常由 Valinor 内置逻辑或适配器处理 - BackedEnum 序列化输出的是枚举值(如
draft),而 Kuiper 序列化器输出枚举名称(如DRAFT);反序列化时 Valinor 只接受枚举值
安装 Valinor
cuyz/valinor 已从 kuiper/serializer 的依赖降为 suggest(可选):默认的 kuiper 序列化器不需要它,只有 SERIALIZER_TYPE=valinor 时才需要。未安装时调用 serializer() 会抛 InvalidArgumentException 并提示 composer require cuyz/valinor。如果项目直接使用 Valinor 适配器:
composer require cuyz/valinorPHP 版本要求
Valinor 2.x 要求 PHP 8.2+(Kuiper 本身要求 PHP 8.1+)。在 PHP 8.1 环境中无法使用 Valinor 适配器。
安装后 Kuiper 框架会自动检测 Valinor,并允许通过 SERIALIZER_TYPE=valinor 切换到 Valinor 适配器。
配置 Valinor 适配器
通过环境变量配置
最简单的切换方式是使用环境变量:
# 切换到 Valinor 序列化器
export SERIALIZER_TYPE=valinor
# 启用 Valinor 缓存(推荐在生产环境使用)
export VALINOR_CACHE_ENABLED=true
# 设置缓存目录
export VALINOR_CACHE_DIR=/var/cache/kuiper/valinor通过配置文件配置
在 src/config.php 中配置 Valinor:
<?php
declare(strict_types=1);
use function kuiper\helper\env;
return [
'application' => [
'serializer' => [
// 切换到 Valinor 适配器
'type' => 'valinor',
// Valinor 特定配置
'valinor' => [
// 启用编译缓存以提高性能
'cache_enabled' => 'true' === env('VALINOR_CACHE_ENABLED', 'false'),
// 缓存目录路径
'cache_dir' => env('VALINOR_CACHE_DIR', 'cache/valinor'),
],
],
],
];通过配置类配置
ValinorSerializerAdapter 构造函数接收两个参数:MapperBuilder 和 NormalizerBuilder(后者用于注册序列化用的 Transformer,如 DateTimeTransformer)。自定义配置类示例:
<?php
declare(strict_types=1);
use CuyZ\Valinor\Cache\FileSystemCache;
use CuyZ\Valinor\MapperBuilder;
use CuyZ\Valinor\NormalizerBuilder;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use kuiper\serializer\adapter\ValinorSerializerAdapter;
use kuiper\serializer\adapter\valinor\DateTimeTransformer;
#[Configuration]
class CustomValinorSerializerConfiguration
{
#[Bean]
public function customValinorSerializer(): ValinorSerializerAdapter
{
$mapperBuilder = (new MapperBuilder())
->allowPermissiveTypes();
// 启用编译缓存
$mapperBuilder = $mapperBuilder->withCache(new FileSystemCache('cache/valinor'));
// 注册 DateTime Transformer,保证 normalize() 输出 RFC3339
$normalizerBuilder = (new NormalizerBuilder())
->registerTransformer(new DateTimeTransformer());
return new ValinorSerializerAdapter($mapperBuilder, $normalizerBuilder);
}
}Valinor 与 Kuiper 序列化器对比
| 特性 | Kuiper Serializer | Valinor 适配器 |
|---|---|---|
| 性能 | 优秀(内置元数据缓存) | 优秀(编译缓存支持) |
| 类型支持 | PHP 8 + PHPDoc 注解 | PHP 8 + 高级类型推断 |
| 错误报告 | 标准异常信息 | 映射错误包装为 SerializeException,原始 MappingError 可通过 getPrevious() 获取 |
| 配置复杂度 | 简单 | 中等 |
| 框架集成 | 深度集成 | 适配器模式 |
| 学习曲线 | 低 | 中等 |
| 适用场景 | 通用场景 | 复杂类型映射 |
| 内存占用 | 低 | 中等 |
| 启动时间 | 快 | 首次较慢(因编译缓存) |
选择建议
使用 Kuiper Serializer 当:
- 需要深度框架集成
- 使用框架内置的 Normalizer 系统
- 配置简单,开箱即用
- 大多数常规序列化场景
- 对启动时间和内存占用有较高要求
使用 Valinor 适配器 当:
- 需要处理复杂的类型映射
- 需要详细的验证错误信息
- 已有 Valinor 使用经验
- 复杂的领域模型映射
- 对类型安全性有更高要求
使用示例
基本使用
在框架中使用 Valinor 序列化器与使用 Kuiper 内置序列化器的方式相同:
<?php
declare(strict_types=1);
namespace App\Service;
use kuiper\serializer\SerializerInterface;
class UserService
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
public function handleUserData(string $json): array
{
// 无论使用哪种序列化器,API 都是一样的
$user = $this->serializer->fromJson($json, User::class);
// 处理用户数据
$processed = $this->processUser($user);
// 序列化回 JSON
return [
'data' => $this->serializer->toJson($processed),
];
}
private function processUser(User $user): ProcessedUser
{
// 处理逻辑
return new ProcessedUser($user);
}
}
class User
{
public function __construct(
public readonly string $name,
public readonly int $age,
public readonly array $preferences,
public readonly ?string $email = null
) {
}
}
class ProcessedUser
{
public function __construct(
public readonly User $original
) {
}
}高级类型映射
Valinor 在处理复杂类型方面表现出色:
<?php
declare(strict_types=1);
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\SerializerInterface;
class OrderService
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
public function createOrder(string $json): Order
{
try {
return $this->serializer->fromJson($json, Order::class);
} catch (SerializeException $error) {
// 适配器把 MappingError 包装为 SerializeException,需从 previous 取出原始错误
$messages = $this->getMappingMessages($error);
$errors = [];
foreach ($messages as $message) {
$errors[] = [
'path' => $message->path(),
'message' => $message->body(),
'source' => $message->sourceValue(),
];
}
throw new \InvalidArgumentException(
'Invalid order data: '.json_encode($errors)
);
}
}
/**
* @return iterable<\CuyZ\Valinor\Mapper\Tree\Message\NodeMessage>
*/
private function getMappingMessages(SerializeException $error): iterable
{
$previous = $error->getPrevious();
return $previous instanceof MappingError ? $previous->messages() : [];
}
}
enum OrderStatus: string
{
case PENDING = 'pending';
case CONFIRMED = 'confirmed';
case SHIPPED = 'shipped';
case DELIVERED = 'delivered';
case CANCELLED = 'cancelled';
}
class Address
{
public function __construct(
public readonly string $street,
public readonly string $city,
public readonly string $zipcode,
public readonly string $country
) {
}
}
class OrderItem
{
public function __construct(
public readonly string $productId,
public readonly string $productName,
public readonly int $quantity,
public readonly float $unitPrice
) {
}
public function getTotal(): float
{
return $this->quantity * $this->unitPrice;
}
}
class Order
{
public function __construct(
public readonly string $orderId,
public readonly \DateTimeImmutable $createdAt,
public readonly OrderStatus $status,
public readonly Address $shippingAddress,
/** @var OrderItem[] */
public readonly array $items,
public readonly ?string $notes = null,
public readonly ?\DateTimeImmutable $updatedAt = null
) {
}
public function getTotalAmount(): float
{
return array_sum(array_map(
fn(OrderItem $item) => $item->getTotal(),
$this->items
));
}
}处理复杂 JSON 数据
<?php
declare(strict_types=1);
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\SerializerInterface;
class DataMigrationService
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
/**
* 从外部 API 迁移复杂的数据结构
*/
public function migrateExternalData(string $externalJson): MigratedData
{
try {
// Valinor 的强大类型推断能力在此处发挥优势
$externalData = $this->serializer->fromJson(
$externalJson,
ExternalApiResponse::class
);
// 转换为内部数据结构
return $this->convertToInternalFormat($externalData);
} catch (SerializeException $error) {
// 详细的错误报告有助于调试数据格式问题
$this->logDetailedMappingErrors($error);
throw $error;
}
}
private function convertToInternalFormat(ExternalApiResponse $external): MigratedData
{
// 转换逻辑
return new MigratedData(/* ... */);
}
private function logDetailedMappingErrors(SerializeException $error): void
{
$previous = $error->getPrevious();
if (!$previous instanceof MappingError) {
error_log('Mapping failed: '.$error->getMessage());
return;
}
foreach ($previous->messages() as $message) {
error_log(sprintf(
"Mapping error at %s: %s (%s)",
$message->path(),
$message->body(),
$message->sourceValue()
));
}
}
}
/**
* 表示外部 API 的复杂响应结构
*/
class ExternalApiResponse
{
public function __construct(
public readonly int $id,
public readonly string $type,
public readonly array $attributes, // 包含各种不同类型的属性
public readonly ?array $relationships, // 关联数据
public readonly Meta $meta, // 元数据
public readonly Links $links // 分页链接
) {
}
}
class Meta
{
public function __construct(
public readonly int $timestamp,
public readonly ?string $version = null,
public readonly array $counts = []
) {
}
}
class Links
{
public function __construct(
public readonly string $self,
public readonly ?string $first = null,
public readonly ?string $last = null,
public readonly ?string $prev = null,
public readonly ?string $next = null
) {
}
}
class MigratedData
{
// 内部数据结构定义
}错误处理
Valinor 特有的错误处理
适配器在 denormalize() 中用 catch (\Throwable) 统一包装错误,因此调用方只会收到 SerializeException,不会直接捕获到 MappingError。原始 MappingError 保存在 getPrevious() 中,从中可以获取:
- 精确的错误位置:
NodeMessage::path() - 错误类型/期望签名:
NodeMessage::type() - 源数据引用:
NodeMessage::sourceValue()(已字符串化) - 错误描述:
NodeMessage::body()
MappingError 没有 node()->dump()
Valinor 2.x 的 MappingError 只提供 messages()、type()、source();NodeMessage 也没有 dump()。调试时请遍历 messages() 读取 path()/body()/sourceValue()。
<?php
declare(strict_types=1);
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\SerializerInterface;
class RobustApiService
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
public function handleApiRequest(string $json, string $targetClass): mixed
{
try {
return $this->serializer->fromJson($json, $targetClass);
} catch (SerializeException $error) {
// 使用 Valinor 的详细错误报告功能
$detailedErrors = $this->extractDetailedErrors($error);
// 记录错误详情用于调试
error_log(sprintf(
'Serialization mapping failed: %s',
json_encode($detailedErrors, JSON_UNESCAPED_UNICODE)
));
// 返回用户友好的错误信息
return $this->createErrorResponse($detailedErrors);
}
}
/**
* @return list<array{path: string, type: string, message: string, source: string}>
*/
private function extractDetailedErrors(SerializeException $error): array
{
$previous = $error->getPrevious();
if (!$previous instanceof MappingError) {
return [[
'path' => '',
'type' => '',
'message' => $error->getMessage(),
'source' => '',
]];
}
$errors = [];
foreach ($previous->messages() as $message) {
$errors[] = [
'path' => $message->path(),
'type' => $message->type(),
'message' => $message->body(),
'source' => $message->sourceValue(),
];
}
return $errors;
}
private function createErrorResponse(array $detailedErrors): array
{
return [
'success' => false,
'error_code' => 'VALIDATION_ERROR',
'errors' => array_map(function ($error) {
return [
'field' => $error['path'],
'message' => $error['message'],
'expected_type' => $error['type'],
];
}, $detailedErrors),
];
}
}性能考虑
缓存策略
Valinor 使用编译缓存来优化性能。首次映射可能较慢,但后续相同结构的映射会非常快速:
// 首次映射(较慢 - 需要编译类型)
$order = $serializer->fromJson($json, Order::class);
// 后续映射(非常快 - 使用编译缓存)
$order2 = $serializer->fromJson($differentJson, Order::class);启用缓存的配置
为了最大化性能,建议在生产环境中启用 Valinor 缓存:
# 生产环境配置
export SERIALIZER_TYPE=valinor
export VALINOR_CACHE_ENABLED=true
export VALINOR_CACHE_DIR=/var/cache/kuiper/valinor缓存目录权限
确保缓存目录有适当的读写权限:
mkdir -p /var/cache/kuiper/valinor
chown -R www-data:www-data /var/cache/kuiper
chmod -R 755 /var/cache/kuiper最佳实践
1. 合理使用 Valinor 的错误报告
利用 Valinor 详细的错误信息来改进数据验证和错误处理:
<?php
declare(strict_types=1);
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\SerializerInterface;
class DataProcessor
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
/**
* 安全地处理未知格式的数据
*/
public function processUnknownFormat(string $rawData, string $className): ?object
{
try {
return $this->serializer->fromJson($rawData, $className);
} catch (SerializeException $error) {
// 详细记录映射错误
$this->logMappingError($error, $className, $rawData);
// 在开发环境中显示详细错误
if ('dev' === ($_ENV['APP_ENV'] ?? 'prod')) {
throw $error;
}
// 生产环境中返回安全的错误信息
return null;
}
}
private function logMappingError(
SerializeException $error,
string $className,
string $rawData
): void {
$previous = $error->getPrevious();
$messages = $previous instanceof MappingError
? iterator_to_array($previous->messages())
: [];
$bodies = array_map(
static fn ($message) => $message->body(),
$messages
);
error_log(sprintf(
'Serialization error in %s: %s. Raw data: %s',
$className,
implode(', ', $bodies ?: [$error->getMessage()]),
substr($rawData, 0, 200).(strlen($rawData) > 200 ? '...' : '')
));
}
}2. 自定义 NormalizerBuilder(注册 Transformer)
Valinor 适配器不经过 Kuiper Normalizer。序列化(normalize()/toJson())阶段的特殊类型转换由注册到 NormalizerBuilder 的 Transformer 完成,例如 DateTimeTransformer:
<?php
declare(strict_types=1);
use CuyZ\Valinor\Cache\FileSystemCache;
use CuyZ\Valinor\MapperBuilder;
use CuyZ\Valinor\NormalizerBuilder;
use kuiper\serializer\adapter\ValinorSerializerAdapter;
use kuiper\serializer\adapter\valinor\DateTimeTransformer;
$adapter = new ValinorSerializerAdapter(
(new MapperBuilder())
->allowPermissiveTypes()
->withCache(new FileSystemCache('cache/valinor')),
(new NormalizerBuilder())
->registerTransformer(new DateTimeTransformer())
);必须传实例而不是类名
registerTransformer() 必须传入 Transformer 实例:类字符串不是 callable,Valinor 会把它登记成属性型 Transformer,全局转换不生效。
3. 渐进式迁移
可以在不改变应用代码的情况下在两种序列化器之间切换。业务代码始终注入 SerializerInterface,只切换环境变量:
# 使用 Kuiper Serializer
export SERIALIZER_TYPE=kuiper
# 使用 Valinor 适配器
export SERIALIZER_TYPE=valinor4. 监控和调试
Valinor 提供了丰富的调试信息,可用于性能和错误监控:
<?php
declare(strict_types=1);
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\SerializerInterface;
use Psr\Log\LoggerInterface;
class MonitoredSerializer
{
public function __construct(
private readonly SerializerInterface $serializer,
private readonly LoggerInterface $logger
) {
}
public function safeDeserialize(string $json, string $className): ?object
{
$start = microtime(true);
try {
$result = $this->serializer->fromJson($json, $className);
$duration = microtime(true) - $start;
$this->logger->info(sprintf(
'Deserialization successful for %s in %.2fms',
$className,
$duration * 1000
));
return $result;
} catch (SerializeException $error) {
$duration = microtime(true) - $start;
$this->logger->error(sprintf(
'Deserialization failed for %s after %.2fms: %s',
$className,
$duration * 1000,
$this->formatValinorError($error)
));
return null;
}
}
private function formatValinorError(SerializeException $error): string
{
$previous = $error->getPrevious();
if (!$previous instanceof MappingError) {
return $error->getMessage();
}
return implode('; ', array_map(
static fn ($message) => $message->body(),
iterator_to_array($previous->messages())
));
}
}故障排除
常见问题
Q: 启用 Valinor 后应用启动变慢?
A: 这是正常的,因为 Valinor 需要在第一次使用时编译类型映射。在生产环境中,启用缓存后性能会显著提升。
Q: 某些对象无法正确序列化?
A: 检查对象的类型定义是否符合 Valinor 的要求。Valinor 对类型的要求比 Kuiper 内置序列化器更严格。
Q: 如何在不中断服务的情况下切换序列化器?
A: 使用环境变量切换,因为这不会改变代码,只是改变依赖注入容器中注册的具体实现。
Q: Valinor 缓存文件过多怎么办?
A: 定期清理缓存目录,或配置适当的 TTL 策略。
调试技巧
要调试 Valinor 映射过程,从 SerializeException 中取出原始 MappingError,遍历消息树:
use CuyZ\Valinor\Mapper\MappingError;
use kuiper\serializer\exception\SerializeException;
try {
$result = $serializer->fromJson($json, MyClass::class);
} catch (SerializeException $error) {
$previous = $error->getPrevious();
if ($previous instanceof MappingError) {
foreach ($previous->messages() as $message) {
echo sprintf(
"path=%s type=%s message=%s source=%s\n",
$message->path(),
$message->type(),
$message->body(),
$message->sourceValue()
);
}
} else {
echo $error->getMessage(), "\n";
}
}性能基准测试
你可以创建一个简单的基准测试来比较两种序列化器的性能:
<?php
declare(strict_types=1);
use kuiper\serializer\SerializerInterface;
class SerializerBenchmark
{
public function __construct(
private readonly SerializerInterface $serializer
) {
}
public function benchmarkDeserialization(string $json, string $className, int $iterations = 1000): array
{
$times = [];
// 预热
$this->serializer->fromJson($json, $className);
for ($i = 0; $i < $iterations; $i++) {
$start = microtime(true);
$this->serializer->fromJson($json, $className);
$times[] = (microtime(true) - $start) * 1000; // 转换为毫秒
}
return [
'average_ms' => array_sum($times) / count($times),
'min_ms' => min($times),
'max_ms' => max($times),
'total_ms' => array_sum($times),
];
}
}总结
Valinor 序列化适配器为 Kuiper 框架提供了一个强大的备选序列化解决方案,特别适合需要处理复杂类型映射和要求详细错误报告的应用场景。通过简单的配置切换,你可以在 Kuiper 内置序列化器和 Valinor 适配器之间灵活选择,而无需修改任何业务代码。
记住,选择序列化器的关键在于了解你的具体需求:如果需要高级类型处理和详细错误信息,则选择 Valinor;如果需要简单易用和轻量级实现,则使用 Kuiper 内置序列化器。