生命周期回调预持久不触发(使用 YAML 文件)



我正在按照The Book学习Symfony。在本教程中,我成功配置了 prePersist 事件(在插入时设置 createdAt 字段)。

现在我正在尝试做同样的事情,但使用 YAML 文件而不是注释。这是我的orm.yml文件:

AppBundleEntityChronicle:
    type: entity
    table: chronicles
    id:
        id:
            type: integer
            generator: {strategy: AUTO}
    fields:
        name:
            type: string
            length: 256
        createdAt:
            type: datetime
    manyToOne:
        creator: 
            targetEntity: User
            inversedBy: chronicles
            joinColumn: 
                name: user_id
                referencedColumnName: id
        game:
            targetEntity: Game
            joinColumn:
                name: game_id
                referencedColumnName: id
    oneToMany:
        characters:
            targetEntity: Character
            mappedBy: chronicle
    lifeCycleCallbacks:
        prePersist: [ setCreatedAtValue ]

这是我的实体类的一个片段:

class Chronicle
{
    private $id;
    private $name;
    private $createdAt;
    // Associations
    private $game;
    private $creator;
    private $characters;
    // TODO: users or user relationships
    // Constructor
    public function __construct(User $creator=null) {
        $this->characters = new ArrayCollection();
        $this->creator = $creator;
    }
    /**
    * Set createdAt at the current time.
    *
    * (Lifecycle callback)
    */
    public function setCreatedAtValue() 
    {
        $this->createdAt = new DateTime();
    }
    // ...
}

但是 setCreatedAtValue() 方法永远不会被调用。因此,当我尝试插入对象时,我会收到异常。

我注意到在使用注释时,我必须使用 @ORM\HasLifecycleCallbacks() 注释来说明生命周期回调的存在,但我在任何地方都没有找到与 yml 中等效的回调,或者是否需要。

教程中,我发现我应该在 services.yml 中注册回调,但教程从未提及它,我也没有在其他任何地方找到它。

如果您将"lifeCycleCallbacks"更改为"lifecycleCallbacks",则会调用它。

最新更新