Zend Framework 2 - Doctrine 2 - Created at timesta

2019-07-26 05:07发布

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!

2条回答
霸刀☆藐视天下
2楼-- · 2019-07-26 06:00

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.

查看更多
\"骚年 ilove
3楼-- · 2019-07-26 06:04

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;
    }
查看更多
登录 后发表回答