0

データベースの列を異なる名前のインスタンス フィールドにマップできる軽量の ORM を作成しています。

例えば。

データベース

  • ユーザーID
  • ユーザー名
  • 別の不適切な名前のフィールド

物体

  • ユーザー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あり、そのクラスを知っています。

この動作の回避策または使用するより良いアーキテクチャはありますか?

4

2 に答える 2

1

解決策は次のとおりです。

public function isValidField($name) {
  $class = get_class($this);
  return in_array(strtolower($name), $class::$db_to_obj);
}
于 2012-06-26T16:27:43.523 に答える
1

継承を使用する場合、保護された変数と静的変数を同時に作成しないでください。

また、継承を使用する場合は、次のようなことができます/すべきです:

parent::isValidField($name) {
  // code here
}
于 2012-06-26T16:24:38.613 に答える