I'm trying to figure out if I'm using the DAO pattern correctly and, more specifically, how abstract db persistence should be by the time it gets to my mapper classes. I'm using PDO as the data-access abstraction object, but sometimes I wonder if I'm trying to abstract the queries too much.
I've just included how I'm abstracting select queries, but I've written methods for all of the CRUD operations.
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
So, my two questions:
Is this the correct use of a DAO, or am I misinterpreting its purpose?
Is abstracting the query process to this degree unnecessary, or even uncommon? Sometimes I feel like I'm trying to make things too easy...