BetterReflection
:crystal_ball: Better Reflection is a reflection API that aims to improve and provide more features than PHP's built-in reflection API.
Top Related Projects
Annotations Docblock Parser
A PHP parser written in PHP
Extracts information about PHP class' properties using metadata of popular sources
Metadata is a library for metadata management in PHP
Next-gen phpDoc parser with support for intersection types and generics
Quick Overview
Roave/BetterReflection is a powerful PHP library that provides advanced reflection capabilities beyond PHP's built-in Reflection API. It allows for static analysis and manipulation of PHP code without loading or executing it, making it ideal for code introspection, static analysis tools, and metaprogramming tasks.
Pros
- Enables reflection on code that is not loaded or executed
- Provides more detailed information than PHP's native Reflection API
- Supports analysis of code stored in strings or files
- Allows modification of reflected structures
Cons
- May have a steeper learning curve compared to native Reflection
- Can be slower than native Reflection for simple tasks
- Requires additional setup and dependencies
- May not always perfectly mirror runtime behavior
Code Examples
- Reflecting on a class:
use Roave\BetterReflection\BetterReflection;
$classInfo = (new BetterReflection())
->reflector()
->reflectClass('MyNamespace\MyClass');
echo $classInfo->getName();
- Analyzing method parameters:
use Roave\BetterReflection\BetterReflection;
$methodInfo = (new BetterReflection())
->reflector()
->reflectClass('MyNamespace\MyClass')
->getMethod('myMethod');
foreach ($methodInfo->getParameters() as $parameter) {
echo $parameter->getName() . ': ' . $parameter->getType();
}
- Modifying a class property:
use Roave\BetterReflection\BetterReflection;
$classInfo = (new BetterReflection())
->reflector()
->reflectClass('MyNamespace\MyClass');
$property = $classInfo->getProperty('myProperty');
$property->setVisibility(\ReflectionProperty::IS_PRIVATE);
echo $classInfo->getAst();
Getting Started
To use Roave/BetterReflection in your project:
-
Install via Composer:
composer require roave/better-reflection
-
Basic usage in your PHP code:
use Roave\BetterReflection\BetterReflection; $reflector = (new BetterReflection())->reflector(); $classInfo = $reflector->reflectClass('MyNamespace\MyClass'); // Now you can use $classInfo to analyze the class
Competitor Comparisons
Annotations Docblock Parser
Pros of Annotations
- Lightweight and focused specifically on annotation parsing
- Well-established and widely used in the Symfony ecosystem
- Simpler to set up and use for basic annotation needs
Cons of Annotations
- Limited to annotation parsing, lacking broader reflection capabilities
- Requires specific annotation syntax in docblocks
- Less flexible for advanced use cases or custom reflection needs
Code Comparison
Annotations:
/**
* @Route("/blog/{slug}", name="blog_show")
*/
public function show($slug) {
// ...
}
BetterReflection:
$classInfo = ReflectionClass::createFromName(MyClass::class);
$method = $classInfo->getMethod('myMethod');
$parameters = $method->getParameters();
Key Differences
- Scope: Annotations focuses solely on parsing docblock annotations, while BetterReflection provides a more comprehensive reflection API
- Use case: Annotations is ideal for projects heavily relying on docblock-based configurations, while BetterReflection suits complex reflection needs
- Performance: Annotations may have a slight edge in parsing speed for its specific use case, but BetterReflection offers more flexibility and features
Conclusion
Choose Annotations for simple annotation parsing in Symfony-based projects. Opt for BetterReflection when you need advanced reflection capabilities or want to avoid dependencies on specific annotation syntax.
A PHP parser written in PHP
Pros of PHP-Parser
- More focused on parsing PHP code into an Abstract Syntax Tree (AST)
- Lighter weight and potentially faster for simple parsing tasks
- Widely used and well-established in the PHP ecosystem
Cons of PHP-Parser
- Limited to parsing and modifying code structure
- Lacks advanced reflection capabilities
- Requires more manual work for complex code analysis tasks
Code Comparison
PHP-Parser:
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse('<?php echo "Hello World!";');
BetterReflection:
$reflector = new DefaultReflector(new AstLocator());
$classInfo = $reflector->reflectClass('MyClass');
$methods = $classInfo->getMethods();
Summary
PHP-Parser excels at parsing PHP code into an AST, making it ideal for tasks that require manipulating code structure. It's lightweight and widely adopted. However, it lacks advanced reflection capabilities.
BetterReflection, on the other hand, provides more comprehensive reflection features, allowing for deeper analysis of PHP code, including type information and docblock parsing. It's better suited for complex code analysis tasks but may be overkill for simple parsing needs.
Choose PHP-Parser for straightforward parsing and AST manipulation, and BetterReflection for advanced code analysis and reflection capabilities.
Extracts information about PHP class' properties using metadata of popular sources
Pros of Property-Info
- Part of the Symfony ecosystem, integrating well with other Symfony components
- Lightweight and focused specifically on property information extraction
- Supports multiple strategies for extracting property information (PHPDoc, type declarations, etc.)
Cons of Property-Info
- Limited scope compared to BetterReflection's broader reflection capabilities
- May require additional Symfony components for full functionality
- Less flexibility for advanced reflection tasks beyond property information
Code Comparison
BetterReflection:
$reflector = new \Roave\BetterReflection\Reflector\DefaultReflector(
new \Roave\BetterReflection\SourceLocator\Type\ComposerSourceLocator()
);
$classInfo = $reflector->reflectClass(MyClass::class);
$properties = $classInfo->getProperties();
Property-Info:
$propertyInfo = \Symfony\Component\PropertyInfo\PropertyInfoExtractor::create();
$properties = $propertyInfo->getProperties(MyClass::class);
$types = $propertyInfo->getTypes(MyClass::class, 'propertyName');
BetterReflection offers more comprehensive reflection capabilities, while Property-Info provides a streamlined approach for property information within the Symfony ecosystem. The choice between them depends on the specific needs of your project and whether you're already using Symfony components.
Metadata is a library for metadata management in PHP
Pros of Metadata
- Lightweight and focused on metadata extraction and manipulation
- Supports various metadata sources (annotations, YAML, XML, etc.)
- Easier to integrate into existing projects due to its specific scope
Cons of Metadata
- Limited to metadata handling, lacking broader reflection capabilities
- Less actively maintained compared to BetterReflection
- Fewer advanced features for code analysis and manipulation
Code Comparison
BetterReflection:
$classInfo = ReflectionClass::createFromName('MyClass');
$methods = $classInfo->getMethods();
foreach ($methods as $method) {
echo $method->getName();
}
Metadata:
$driver = new AnnotationDriver([new AnnotationReader()]);
$metadata = $driver->loadMetadataForClass(new \ReflectionClass('MyClass'));
foreach ($metadata->methodMetadata as $method) {
echo $method->name;
}
Both libraries offer ways to inspect class metadata, but BetterReflection provides a more comprehensive reflection API, while Metadata focuses specifically on metadata extraction and manipulation from various sources.
Next-gen phpDoc parser with support for intersection types and generics
Pros of phpdoc-parser
- Lightweight and focused specifically on parsing PHPDoc comments
- Easier to integrate into existing projects due to its smaller scope
- More frequent updates and active maintenance
Cons of phpdoc-parser
- Limited functionality compared to BetterReflection's broader feature set
- Lacks advanced reflection capabilities for analyzing PHP code structure
- May require additional libraries for comprehensive code analysis
Code Comparison
phpdoc-parser:
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
$lexer = new Lexer();
$parser = new PhpDocParser();
$tokens = $lexer->tokenize($docComment);
$ast = $parser->parse($tokens);
BetterReflection:
use Roave\BetterReflection\BetterReflection;
$reflector = new BetterReflection();
$classInfo = $reflector->classReflector()->reflect('MyClass');
$methodInfo = $classInfo->getMethod('myMethod');
$docComment = $methodInfo->getDocComment();
Both libraries serve different purposes, with phpdoc-parser focusing on PHPDoc parsing and BetterReflection offering a more comprehensive reflection API. The choice between them depends on the specific requirements of your project and the depth of analysis needed.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Better Reflection
Better Reflection is a reflection API that aims to improve and provide more features than PHP's built-in reflection API.
Why is it better?
- You can reflect on classes that are not already loaded, without loading them
- Ability to reflect on classes directly from a string of PHP code
- Reflecting directly on closures
- Ability to extract AST from methods and functions
- Ability to return AST representation of a class or function
- Fetch return type declaration and parameter type declarations in PHP 7 code
- Moar stuff coming soon!
Typically you would use Better Reflection for static analysis tooling. It can serve as a baseline to access type information (e.g. doc blocks, type declarations), method/function body AST fetching etc. for static analysis.
Better Reflection is NOT suited to runtime usage, since performance is much worse than PHP built-in reflection. If you do not want to do anything that native PHP reflection can't do, then just use native PHP reflection! The "Better" in Better Reflection refers to feature, not speed!
Be sure to read more in the feature documentation.
Installation
Require using composer:
composer require roave/better-reflection
Usage
<?php
use Roave\BetterReflection\BetterReflection;
$classInfo = (new BetterReflection())
->reflector()
->reflectClass(\Foo\Bar\MyClass::class);
Documentation
Upgrading
Please refer to the Upgrade Documentation documentation to see what is required to upgrade your installed
BetterReflection
version.
Limitations
- PHP cannot autoload functions, therefore we cannot statically reflect functions
License
This package is released under the MIT license.
Contributing
If you wish to contribute to the project, please read the CONTRIBUTING notes.
Top Related Projects
Annotations Docblock Parser
A PHP parser written in PHP
Extracts information about PHP class' properties using metadata of popular sources
Metadata is a library for metadata management in PHP
Next-gen phpDoc parser with support for intersection types and generics
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot