问题
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