Doctrine HasLifecycleCallbacks PrePersist|PreUpdat

2019-07-14 06:35发布

I'm using Doctrine 2 with ZF2 and the Doctrine-Module. I've written an Entity that needs a PreUpdate|PrePersist, because Doctrine doesn't allow Date|Datetime in a primary key:

<?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;
    }

}

The Problem is now, if i set a DateTime as a Date I get the message:

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

because it doesn't walk into the formatDate.

1条回答
beautiful°
2楼-- · 2019-07-14 07:33

First of all, since you mapped the field Sample#date as datetime, it should always be either null or an instance of DateTime.

Therefore, you should typehint your setDate method as following:

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

Also, your lifecycle callback is not invoked because the visibility of method formatDate is protected, therefore not accessible by the ORM. Change it into public and it will work. No conversion should be necessary anyway, so you can get rid of it.

查看更多
登录 后发表回答