我刚刚第一次将FOSUserBundle导入到symfony2项目中,并且在扩展用户实体时我注意到了一个问题。我使用prePersist和preUpdate生命周期回调添加了created_at和updated_at字段,但是没有读取这些方法。
如果我在构造函数中为这些字段设置了setter,那么将填充字段(但显然这与updated_at无法正常工作)。我添加的其他字段已按预期工作。
您是否需要以某种方式扩展UserListener以允许生命周期事件正常工作?
请在下面找到我的代码,非常感谢任何帮助或建议。
UserEntity:
namespace Acme\UserExtensionBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Acme\UserExtensionBundle\Entity\User
*
* @ORM\Table(name="acme_user")
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class User extends BaseUser{
/**
* @var integer $id
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var datetime $created_at
* @ORM\Column(name="created_at", type="datetime")
*/
protected $created_at;
/**
* @var datetime $updated_at
* @ORM\Column(name="updated_at", type="datetime")
*/
protected $updated_at;
...
public function __construct() {
parent::__construct();
$this->created_at = new \DateTime;
$this->updated_at = new \DateTime;
}
/*
* @ORM\preUpdate
*/
public function setUpdatedTimestamp(){
$this->updated_at = new \DateTime();
}
...
答案 0 :(得分:2)
快速查看后,我只能在注释名称的情况下发现一点错误。
应该是
@ORM\PreUpdate
而不是
@ORM\preUpdate
恕我直言,执行时会导致错误。
无论如何,我建议你使用http://symfony.com/doc/current/cookbook/doctrine/common_extensions.html中描述的DoctrineExtensionsBundle。
它带有Timestampable(以及更多有用的)行为,因此您不需要自己编写代码(重新发明轮子)。
我和FOSUserBundle一起使用它并且工作正常。这就是我在用户实体中的定义:
/**
* @var \DateTime $created
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
protected $created;
/**
* @var \DateTime $updated
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
protected $updated;