【问题标题】:How can i use php8 attributes instead of annotations in doctrine?我如何在教义中使用 php8 属性而不是注释?
【发布时间】:2021-06-20 12:15:11
【问题描述】:

这是我想使用的:

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

而不是这个:

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

但我收到此错误:

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

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

【问题讨论】:

  • 你有什么用例需要使用这样的注释?你想解决什么问题?
  • 如果您有数百个注释并想要转换它们的属性,您可能更愿意自动执行此操作。我写了一个开源工具 Rector 来为你处理这个升级:getrector.org/blog/how-to-upgrade-annotations-to-attributes

标签: php symfony doctrine-orm doctrine php-8


【解决方案1】:

正如@Seb33300 所说,是的,它是 Doctrine ORM 2.9 中的 now possible。但是对于 Symfony,您需要做的还不止这些。以下是升级步骤的完整列表:

  1. 升级 Doctrine ORM:"doctrine/orm": "^2.9".

  2. 升级学说包:"doctrine/doctrine-bundle": "^2.4".

  3. 设置doctrine.orm.mappings.App.type: attribute(默认设置为annotation):

    # config/packages/doctrine.yaml
    
    doctrine:
      orm:
        mappings:
          App:
            type: attribute
    
  4. 对您的实体应用类似的更改:

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

【讨论】:

  • 从“注解”到“属性”的改变至关重要。感谢您记录它。
【解决方案2】:

编辑:Doctrine 2.9 is now released 支持 PHP 8 属性!

PHP 8 注释已合并到尚未发布的 Doctrine ORM 2.9.x 分支中: https://github.com/doctrine/orm/pull/8266

以下是与此功能相关的文档参考: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/attributes-reference.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2016-04-09
    • 2018-07-20
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多