How can i use php8 attributes instead of annotations in doctrine?

10,505

Solution 1

As @Seb33300 says, yes, it's now possible in Doctrine ORM 2.9. But for Symfony you need to do a little bit more than that. Here is a full list of steps to upgrade:

  1. Upgrade Doctrine ORM: "doctrine/orm": "^2.9".

  2. Upgrade Doctrine Bundle: "doctrine/doctrine-bundle": "^2.4".

  3. Set doctrine.orm.mappings.App.type: attribute (by default it's set to annotation):

    # config/packages/doctrine.yaml
    
    doctrine:
      orm:
        mappings:
          App:
            type: attribute
    
  4. Apply similar changes to your entities:

    --- Dummy.php.old     Mon Jun 07 00:00:00 2021
    +++ Dummy.php         Mon Jun 07 00:00:00 2021
    @@ -7,15 +7,11 @@
     use App\Repository\DummyRepository;
     use Doctrine\ORM\Mapping as ORM;
    
    -/**
    - * @ORM\Entity(repositoryClass = DummyRepository::class)
    - */
    +#[ORM\Entity(repositoryClass: DummyRepository::class)]
     class Dummy
     {
    -    /**
    -     * @ORM\Id
    -     * @ORM\GeneratedValue
    -     * @ORM\Column(type = 'integer')
    -     */
    +    #[ORM\Id]
    +    #[ORM\GeneratedValue]
    +    #[ORM\Column(type: 'integer')]
         private $id;
     }
    

Solution 2

EDIT: Doctrine 2.9 is now released with PHP 8 attributes support!

PHP 8 annotations have been merged in Doctrine ORM 2.9.x branch which is not released yet: https://github.com/doctrine/orm/pull/8266

Here is the documentation reference related to this feature: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/attributes-reference.html

Share:
10,505
Admin
Author by

Admin

Updated on June 19, 2022

Comments

  • Admin
    Admin about 2 years

    This is what I would like to use:

    #[ORM\Column(type: "string")]
    

    instead of this:

    /**
     *  @ORM\Column(type="string")
     */
    

    But I'm getting this error:

    (error: Class 'Column' is not annotated with 'Attribute' )
    

    Is it because Doctrine does not support it yet, or am I missing something?

  • Jason Aller
    Jason Aller about 3 years
    The change from "annotation" to "attribute" is critical. Thank you for documenting it.
  • the_nuts
    the_nuts about 2 years
    Is there any way to allow both, to have a smooth migration for the existing attributes?