koriym / attributes
An annotation/attribute reader
Installs: 1 850 588
Dependents: 18
Suggesters: 1
Security: 0
Stars: 40
Watchers: 6
Forks: 7
Open Issues: 1
Requires
- php: ^7.2 || ^8.0
- doctrine/annotations: ^1.12 || ^2.0
Requires (Dev)
- ext-pdo: *
- bamarni/composer-bin-plugin: ^1.4
- phpunit/phpunit: ^8.5.24 || ^9.5
Suggests
- koriym/param-reader: An attribute/annotation reader for parameters
README
A koriym/attributes
dual reader implements doctrine/annotation Reader interface
in order to read both doctrine/annotation and PHP 8 attributes.
Doctrine annotations are different by design than PHP core one. Not all attributes can be read by this reader (ex. parameters), and not all doctrine/annotations can be read by this reader either. (ex. nested annotations)
However, This reader help you to code forward compatible that supports both PHP 7.x annotations and 8.x attributes in certain senario.
Installation
composer require koriym/attributes
Usage
Create the reader instance.
use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\Reader; use Koriym\Attributes\DualReader; use Koriym\Attributes\AttributeReader; $reader = new DualReader( new AnnotationReader(), new AttributeReader() ); assert($reader instanceof Reader);
The reader can read both annotations and attributes.
Compatible Annotation
Existing doctrine annotations can be changed into annotations that work for both doctrine annotation and PHP8 attributes.
Add #[Attribute]
attribute.
use Attribute;
/** @Annotation */
+#[Attribute]
final class Foo
{
}
Then add constructor when annotation has properties.
Following example works with both PHP8 attribute and doctrine/annotations
.
use Attribute; +use Doctrine\Common\Annotations\NamedArgumentConstructor; /** * @Annotation * @Target("METHOD") +* @NamedArgumentConstructor */ +#[Attribute(Attribute::TARGET_METHOD)] final class Foo { public string $bar; public int $baz; + public function __construct(string $bar = '', int $baz = 0) + { + $this->bar = $bar; + $this->baz = $baz; + } }
See more about annotation compatible attribute at Constructors with Named Parameters