1

一个类的 __construct() 方法是否需要公开才能在另一个类中调用该类的静态方法?

我试图通过调用数据库类的静态方法在我的模型类(MVC 应用程序)中获取数据库实例。这个 Database 类的构造函数是私有的,以便具有单例模式。但是当我尝试在我的模型类中调用静态方法时,它似乎会产生干扰。

当我将数据库构造函数设置为公共时,它可以工作。但是,它不再是真正的单例模式了。

有什么建议么?

数据库类:

class Database extends PDO {

    private static $instance;
    private $dsn;
    private $user;
    private $pass;

    public function __construct() {
        $this->dsn  = DB_ENGINE .':host='. DB_HOST .';dbname='. DB_NAME;
        $this->user = DB_USER;
        $this->pass = DB_PASS;
        parent::__construct($this->dsn, $this->user, $this->pass);
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }

    /**
     * select
     * @param string $sql An SQL string
     * @param array $array Paramters to bind
     * @param constant $fetchMode A PDO Fetch mode
     * @return mixed
     */
    public function select($sql, $fetchMode = PDO::FETCH_ASSOC, $array = array())
    {
        $stmt = $this->prepare($sql);
        foreach ($array as $key => $value) {
            $stmt->bindValue("$key", $value);
        }

        $stmt->execute();
        return $stmt->fetchAll($fetchMode);
    }

    /**
     * insert
     * @param string $table A name of table to insert into
     * @param string $data An associative array
     */
    public function insert($table, $data)
    {
        ksort($data);

        $fieldNames = implode(', ', array_keys($data));
        $fieldValues = ':' . implode(', :', array_keys($data));

        $stmt = $this->prepare("INSERT INTO $table ($fieldNames) VALUES ($fieldValues)");

        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }

        $stmt->execute();
    }

    /**
     * update
     * @param string $table A name of table to insert into
     * @param string $data An associative array
     * @param string $where the WHERE query part
     */
    public function update($table, $data, $where)
    {
        ksort($data);

        $fieldDetails = NULL;
        foreach ($data as $key=> $value) {
            $fieldDetails .= "$key=:$key,";
        }
        $fieldDetails = rtrim($fieldDetails, ',');

        $stmt = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");

        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }

        $stmt->execute();
    }

    /**
     * delete
     * 
     * @param string $table
     * @param string $where
     * @param integer $limit
     * @return integer Affected Rows
     */
    public function delete($table, $where, $limit = 1)
    {
        return $this->exec("DELETE FROM $table WHERE $where LIMIT $limit");
    }

}

型号类:

class Model {

    protected $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

}
4

0 回答 0