console-helpers / parser-reflection
4.0.0-RC2
2024-03-18 21:43 UTC
Requires
- php: >=8.2
- nikic/php-parser: ^5.0
Requires (Dev)
- phpunit/phpunit: ^10.5.8
- rector/rector: ^1.0
- rector/rector-php-parser: ^0.14.0
- tracy/tracy: ^2.10
- dev-master / 4.x-dev
- 4.0.0-RC2
- 4.0.0-RC1
- 3.x-dev
- 3.0.1
- 3.0.0
- 3.0.0-RC1
- 2.x-dev
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.0
- 1.x-dev
- 1.4.1
- 1.4.0
- 1.3.0
- 1.2.1
- 1.2.0
- 1.1.0
- 1.0.2
- 1.0.1
- 1.0.0
- 1.0.0-alpha
- 0.6.0
- 0.5.0
- dev-feature/ast-preserving-node-resolving
- dev-dependabot/composer/phpunit/phpunit-tw-9.5
- dev-fix/is-subclass-of
This package is auto-updated.
Last update: 2024-05-04 08:29:39 UTC
README
此库已被弃用。请使用BetterReflection。
解析反射API库提供了一组类,这些类扩展了原始内部反射类,但由PHP-Parser库提供支持,因此可以在不将类加载到内存中的情况下创建反射实例。
此库可用于分析源代码;用于自动代理创建等等。
安装
可以使用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
和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()
等。这些方法将触发类加载过程并切换到内部反射。