anteris-dev / reflection-finder
帮助您找到所需的类。
Requires
- php: 8.0
- ramsey/collection: ^1.1
- symfony/filesystem: ^5.2
- symfony/finder: ^5.2
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-08-27 08:19:10 UTC
README
帮助您找到所需的类。
入门
此包引入了一个类似于Symfony的查找器,用于反射类。它允许您根据某些搜索参数(例如命名空间、父类等)搜索和检索PHP类的反射类,并允许您从文件系统内容中创建反射对象。
安装方法
composer require anteris-dev/reflection-finder:dev-master
基本用法
要开始使用,可以通过调用静态new()
方法或创建类的实例来创建该类的新实例。
例如
use Anteris\ReflectionFinder\Finder; $finder = new Finder; // OR $finder = Finder::new();
创建查找器对象实例后,您有以下搜索方法可供选择。
class($className)
- 将返回结果限制为传递的FQDN或短名所属的类。extends($className)
- 将返回结果限制为扩展传递的类FQDN的类。filter(callable $callback)
- 允许您指定一个自定义过滤器。回调函数接收一个参数,该参数将是\ReflectionClass
的实例。如果函数返回true,则类将被包含,否则将不会。hasConstant($constantName)
- 将返回结果限制为具有传递名称的常量的类。hasMethod($methodName)
- 将返回结果限制为具有传递名称的方法的类。hasProperty($propertName)
- 将返回结果限制为具有传递名称的属性的类。implements($interfaceName)
- 将返回结果限制为实现传递的接口FQDN的类。in(string $directory)
- 在传递的目录中启动类的搜索。返回ReflectionClasses集合。namespace($namespace)
- 将返回结果限制为位于传递的命名空间下的类。uses($traitName)
- 将返回结果限制为使用传递的特质FQDN的类。
以下是如何使用这些方法的示例。
// Searches for classes with the namespace of "Test" in the current directory $classes = Finder::new()->namespace('Test')->in(__DIR__); // Searches for classes with the properties "firstName" AND "lastName" defined $classes = Finder::new()->property('firstName')->property('lastName')->in(__DIR__); // Runs a custom check against the reflection class' filename $classes = Finder::new() ->filter(function (\ReflectionClass $reflection) { if (str_contains($reflection->getFileName(), 'Test.php')) { return false; } return true; })->in(__DIR__);
文件系统操作
当返回in()
方法时,返回一个Anteris\ReflectionFinder\Collection\ReflectionCollection
的实例。这是一个可迭代的集合,包含Anteris\ReflectionFinder\Reflection\ReflectionClass
的实例。
Anteris\ReflectionFinder\Reflection\ReflectionClass
扩展了\ReflectionClass
并为构建任何反射工具提供了以下方法。请注意,这些方法可能会破坏您使用PSR-4等时类的可用性。
copy(string $targetFile, bool $overwriteNewerFiles = false)
- 将类文件复制到指定的目标文件。rename(string $target, bool $overwrite = false)
- 将类文件重命名为指定的目标文件。remove()
- 从文件系统中删除类。
高级功能
此包使用LoadingStrategy
类来确定如何将文件对象解析为ReflectionClass。默认情况下,此包附带一个Psr4LoadingStrategy
类,允许它从任何使用Symfony的查找器找到的文件中获取正确的类FQDN。您可以通过实现Anteris\ReflectionFinder\LoadingStrategyInterface
并传递其实例给Finder::registerLoadingStrategy()
来创建自己的LoadingStrategy。
例如
use Anteris\ReflectionFinder\Finder; use Anteris\ReflectionFinder\LoadingStrategy\LoadingStrategyInterface; class MyCustomLoadingStrategy implements LoadingStrategyInterface { public function resolve(string $directory): ReflectionCollection { // ...do something here } } $finder = Finder::new()->registerLoadingStrategy(new MyCustomLoadingStrategy); // Use your finder here...
有关更多信息,请查看Anteris\ReflectionFinder\Psr4LoadingStrategy
类。