I am building a web app that needs to access various tables in a given MySQL db. To do that, I have created a generic class, see DAO_DBRecord.php
below, and I create children classes for each table I want to access, e.g., DAO_User.php
is used to access the users
table. The only difference in the children classes is that I change the value of the variable which contains the name of the table I wish to access.
My questions are:
1 - Should I make the DAO_DBRecord.php
class abstract? I'm not planning to instantiate it, and in fact as it is written I cannot access any table with it.
2 - Should I use constants in the DAO_DBRecord.php
class (e.g., const USER_TABLENAME = 'users'; const ARTICLE_TABLENAME = 'articles';
) and reference them in the children classes (e.g., private Stable = USER_TABLENAME;
)?
3 - Anything else I should do?
Class_DB.php:
<?php
class DB {
private $dbHost;
private $dbName;
private $dbUser;
private $dbPassword;
function __construct($dbHost, $dbName, $dbUser, $dbPassword) {
$this->dbHost=$dbHost;
$this->dbName=$dbName;
$this->dbUser=$dbUser;
$this->dbPassword=$dbPassword;
}
function createConnexion() {
return new PDO("mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser, $this->dbPassword);
}
}
?>
DAO_DBRecord.php
<?php
require_once('Class_DB.php');
class DAO_DBrecord {
private $dbh; // This is an instance of Class_DB to be injected in the functions.
private $table=NULL;
function __construct($dbh){
$this->dbh=$dbh;
}
function dbConnect(){
$dbConnection=$this->dbh->createConnexion();
return $dbConnection;
}
function checkRecordExists($recordIdentifier, $tableColName){
$dbConnection=$this->dbConnect();
$query=$dbConnection->prepare("SELECT COUNT(*) FROM $table "
. "WHERE $tableColName = :recordIdentifier");
$query->bindParam(":recordIdentifier", $recordIdentifier);
$query->execute();
$result=$query->fetch(PDO::FETCH_ASSOC);
if ($result["COUNT(*)"]>0){
return true;
} else return false;
}
}
?>
DAO_Users.php
<?php
class DAO_User extends DAO_DBRecord {
private $table='users';
}
?>