2012-06-26 36 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 
}