I am building my first PHP OO project and am very much trying to avoid code duplication and use best practices for database and class design.
An issue I have is around my DAO and how they get / use the database connection.
This is what I have so far;
class DbConfig
{
protected $db_host = 'hardcoded_host';
protected $db_name = 'hardcoded_dbname';
protected $db_user = 'hardcoded_user';
protected $db_pass = 'hardcoded_pass';
}
As you can see - these values are hardcoded, I then extend this class with my DAO, meaning I would only need to alter these details in one place.
class Dao extends dbConfig
{
private $dbh;
public function __construct()
{
// create $dbh PDO connection here and assign to private $dbh
$this->dbh = $dbh;
}
public function createUser($username, $password)
{
// use $dbh connection and insert new user to db
}
public function checkUserCredentials($username, $password)
{
// used to check login details
}
public function createClient($name)
{
// as with createUser, except for client
}
}
As you can see - I am performing CRUD operations on more than one database table / type - user and client.
I think the code would be better modulated and easy to understand if I had a user DAO and a client DAO (because there will be many more needed than these two) - but the problem I see is that I'd have to code the connection into each DAO.
Or I would have a connection class and pass this through the constructor of the DAO - is that a better option? The only issue I see is I would have to instantiate a connection class before I instantiate every DAO - and pass it into every method of all the DAO's.
eg:
$dbh = new databaseConnection();
$user = new UserDao();
$user->createUser($dbh);
This seems like unnecessary additional coding to me.
Should I stick to just one DAO? Or is there a way around having to write the connection method into every DAO if I create multiple? Using a trait perhaps?
EDIT: Another option - create te connection in my parent class DbConfig (top of the question), and then call parent::construct in each DAO's constructor thereafter. The problem I can forsee with this method is that I wouldn't be able to add any other initialisation code in the child classes.
Thanks