如何在Doctrine中使用PHP8属性而不是注释?

29

这是我想要使用的:

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

使用以下内容替换:

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

但我遇到了这个错误:

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

是因为Doctrine还不支持,还是我漏掉了什么?


你需要使用这样的注释有什么用例?你想解决什么问题? - hppycoder
3
如果您有数百个注释想要转换为属性,您可能希望自动化此过程。我编写了一个名为Rector的开源工具,可以为您处理这个升级过程:https://getrector.org/blog/how-to-upgrade-annotations-to-attributes - Tomas Votruba
2个回答

67

正如@Seb33300所说,在Doctrine ORM 2.9中现在可以这样做。但是对于Symfony,您需要做更多的工作。以下是升级的完整步骤清单:

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

19
从“注释”到“属性”的变化非常关键。感谢您对此进行了记录。 - Jason Aller
7
有没有办法同时允许平稳迁移现有属性? - the_nuts
@the_nuts 你能找到一种允许两者的方法吗?请告诉我。 - nas
1
@nas 是的,我创建了另一个目录,所以我在 Entity 中仍然使用注释,而在 EntAttribs 中(找不到更好的名称lol)则使用属性:https://pastebin.com/VS1jGD8x - the_nuts

16

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接