【问题标题】:Best OOP design pattern for static class DbTable静态类 DbTable 的最佳 OOP 设计模式
【发布时间】:2015-02-07 18:50:16
【问题描述】:

我有 DbTable 类,它实现了对数据库的所有 db 查询,例如 insertRecord、updateRecord、...但是变量没有重写。

abstract class DbTable {
    public static $table;

    public static function insertRecord($data) {
       // here I add some values to data, but that's not important
       my_db::insert(self::$table, $data);
    }
}

class User extends DbTable {
    public static $table = 'table_users';
}

// everywhere I can call
User::insertRecord($data);

我知道我可以打电话

$c = get_called_class();
my_db::insert($c::$table, $data);

但我认为这根本不是最好的解决方案。

方法和变量可以是非静态的,我只是使用它们,因为写User::insertRecord而不是$user = new User(); $user->insertRecord($data);很舒服

【问题讨论】:

    标签: php oop design-patterns


    【解决方案1】:

    当您使用静态类时,您需要指定变量源,在这种情况下,您的范围是两个类而不是单个类,这会有所不同,因为self 的范围是并发类和当你想同时使用这两个类时,你必须使用static。

    /**
    * For testing
    */
    class my_db {
        public static function insert($table, $data){
            echo $table;
        }
    }
    abstract class DbTable {
        public static $table = null;
    
        public static function insertRecord($data) {
    
            //self::$table is empty
            //static::$table has 'table_users'
    
            // here I add some values to data, but that's not important
            my_db::insert(static::$table, $data);
        }
    }
    
    class User extends DbTable {
        public static $table = 'table_users';
    }
    
    // everywhere I can call
    User::insertRecord(['Hi']);
    

    self::$table 是空

    static::$table 有 'table_users'

    您可以在此处阅读更多相关信息:SO Answer 和 PHP Documentation

    【讨论】:

      【解决方案2】:

      在这种情况下,不需要使用静态变量。您只需要动态创建User 对象并调用方法。

      abstract class DbTable
      {
          protected $tableName;
      
          public static function insertRecord($data) 
          {
              $object = static::newInstance();
              $object->insert($data);
          }
      
          public static function newInstance()
          {
              $className = get_called_class();
              return new $className();
          }
      
          public function insert($data)
          {
              my_db::insert($this->tableName, $data);
          }
      }
      
      class User extends DbTable 
      {
          public function __construct()
          {
              $this->tableName = 'table_users';
          }
      }
      

      您现在可以调用:

      User::insertRecord(['col1' => 'val1']);
      

      但您也可以从 instated 对象中插入行:

      $user = new User();
      $user->insert(['col1' => 'val1']);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 2011-07-30
        • 2011-04-12
        • 1970-01-01
        • 2012-05-25
        相关资源
        最近更新 更多