ReflectionNamespace
ReflectionNamespace 类用于通过静态分析获取指定命名空间下的所有类元数据,支持文件缓存以提高性能。它是组件扫描和类发现机制的核心组件。
特性
- 零代码执行: 使用静态分析获取类元数据,不执行类代码
- Composer 集成: 自动从 Composer ClassLoader 获取 PSR-4 命名空间映射
- 两级缓存: 本地内存缓存 + PSR-6 文件缓存
- 缓存失效: 基于文件修改时间签名的自动缓存失效机制
- 安全验证: 文件内容验证,防止代码注入攻击
基本用法
从 ClassLoader 创建实例
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
// 获取 Composer ClassLoader
$loader = require_once __DIR__ . '/vendor/autoload.php';
// 创建 ReflectionNamespace 实例
$reflectionNs = new ReflectionNamespace($loader);
// 获取指定命名空间下的所有类
$classes = $reflectionNs->getClasses(['App\\Controller']);
foreach ($classes as $className => $metadata) {
echo "Class: $className\n";
echo "File: " . $metadata->getFileName() . "\n";
// ClassMetadata 没有方法列表 API,方法通过 toReflectionClass() 获取
echo "Methods: " . count($metadata->toReflectionClass()->getMethods()) . "\n";
}手动注册命名空间目录
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
$loader = require_once __DIR__ . '/vendor/autoload.php';
$reflectionNs = new ReflectionNamespace($loader);
// 手动注册额外的命名空间目录
$reflectionNs->register('Custom\\Namespace', '/path/to/custom/src');
// 获取类元数据
$classes = $reflectionNs->getClasses(['Custom\\Namespace']);获取类元数据
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
$loader = require_once __DIR__ . '/vendor/autoload.php';
$reflectionNs = new ReflectionNamespace($loader);
// 获取多个命名空间的类
$classes = $reflectionNs->getClasses([
'App\\Controller',
'App\\Service',
'App\\Repository',
]);
// 遍历类元数据
foreach ($classes as $className => $metadata) {
// 检查类属性
if ($metadata->hasAttribute('Component')) {
echo "Found component: $className\n";
}
// 获取类的方法(经 toReflectionClass() 得到 ReflectionClass)
foreach ($metadata->toReflectionClass()->getMethods() as $method) {
echo " Method: " . $method->getName() . "\n";
// 检查方法属性
if ($method->getAttributes(GetMapping::class) !== []) {
echo " - Has GetMapping attribute\n";
}
}
}缓存配置
本地内存缓存
本地缓存自动启用,基于目录哈希存储在内存中:
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
$loader = require_once __DIR__ . '/vendor/autoload.php';
$reflectionNs = new ReflectionNamespace($loader);
// 第一次调用会分析目录
$classes = $reflectionNs->getClasses(['App\\Controller']);
// 第二次调用会使用本地缓存(同一请求内)
$classes = $reflectionNs->getClasses(['App\\Controller']);PSR-6 文件缓存配置
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\RedisDriver;
$loader = require_once __DIR__ . '/vendor/autoload.php';
// 创建 PSR-6 缓存实例
$cache = new CacheItemPool(new RedisDriver([
'host' => 'localhost',
'port' => 6379,
]));
// 创建带缓存的 ReflectionNamespace
$reflectionNs = new ReflectionNamespace($loader, $cache);
// 类元数据会被缓存到 Redis
$classes = $reflectionNs->getClasses(['App\\Controller']);缓存失效机制
php
<?php
declare(strict_types=1);
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\FileDriver;
$loader = require_once __DIR__ . '/vendor/autoload.php';
// 使用文件缓存
$cache = new CacheItemPool(new FileDriver([
'dir' => __DIR__ . '/cache/reflection',
]));
$reflectionNs = new ReflectionNamespace($loader, $cache);
// 获取类元数据
$classes = $reflectionNs->getClasses(['App\\Controller']);
// 缓存会自动失效:
// - 当源文件被修改时,基于文件修改时间签名验证
// - 当缓存过期时(默认 1 小时 TTL)完整示例
基础使用示例
php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
/**
* 示例:扫描控制器命名空间
*/
function scanControllers(ClassLoader $loader): array
{
$reflectionNs = new ReflectionNamespace($loader);
// 获取所有控制器类
$controllers = [];
$classes = $reflectionNs->getClasses(['App\\Controller']);
foreach ($classes as $className => $metadata) {
// 检查是否有 Controller 属性
if ($metadata->hasAttribute('Controller')) {
$controllers[] = [
'class' => $className,
'file' => $metadata->getFileName(),
'methods' => array_map(
fn (\ReflectionMethod $method): string => $method->getName(),
$metadata->toReflectionClass()->getMethods()
),
];
}
}
return $controllers;
}
// 使用示例
$loader = require_once __DIR__ . '/vendor/autoload.php';
$controllers = scanControllers($loader);
print_r($controllers);带缓存的配置示例
php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\FileDriver;
/**
* 创建带缓存的 ReflectionNamespace
*/
function createCachedReflectionNamespace(
ClassLoader $loader,
string $cachePath
): ReflectionNamespace {
// 创建文件缓存
$cache = new CacheItemPool(new FileDriver([
'dir' => $cachePath,
]));
return new ReflectionNamespace($loader, $cache);
}
// 使用示例
$loader = require_once __DIR__ . '/vendor/autoload.php';
$reflectionNs = createCachedReflectionNamespace(
$loader,
__DIR__ . '/cache/reflection'
);
// 第一次调用会分析并缓存
$start = microtime(true);
$classes = $reflectionNs->getClasses(['App\\Controller']);
$firstTime = microtime(true) - $start;
echo "First call: {$firstTime}s\n";
// 后续调用会使用缓存(跨请求)
$start = microtime(true);
$classes = $reflectionNs->getClasses(['App\\Controller']);
$cachedTime = microtime(true) - $start;
echo "Cached call: {$cachedTime}s\n";
echo "Speedup: " . round($firstTime / $cachedTime, 2) . "x\n";与 ComponentScanner 集成示例
php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Composer\Autoload\ClassLoader;
use kuiper\reflection\ReflectionNamespace;
use kuiper\di\ComponentCollection;
use kuiper\di\ComponentScanner;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\FileDriver;
/**
* 配置 ComponentScanner 使用带缓存的组件扫描
*/
function configureComponentScanner(ClassLoader $loader): ComponentScanner
{
// 创建文件缓存
$cache = new CacheItemPool(new FileDriver([
'dir' => __DIR__ . '/cache/component-scan',
]));
// 创建 ComponentScanner(构造函数需要 ClassLoader 与 ComponentCollection)
return new ComponentScanner(
$loader,
new ComponentCollection(),
$cache
);
}
// 使用示例
$loader = require_once __DIR__ . '/vendor/autoload.php';
$scanner = configureComponentScanner($loader);
// 扫描组件(scan() 无参数,扫描结果注册到 ComponentCollection)
$scanner->scan();
$components = ComponentCollection::getInstance()->getComponents(\kuiper\di\attribute\Component::class);
echo "Found " . count($components) . " components\n";注意:
ComponentScanner的构造函数需要ClassLoader与ComponentCollection两个必填参数;scan()不接受参数、返回void,扫描结果注册到ComponentCollection单例中。排除命名空间请通过ContainerBuilder::componentScanExclude()或ComponentScannerBuilder::excludeNamespace()配置。
API 参考
构造函数
php
public function __construct(
ClassLoader $classLoader,
?CacheItemPoolInterface $fileCache = null,
?StaticClassAnalyzer $staticAnalyzer = null,
)参数说明:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
$classLoader | ClassLoader | 是 | Composer ClassLoader 实例 |
$fileCache | ?CacheItemPoolInterface | 否 | PSR-6 缓存接口,用于文件缓存 |
$staticAnalyzer | ?StaticClassAnalyzer | 否 | 静态分析器,默认创建新实例 |
方法列表
register
php
public function register(string $namespace, string $dir): static注册命名空间目录映射。
参数:
$namespace: 命名空间(例如:App\\Controller)$dir: 目录路径(例如:/path/to/src/Controller)
返回值: $this,支持链式调用
示例:
php
$reflectionNs
->register('App\\Controller', __DIR__ . '/src/Controller')
->register('App\\Service', __DIR__ . '/src/Service');getClasses
php
public function getClasses(array $namespaces): array获取指定命名空间下的所有类元数据。
参数:
$namespaces: 命名空间数组
返回值:
- 键:类名(完全限定名)
- 值:
ReflectionClassInterface(ClassMetadata 实例)
示例:
php
$classes = $reflectionNs->getClasses(['App\\Controller', 'App\\Service']);
foreach ($classes as $className => $metadata) {
echo $className . "\n";
}最佳实践
缓存策略建议
开发环境: 禁用文件缓存或设置短 TTL
php// 开发环境:禁用缓存 $reflectionNs = new ReflectionNamespace($loader);生产环境: 启用文件缓存,设置合理 TTL
php// 生产环境:启用缓存 $cache = new CacheItemPool(new FileDriver(['dir' => '/var/cache/kuiper'])); $reflectionNs = new ReflectionNamespace($loader, $cache);缓存预热: 在部署时预热缓存
php// 部署脚本中预热缓存 $reflectionNs->getClasses(['App\\Controller']); $reflectionNs->getClasses(['App\\Service']);
性能优化提示
批量获取: 一次性获取多个命名空间,减少 I/O
php// ✅ 推荐:批量获取 $classes = $reflectionNs->getClasses([ 'App\\Controller', 'App\\Service', 'App\\Repository', ]); // ❌ 避免:多次单独获取 $controllers = $reflectionNs->getClasses(['App\\Controller']); $services = $reflectionNs->getClasses(['App\\Service']);合理命名空间范围: 避免扫描过大的命名空间
php// ✅ 推荐:精确的命名空间 $classes = $reflectionNs->getClasses(['App\\Controller\\Api']); // ❌ 避免:过于宽泛的命名空间 $classes = $reflectionNs->getClasses(['App']);使用单例: 在应用中共享 ReflectionNamespace 实例
php// ✅ 推荐:单例模式 class ReflectionNamespaceProvider { private static ?ReflectionNamespace $instance = null; public static function getInstance(): ReflectionNamespace { if (self::$instance === null) { $loader = require_once __DIR__ . '/vendor/autoload.php'; self::$instance = new ReflectionNamespace($loader); } return self::$instance; } }
安全注意事项
ReflectionNamespace 包含多层安全保护:
- 文件内容验证: 只加载包含类/接口/特质声明的文件
- 危险代码检测: 检测
eval()、assert()等危险函数 - 路径验证: 使用
realpath()验证目录路径 - 异常处理: 加载失败时记录错误而不是终止执行
更多资源
- 反射模块概述 - 反射模块完整介绍
- 类型解析 - 详细的类型解析说明
- PHPDoc 处理 - PHPDoc 注解处理
- PSR-6: Caching Interface - PSR-6 缓存标准