2013-02-25 82 views
2

我使用的是ZF2和Doctrine-Module的Doctrine 2。 我已經寫了一個實體,需要一個更新前| PrePersist,因爲教義不允許 日期|日期時間在主鍵:Doctrine HasLifecycleCallbacks PrePersist | PreUpdate不會觸發

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

} 

現在的問題,如果我設置日期時間爲日期我得到消息:

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

因爲它不走進formatDate。

回答

5

首先,因爲你映射領域Sample#datedatetime,它應該永遠是要麼nullDateTime一個實例。

因此,你應該typehint你setDate方法如下:

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

此外,您lifecycle callback不會被調用,因爲方法formatDate的能見度protected,因此不被ORM訪問。將其更改爲public,它將起作用。無論如何不需要轉換,所以你可以擺脫它。

+0

在我的情況下,ORM:PrePersist被忽略了......你註冊了一些服務還是其他的東西? – Ron 2013-06-03 12:01:39

+2

@它是一個回調。它必須是公開的,並且必須在元數據中註冊。 – Ocramius 2013-06-03 12:53:44

+0

謝謝!但我如何在元數據中註冊它?從來沒有見過這個......或者它可能是trival? – Ron 2013-06-03 13:45:06

相關問題