2013-06-03 48 views
1

我想在ZF2中創建一個自定義created_at註釋。我發現了一個(German) tutorial如何在Symfony2中構建這樣的註釋。Zend Framework 2 - Doctrine 2 - 創建時間戳字段

除了註冊prePersist聽衆以外,一切似乎都很容易複製。

中的Symfony的代碼是:

services: 
created_at_listener: 
    class: Scandio\Annotations\Driver\CreatedAtDriver 
    tags: 
     - {name: doctrine.event_listener, event: prePersist} 
    arguments: [@annotation_reader] 

任何建議如何在Zend公司實現這一目標?

謝謝!

回答

5

Thanks to Ocramius我發現了一個不同的解決方案,用於創建在時間戳創建PrePersist

/** 
* ... 
* @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; 
    } 
4

簡單的解決方案:

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; 

    ... 
} 

無需昂貴的活動功能。