如何在学说中使用 php8 属性而不是注释?

glm*_*glm 7 php doctrine symfony doctrine-orm php-8

这是我想使用的:

#[ORM\Column(type="string")]
Run Code Online (Sandbox Code Playgroud)

而不是这个:

/**
 *  @ORM\Column(type="string")
 */
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

(error: Class 'Column' is not annotated with 'Attribute' )
Run Code Online (Sandbox Code Playgroud)

是因为 Doctrine 还不支持它,还是我错过了什么?

Den*_*s V 25

正如@Seb33300 所说,是的,现在可以在 Doctrine ORM 2.9 中实现。但是对于 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
    
    Run Code Online (Sandbox Code Playgroud)
  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;
     }
    
    Run Code Online (Sandbox Code Playgroud)

  • 有没有什么办法可以让两者,现有的属性顺利迁移呢? (7认同)
  • 从“注释”到“属性”的转变至关重要。感谢您记录它。 (4认同)

Seb*_*300 8

编辑:Doctrine 2.9现已发布,支持 PHP 8 属性!

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

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