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

glm picture glm · Mar 23, 2021 · Viewed 11.5k times · Source

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?

Answer

Denis V picture Denis V · Jun 7, 2021

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;
     }