Zend框架2 -原则2 -创建时间戳字段


Zend Framework 2 - Doctrine 2 - Created at timestamp field

我想在ZF2中创建一个自定义的created_at注释。我找到了一个如何在Symfony2中构建这样一个注释的(德语)教程。

一切似乎都很容易复制,除了注册prePersist侦听器。

Symfony中的代码是:

services:
created_at_listener:
    class: Scandio'Annotations'Driver'CreatedAtDriver
    tags:
      - {name: doctrine.event_listener, event: prePersist}
    arguments: [@annotation_reader]

有什么建议如何在Zend实现这一点吗?

多亏了Ocramius,我找到了创建PrePersist的不同解决方案,创建时间戳:

/**
 * ...
 * @ORM'HasLifecycleCallbacks
 * ...
*/
class ChangeRequest
    ...
    /**
     * @ORM'Column(type="datetime", nullable=true)
     * @Form'Attributes({"type":"text"})
     * @Form'Options({"label":"Created at"})
     * @Form'Exclude()
     */
    protected $created_at;
    ...
    /**
     * @ORM'PrePersist
     */
    public function timestamp()
        {
        if(is_null($this->getCreatedAt())) {
            $this->setCreatedAt(new 'DateTime());
        }
        return $this;
    }

更简单的解决方案:

class ChangeRequest
{
    public function __construct()
    {
        $this->created_at = new 'DateTime();
    }
    ...
    /**
     * @ORM'Column(type="datetime", nullable=true)
     * @Form'Attributes({"type":"text"})
     * @Form'Options({"label":"Created at"})
     * @Form'Exclude()
     */
    protected $created_at;
    ...
}

没有昂贵的事件功能