An annotation/attribute reader

1.0.5 2023-07-08 09:09 UTC

This package is auto-updated.

Last update: 2024-05-01 00:07:16 UTC


codecov Type Coverage Continuous Integration Static Analysis Coding Standards

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.


composer require koriym/attributes


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 */
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
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