roave/better-reflection
Enhanced PHP reflection for static analysis: reflect classes without loading them, from PHP code strings or closures, extract AST from functions/methods, and read type declarations and docblocks. Feature-rich but slower than native reflection.
Reflection API, and some methods (e.g., newInstance(), invoke()) are unsupported.Container::getReflection() for advanced type hints or validation (though native reflection is preferred for runtime).@Route in Laravel routes).composer require roave/better-reflection. Compatible with Laravel’s autoloader (ComposerSourceLocator is pre-bundled).Reflection API with ~90% method support (see compatibility docs). Existing reflection-based code can often swap ReflectionClass for BetterReflection\Reflection\ReflectionClass with minimal changes.php artisan make:) could leverage this for advanced code generation.newInstance(), getExtension(), or closure-specific methods (e.g., getClosureThis). Requires fallback logic or custom wrappers.BetterReflection::createFromIde() for IDE-like environments.BetterReflection’s attribute support may reduce reliance on ReflectionAttribute.Illuminate\Support\Traits\ReflectsClosures) that could conflict?newInstance())?Reflection. For AST: Consider php-parser/php-parser or nikic/php-parser.illuminate/support traits or laravel/serializable-closure.Illuminate\Contracts\Validation\Rule).make:controller, make:middleware) with advanced code inspection.[Route], [HandleIncoming]).ReflectionClass with BetterReflection\Reflection\ReflectionClass incrementally.// Before
$reflection = new \ReflectionClass(MyClass::class);
// After
$reflection = (new BetterReflection())->reflector()->reflectClass(MyClass::class);
class ReflectionFacade {
public static function reflectClass(string $class): ReflectionClass {
try {
return (new BetterReflection())->reflector()->reflectClass($class);
} catch (Exception) {
return new \ReflectionClass($class);
}
}
}
BetterReflection only where native reflection fails (e.g., closures, unloaded classes).$closureReflection = (new BetterReflection())
->reflector()
->reflect(new \ReflectionFunction($closure));
Reflection API (see compatibility docs).newInstance() or getExtension() will throw exceptions—handle gracefully.make:seeder command that validates class methods before generation.app/Providers/EventServiceProvider.Kernel.php middleware.ReflectionClass usages in static analysis tools (low risk if wrapped).composer.json to avoid surprises (e.g., roave/better-reflection:^6.0).ClassNotFoundException vs. ReflectionException).newInstance()).How can I help you explore Laravel packages today?