类'__construct()方法是否需要公开,以便在另一个类中调用此类的静态方法?
我正在尝试通过调用Database类的静态方法在Model类(MVC app)中获取Database实例。此Database类的构造函数是私有的,以便具有单例模式。但是当我尝试在我的Model类中调用静态方法时,它似乎在干扰。
当我将Database构造函数设置为public时,它可以正常工作。但那时它不再是单身人士模式了。
有什么建议吗?
数据库类:
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();
}
}