How to Upgrade Annotations to Attributes

This feature is available since Rector 0.12.
April 2022 Update

Since Rector 0.12 a new RectorConfig is available with simpler and easier to use config methods.


We used @annotations in PHP 7.4 and below. Now we can use native #[attributes] in PHP 8. They have better support in PHPStan and Rector, thanks to their native language nature.

The Internet is full of questions "How can I use PHP 8 attributes instead of annotations in Doctrine?" or "Converting Annotations to Attributes".

Do you want to know the answer? Rector has a simple solution for you.

One package that added support for attributes is Doctrine:

 use Doctrine\ORM\Mapping as ORM;

-/**
- * @ORM\Column(type="string")
- */
+#[ORM\Column(type: "string")]

Now, let's go to upgrade itself. It's effortless.

Upgrade from Annotations to Attributes in 3 Steps

1. Configure rector.php to include the packages you use:

use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Symfony\Set\SymfonySetList;
use Rector\Symfony\Set\SensiolabsSetList;
use Rector\Nette\Set\NetteSetList;
use Rector\Config\RectorConfig;

return function (RectorConfig $rectorConfig): void {
    $rectorConfig->sets([
        DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
        NetteSetList::ANNOTATIONS_TO_ATTRIBUTES,
        SensiolabsSetList::FRAMEWORK_EXTRA_61,
    ]);
};

2. Run Rector to upgrade your code

vendor/bin/rector process

3. Handle Manual Steps

  • Do you use doctrine/orm? Be sure to use at least version 2.9, where attributes were released.

  • Do you use Doctrine with Symfony? Update the Symfony bundle mapping parser in your config to read attributes:

 # config/packages/doctrine.yaml
 doctrine:
     orm:
         mappings:
             App:
-                type: annotation
+                type: attribute

This enables new Symfony auto-detection feature.

That's it! Now your codebase uses nice and shiny PHP 8 native attributes.


Happy coding!