【发布时间】:2012-07-01 06:09:47
【问题描述】:
我试图弄清楚我是否正确使用了 DAO 模式,更具体地说,当它到达我的映射器类时,抽象数据库持久性应该是怎样的。我使用 PDO 作为数据访问抽象对象,但有时我想知道我是否试图抽象查询太多。
我刚刚介绍了我如何抽象选择查询,但我已经为所有 CRUD 操作编写了方法。
class DaoPDO {
function __construct() {
// connection settings
$this->db_host = '';
$this->db_user = '';
$this->db_pass = '';
$this->db_name = '';
}
function __destruct() {
// close connections when the object is destroyed
$this->dbh = null;
}
function db_connect() {
try {
/**
* connects to the database -
* the last line makes a persistent connection, which
* caches the connection instead of closing it
*/
$dbh = new PDO("mysql:host=$this->db_host;dbname=$this->db_name",
$this->db_user, $this->db_pass,
array(PDO::ATTR_PERSISTENT => true));
return $dbh;
} catch (PDOException $e) {
// eventually write this to a file
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
} // end db_connect()'
function select($table, array $columns, array $where = array(1=>1), $select_multiple = false) {
// connect to db
$dbh = $this->db_connect();
$where_columns = array();
$where_values = array();
foreach($where as $col => $val) {
$col = "$col = ?";
array_push($where_columns, $col);
array_push($where_values, $val);
}
// comma separated list
$columns = implode(",", $columns);
// does not currently support 'OR' arguments
$where_columns = implode(' AND ', $where_columns);
$stmt = $dbh->prepare("SELECT $columns
FROM $table
WHERE $where_columns");
$stmt->execute($where_values);
if (!$select_multiple) {
$result = $stmt->fetch(PDO::FETCH_OBJ);
return $result;
} else {
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($results, $row);
}
return $results;
}
} // end select()
} // end class
那么,我的两个问题:
这是对 DAO 的正确使用,还是我误解了它的目的?
将查询过程抽象到这种程度是不必要的,甚至是不常见的吗?有时我觉得我试图让事情变得太容易......
【问题讨论】:
-
如果您没有以任何方式定义或使用属性
this->dbh,那么让__destruct执行$this->dbh = null;有什么意义?每个$this->db_connect();结果都分配给方法范围级别的本地范围$dbh...
标签: php design-patterns data-access-layer