baraja-core/class-map-generator
Composer 安装命令:
composer require baraja-core/class-map-generator
包简介
Find all classes in specific directory.
README 文档
README
A lightweight PHP library for scanning directories and generating a complete map of all PHP classes, interfaces, and traits with their corresponding file paths.
🎯 Key Features
- Recursive directory scanning - Automatically traverses all subdirectories to find PHP files
- Token-based parsing - Uses PHP's native
token_get_all()for reliable class detection - Full namespace support - Correctly resolves fully qualified class names with namespaces
- Supports all class types - Detects classes, interfaces, and traits
- Memory efficient - Includes garbage collection optimization for large codebases
- Zero dependencies - Pure PHP implementation with no external requirements
- PHP 8.0+ compatible - Built for modern PHP applications
🏗️ Architecture
The library consists of a single, focused class that handles all scanning and parsing logic:
┌─────────────────────────────────────────────────────────────────┐
│ ClassMapGenerator │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌──────────────────┐ ┌───────────┐ │
│ │ createMap() │───►│ Directory Scan │───►│ Output │ │
│ │ (public) │ │ (recursive) │ │ Map │ │
│ └─────────────────┘ └────────┬─────────┘ └───────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ findClasses() │ │
│ │ (private) │ │
│ └────────┬─────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ Token Parser │ │
│ │ - T_NAMESPACE │ │
│ │ - T_CLASS │ │
│ │ - T_INTERFACE │ │
│ │ - T_TRAIT │ │
│ └──────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
How It Works
-
Directory Iteration: The
createMap()method usesRecursiveDirectoryIteratorto traverse all files in the specified directory and its subdirectories. -
File Filtering: Only files with the
.phpextension are processed, skipping all other file types. -
Token Parsing: Each PHP file is read and parsed using PHP's
token_get_all()function, which breaks down the source code into tokens. -
Namespace Detection: The parser tracks
T_NAMESPACEtokens to build the current namespace context for class resolution. -
Class Detection: When
T_CLASS,T_INTERFACE, orT_TRAITtokens are encountered, the parser extracts the class name and combines it with the current namespace. -
::class Constant Handling: The parser intelligently skips
::classconstant usage (e.g.,SomeClass::class) to avoid false positives. -
Memory Management: After processing each file,
gc_mem_caches()is called to address a known PHP memory issue withtoken_get_all().
📦 Installation
It's best to use Composer for installation, and you can also find the package on Packagist and GitHub.
To install, simply use the command:
$ composer require baraja-core/class-map-generator
You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.
Requirements
- PHP 8.0 or higher
- No external dependencies
🚀 Usage
Basic Usage
Generate a class map for a directory:
use Baraja\ClassMapGenerator\ClassMapGenerator; $map = ClassMapGenerator::createMap(__DIR__ . '/src');
Return Value
The createMap() method returns an associative array where:
- Keys are fully qualified class names (including namespace)
- Values are absolute file paths
// Example output: [ 'App\Controllers\HomeController' => '/var/www/project/src/Controllers/HomeController.php', 'App\Models\User' => '/var/www/project/src/Models/User.php', 'App\Services\AuthService' => '/var/www/project/src/Services/AuthService.php', ]
Practical Examples
Finding a Specific Class File
$map = ClassMapGenerator::createMap(__DIR__ . '/src'); if (isset($map['App\Services\PaymentService'])) { $filePath = $map['App\Services\PaymentService']; echo "PaymentService is located at: {$filePath}"; }
Listing All Classes in a Namespace
$map = ClassMapGenerator::createMap(__DIR__ . '/src'); $controllers = array_filter( $map, fn($class) => str_starts_with($class, 'App\\Controllers\\'), ARRAY_FILTER_USE_KEY ); foreach ($controllers as $className => $filePath) { echo "{$className}\n"; }
Building an Autoloader
$map = ClassMapGenerator::createMap(__DIR__ . '/src'); spl_autoload_register(function (string $class) use ($map): void { if (isset($map[$class])) { require_once $map[$class]; } });
Caching the Class Map
For performance optimization in production environments:
$cacheFile = __DIR__ . '/cache/classmap.php'; if (file_exists($cacheFile)) { $map = require $cacheFile; } else { $map = ClassMapGenerator::createMap(__DIR__ . '/src'); file_put_contents( $cacheFile, '<?php return ' . var_export($map, true) . ';' ); }
Scanning Multiple Directories
$directories = [ __DIR__ . '/src', __DIR__ . '/lib', __DIR__ . '/modules', ]; $fullMap = []; foreach ($directories as $dir) { $fullMap = array_merge($fullMap, ClassMapGenerator::createMap($dir)); }
🔍 What Gets Detected
The library detects the following PHP constructs:
| Construct | Detected | Example |
|---|---|---|
| Classes | Yes | class MyClass {} |
| Abstract classes | Yes | abstract class BaseController {} |
| Final classes | Yes | final class ImmutableValue {} |
| Interfaces | Yes | interface PaymentGateway {} |
| Traits | Yes | trait Loggable {} |
| Anonymous classes | No | new class {} |
| Enums | No | enum Status {} |
⚠️ Limitations
- Anonymous classes are not detected (they have no name to map)
- PHP Enums (PHP 8.1+) are not detected by the current implementation
- Files must be syntactically valid PHP - parsing errors may cause issues
- Multiple classes per file are fully supported, but only the class matching the filename is typically recommended
🔧 Technical Notes
Memory Management
The library calls gc_mem_caches() after processing each file to address a known PHP memory issue where token_get_all() doesn't release memory properly. This ensures stable memory usage when scanning large codebases.
Path Resolution
The library attempts to get the real path of each file using getRealPath(). If this fails (e.g., on some edge cases with symlinks), it falls back to getPathname().
Inspiration
This library is based on the Symfony ClassLoader component, adapted and modernized for PHP 8.0+ with strict typing and simplified API.
👨💻 Author
Jan Barášek - https://baraja.cz
📄 License
baraja-core/class-map-generator is licensed under the MIT license. See the LICENSE file for more details.
baraja-core/class-map-generator 适用场景与选型建议
baraja-core/class-map-generator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 15 次下载、GitHub Stars 达 1, 最近一次更新时间为 2020 年 12 月 31 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 baraja-core/class-map-generator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 baraja-core/class-map-generator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 15
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 2
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Unknown
- 更新时间: 2020-12-31