反射模块
Kuiper 反射模块提供了强大的 PHP 类型解析和 PHPDoc 处理功能,支持 PHP 8 类型系统和 PHPStan 类型注解。
特性
- ✅ PHP 8 类型解析: 完整支持 PHP 8 的类型系统,包括联合类型、可空类型等
- ✅ PHPDoc 处理: 基于 PHPStan/phpdoc-parser 的 PHPDoc 注解解析
- ✅ 类型过滤器: 灵活的类型验证和数据清理系统
- ✅ 类型系统: 完整的类型层次结构,支持基本类型、复合类型、特殊类型
- ✅ 缓存支持: LRU 缓存和无限制缓存模式,提高解析性能
- ✅ 类名解析: 智能的完全限定类名(FQCN)解析,支持 use 语句
- ✅ 扩展性: 支持自定义类型解析器和类型过滤器
架构
反射模块的核心组件:
text
ReflectionType
├── PhpstanTypeParser (类型解析器)
├── ReflectionDocBlockFactory (PHPDoc 工厂)
├── TypeFilterRegistry (类型过滤器注册表)
└── Type Hierarchy (类型层次结构)
├── PrimitiveType (基本类型)
├── ArrayType (数组类型)
├── MapType (映射类型)
├── ClassType (类类型)
├── CompositeType (联合类型)
└── Special Types (特殊类型)快速开始
基本类型解析
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 从类型字符串解析
$type = ReflectionType::parse('string');
echo $type->getName(); // "string"
echo $type->isScalar(); // true
// 解析可空类型
$type = ReflectionType::parse('?int');
echo $type->allowsNull(); // true
// 解析联合类型
$type = ReflectionType::parse('string|int');
echo $type->isComposite(); // true从 PHP 反射创建
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
use ReflectionClass;
use ReflectionMethod;
class Example
{
public function process(string|array $data): ?int
{
return null;
}
}
// 从方法参数解析类型
$method = new ReflectionMethod('Example', 'process');
$parameter = $method->getParameters()[0];
$type = ReflectionType::fromPhpType($parameter->getType());
echo $type; // "string|int"
// 从返回值类型解析
$returnType = ReflectionType::fromPhpType($method->getReturnType());
echo $returnType; // "?int"PHPDoc 解析
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
/**
* @param array<string, int> $data 数据数组
* @return User|null 用户对象
*/
class UserRepository
{
public function findById(int $id): ?User
{
return null;
}
}
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 解析方法文档块
$method = new ReflectionMethod('UserRepository', 'findById');
$docBlock = $factory->createMethodDocBlock($method);
// 获取参数类型
$paramType = $docBlock->getParameterTypes()['id'];
echo $paramType->getName(); // "int"
// 获取返回值类型
$returnType = $docBlock->getReturnType();
echo $returnType; // "?User"类型系统
反射模块实现了完整的 PHP 类型层次结构:
基本类型 (Primitive Types)
- IntegerType: 整数类型 (
int) - FloatType: 浮点类型 (
float) - StringType: 字符串类型 (
string) - BooleanType: 布尔类型 (
bool) - NullType: 空类型 (
null)
复合类型 (Compound Types)
- ArrayType: 数组类型 (
array,string[],array<int>) - MapType: 映射类型 (
array<string, int>) - ObjectType: 对象类型 (
object)
类类型 (Class Types)
- ClassType: 具体类类型 (
DateTime,App\User) - ObjectShapeType: 对象形状类型 (
object{string id, int age})
特殊类型 (Special Types)
- MixedType: 混合类型 (
mixed) - VoidType: 无返回值类型 (
void) - CallableType: 可调用类型 (
callable) - IterableType: 可迭代类型 (
iterable) - ResourceType: 资源类型 (
resource)
联合类型 (Composite Types)
- CompositeType: 联合类型 (
string|int,null|bool|string)
类型检查
类型验证
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
$type = ReflectionType::parse('string');
// 检查类型
echo $type->isScalar(); // true
echo $type->isPrimitive(); // true
echo $type->isArray(); // false
echo $type->isClass(); // false
// 值验证
echo $type->isValid('hello'); // true
echo $type->isValid(123); // false类型比较
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
$type1 = ReflectionType::parse('string');
$type2 = ReflectionType::parse('string');
$type3 = ReflectionType::parse('?string');
echo $type1->equals($type2); // true
echo $type1->equals($type3); // false (可空性不同)高级功能
类型过滤器
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
use kuiper\reflection\TypeFilterRegistryInterface;
use kuiper\reflection\DefaultTypeFilterRegistry;
use kuiper\reflection\type\StringType;
// 创建自定义类型过滤器
class StringFilter implements \kuiper\reflection\TypeFilterInterface
{
public function isValid(mixed $value): bool
{
return is_string($value) && strlen($value) > 0;
}
public function sanitize(mixed $value): mixed
{
return is_string($value) ? trim($value) : $value;
}
}
// 注册类型过滤器(按「类型类名 + 过滤器类名」注册,不是按实例注册)
$registry = new DefaultTypeFilterRegistry();
$registry->register(StringType::class, StringFilter::class);
ReflectionType::setFilterRegistry($registry);
// 使用类型过滤器
$type = ReflectionType::parse('string');
echo $type->sanitize(' hello '); // "hello"自定义类型解析器
php
<?php
declare(strict_types=1);
use kuiper\reflection\parser\PhpstanTypeParser;
use kuiper\reflection\ReflectionType;
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\reflection\TypeParserInterface;
// 创建自定义类型解析器
// 注意:不要在 parse() 里回调 ReflectionType::parse()——那会再次进入本解析器,
// 造成无限递归。需要默认行为时委托给 PhpstanTypeParser。
class CustomTypeParser implements TypeParserInterface
{
private PhpstanTypeParser $default;
public function __construct()
{
$this->default = new PhpstanTypeParser();
}
public function parse(string $typeString): ReflectionTypeInterface
{
// 自定义解析逻辑(示例:先交给默认解析器)
return $this->default->parse($typeString);
}
}
// 设置自定义解析器
ReflectionType::setParser(new CustomTypeParser());
// 使用自定义解析器
$type = ReflectionType::parse('string');
// 恢复默认解析器(setParser 的参数不可为 null)
ReflectionType::setParser(new PhpstanTypeParser());性能优化
LRU 缓存
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
// 创建具有 LRU 缓存的工厂(最多缓存 1000 个条目)
$factory = new ReflectionDocBlockFactory(
1000,
new UseStatementCache()
);
// 获取缓存统计信息
$stats = $factory->getCacheStats();
echo $stats['mode']; // "lru"
echo $stats['size']; // 当前缓存大小
echo $stats['max_size']; // 最大缓存大小清除缓存
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 清除所有缓存
$factory->clearCache();最佳实践
1. 显式创建工厂实例
php
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
// ✅ 推荐显式创建实例并注入依赖
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());2. 缓存解析结果
php
// 工厂内部使用 LRU 缓存,重复解析不会损失性能
// 缓存大小在构造函数中指定
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());3. 使用类型检查
php
// 在处理数据前先检查类型
if ($type->allowsNull()) {
// 处理可空情况
}
if ($type->isComposite()) {
// 处理联合类型
foreach ($type->getTypes() as $subType) {
// ...
}
}文档导航
- 类型解析 - 详细的类型解析说明
- PHPDoc 处理 - PHPDoc 注解处理
- ReflectionNamespace - 命名空间类元数据获取
- 测试 - 反射模块测试指南