Zend Framework 2 - Doctrine 2 - Created at timestamp field

北慕城南 提交于 2019-12-11 14:02:19

问题


I want to create a custom created_at annotation in ZF2. I found a (German) tutorial how to build such an annotation in Symfony2.

Everything seems easy to copy except the registering of the prePersist listener.

The code in Symfony is:

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

Any suggestions how to achieve this in Zend?

Thanks!


回答1:


Thanks to Ocramius I found a different solution for creating a PrePersist created at timestamp:

/**
 * ...
 * @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;
    }



回答2:


Easier solution:

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;

    ...
}

without costly event functionality.



来源:https://stackoverflow.com/questions/16894716/zend-framework-2-doctrine-2-created-at-timestamp-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!