2012-06-26 47 views
0

我正在寫一個輕量級的ORM可以用不同的名字PHP類的繼承和靜態成員,處事

如數據庫列實例字段映射的正確方法。

數據庫

  • 用戶ID
  • 用戶名
  • anotherpoorlynamedfield

對象

  • user_id說明
  • 用戶名
  • another_poorly_named_field

要做到這一點我原來的設計是這樣的

abstract class DbObj { 
    /* In a subclass the author would provide the mapping of fileds 
    * from the database to the object 
    * e.g. 
    * array('userid' => 'user_id', 'username' => 'username'.... 
    */ 
    protected static $db_to_obj = array(); 

    /* This would be auto popuplated from $db_to_obj in reverse */ 
    protected static $obj_to_db = array(); 

    /* Many Methods truncated... */ 

    /* Used by magic methods to make sure a field is legit */ 
    public function isValidField($name) { 
     return in_array(strtolower($name), self::$db_to_obj); 
    } 
} 

於是我繼承了這一點

class Cat extends DbObj { 
    protected static $db_to_obj = array(
     'catsname' => 'name', 
     'itsage' => 'age' 
    ); 
} 

isValidField方法不按預期工作。使用一個調試器或者一個好的var_dump你會發現self::$db_to_obj的值是父類的值。如果isValidFieldstatic,我會理解,但事實並非如此。它確實有一個$this指針,它確實知道它的類。

有沒有這種行爲或更好的架構使用的解決方法?

+0

[ORM ==反模式(HTTP:// seldo。 COM /博客/ 2011/08/11/orm_is_an_antipattern /)['static' ==有害(http://kore-nordmann.de/blog/0103_static_considered_harmful.html)......我會重新考慮你想要什麼去做。 – rdlowrey

+0

同意對ORM位,但如果你不greenfielding的應用程序,並試圖慢慢改變它,那麼你得工作,你有什麼。感謝關於靜態的信息,但我覺得有一些設計模式是最適合的。 – wmarbut

+0

隨意使用'static',它只是讓你享受生活的面向對象的好處。 'static'是面向類的編程,而不是OOP。 – rdlowrey

回答

1

這裏有一個解決方案:

public function isValidField($name) { 
    $class = get_class($this); 
    return in_array(strtolower($name), $class::$db_to_obj); 
} 
1

不要創造出使用繼承時,同時保護和靜態變量。

如果你使用繼承,你可以/應該這樣做:

parent::isValidField($name) { 
    // code here 
}