我试图弄清楚我是否正确使用了 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 的正确使用,还是我误解了它的目的?
将查询过程抽象到这种程度是不必要的,甚至是不常见的吗?有时我觉得我试图让事情变得太容易......