mingyuanyun / parser-reflection
提供基于原始源代码的反射信息
Requires
- php: >=7.0
- nikic/php-parser: ^4.0 <4.7.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2021-10-13 12:40:15 UTC
README
Parser Reflection API 库提供了一组扩展原始内部反射类的类,但由 PHP-Parser 库提供动力,从而允许在不将类加载到内存中时创建反射实例。
此库可用于分析 PHP 5.5、5.6、7.0 版本的源代码;用于自动代理创建等。
安装
可以使用 Composer 安装此库。安装非常简单
$ composer require goaop/parser-reflection
Composer 将将库安装到您的项目的 vendor/goaop/parser-reflection
目录。
使用
初始化
在首次使用库之前,可以可选地初始化。如果您使用 Composer 安装包和加载类,则无需担心初始化,库将自动初始化。
如果项目使用自定义自动加载器,则应遵循以下步骤
- 创建一个实现
\Go\ParserReflection\LocatorInterface
的新类 - 创建该类的实例并将其传递给
ReflectionEngine::init()
方法以进行初始配置
不加载具体类/方法/属性进行反射
只需像传统类一样使用 Go\ParserReflection
包的反射类
$parsedClass = new \Go\ParserReflection\ReflectionClass(SomeClass::class);
var_dump($parsedClass->getMethods());
$parsedMethod = new \Go\ParserReflection\ReflectionMethod(SomeClass::class, 'someMethod');
echo (string)$parsedMethod;
或者,您可以使用额外的类 [ReflectionFile
](docs/reflection_file.md) 和 ReflectionFileNamespace
来分析原始 PHP 文件
$parsedFile = new \Go\ParserReflection\ReflectionFile('SomeClass.php');
$fileNameSpaces = $parsedFile->getFileNamespaces();
// We can iterate over namespaces in the file
foreach ($fileNameSpaces as $namespace) {
$classes = $namespace->getClasses();
// Iterate over the classes in the namespace
foreach ($classes as $class) {
echo "Found class: ", $class->getName(), PHP_EOL;
// Now let's show all methods in the class
foreach ($class->getMethods() as $method) {
echo "Found class method: ", $class->getName(), '::', $method->getName(), PHP_EOL;
}
// ...all properties in the class
foreach ($class->getProperties() as $property) {
echo "Found class property: ", $class->getName(), '->', $property->getName(), PHP_EOL;
}
}
}
它是如何工作的?
为了了解库是如何工作的,让我们看看在调用 new \Go\ParserReflection\ReflectionClass(SomeClass::class)
时会发生什么
\Go\ParserReflection\ReflectionClass
要求反射引擎为给定的类名提供一个 AST 节点- 反射引擎要求定位器为给定的类定位一个文件名
ComposerLocator
实例要求 Composer 为给定的类查找文件名并将此结果返回给反射引擎- 反射引擎加载文件的内容并将其传递给 PHP-Parser 进行标记化和处理
- PHP-Parser 返回一个 AST(抽象语法树)
- 然后反射引擎分析此 AST 以提取特定节点并将它们包装到相应的反射类中。
兼容性
所有解析反射类都扩展了 PHP 内部反射类,这意味着您可以在需要 \ReflectionClass
实例的任何地方使用 \Go\ParserReflection\ReflectionClass
实例。所有反射方法都应与原始方法兼容,提供不需要对象操作的方法,例如 invoke()
、invokeArgs()
、setAccessible()
等。这些方法将触发类的自动加载并切换到内部反射。