主义HasLifecycleCallbacks PrePersist | PreUpdate不会触发

时间:2013-02-25 09:56:49

标签: doctrine-orm

我正在使用Doctrine 2和ZF2以及Doctrine-Module。 我写了一个需要PreUpdate | PrePersist的实体,因为Doctrine不允许 日期|主键中的日期时间:

<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="sample")
 */
class Sample
{

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="string")
     * @var integer
     */
    protected $runmode;

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="date")
     * @var DateTime
     */
    protected $date;


    public function getRunmode()
    {
        return $this->runmode;
    }

    public function setRunmode($runmode)
    {
        $this->runmode = $runmode;
        return $this;
    }

    public function getDate()
    {
        return $this->date;
    }

    public function setDate($date)
    {
        $this->date = $date;
        return $this;
    }

    /**
     *
     * @ORM\PreUpdate
     * @ORM\PrePersist
     */
    protected function formatDate()
    {
        die('preUpdate, prePersist');
        if ($this->date instanceof \DateTime) {
            $this->date = $this->date->format('Y-m-d');
        }
        return $this;
    }

}

现在问题是,如果我将DateTime设置为日期,我会收到消息:

"Object of class DateTime could not be converted to string"

因为它没有走进formatDate。

1 个答案:

答案 0 :(得分:5)

首先,由于您将字段Sample#date映射为datetime,因此它应始终为nullDateTime的实例。

因此,您应该按照以下方式键入您的setDate方法:

public function setDate(\DateTime $date = null)
{
    $this->date = $date;
    return $this;
}

此外,您的lifecycle callback未被调用,因为方法formatDate的可见性为protected,因此ORM无法访问。将其更改为public即可。无论如何都不需要转换,所以你可以摆脱它。