2013-02-16 17 views
0

這個問題在過去的幾個小時裏一直讓我瘋狂。我添加的屬性posts_published_date用戶實體(它跟蹤特定用戶發了一個帖子最後日期)。下面是一些相關線路:學說不在我的實體中加載或保存特定屬性

初始化在實體的屬性。

/** 
* @Column(type="integer", length=3, nullable=false) 
*/ 
protected $posts_published_today; 
/** 
* @Column(type="string", length=7, nullable=true) 
*/ 
protected $posts_published_date; 
/** 
* @Column(type="integer", length=3, nullable=true) 
*/ 
protected $posts_published_limit; 

在實體使用屬性:

public function setPostsPublishedToday($value){ 
    $today = date("now"); 
    if ($today != $this->posts_published_date){ 
     $this->posts_published_today = 1; 
     debug($this->posts_published_date . " != " . $today, "1"); 
     $this->posts_published_date = $today; 
     debug($this->posts_published_date . " == " . $today, "2"); 
    } else { 
     $this->posts_published_today = $value; 
    } 
} 

兩個(1)調試與下面的輸出運行:

Debug 1: != 220136 
Debug 2: 220136 == 220136 

posts_published_date沒有得到存儲在數據庫中,但posts_published_today正在檢索並保存好。

+0

您應該添加在這種情況下使用的代碼。 另外,考慮對'posts_published_date'屬性使用''datetime''字段類型,然後最終爲其分配一個'DateTime'對象。 – Ocramius 2013-02-16 22:34:18

回答

0

你爲什麼不使用類變量的setter函數,而不是直接訪問它?試試:

public function setPostsPublishedToday($value) 
{ 
    $today = date("now"); 
    if ($today != $this->getPostsPublishedDate()) { 
     $this->posts_published_today = 1; 
     $this->setPostsPublishedDate($today); 
    } else { 
     $this->posts_published_today = $value; 
    } 
} 

這樣一切都通過基礎方法路由,你可以保證行爲。如果你允許你的代碼訪問類變量,那麼它變得不可持續,如果你碰巧改變了某個特定的數據庫列,那麼它將成爲一場噩夢。等等。當你嘗試上述時會發生什麼?你堅持一切嗎?

+0

他正在實體內部工作...我不會擔心在這種情況下使用公共API,但在OOP中總是一個大討論:) – Ocramius 2013-02-16 22:32:07

+0

是的,我在實體本身。你建議的改變沒有效果。會發生什麼是posts_published_today成功更改(我檢查了phpMyAdmin),而posts_published_date保持不變。這告訴我,堅持和沖洗工作正常。 – Furyvore 2013-02-17 01:50:13