title: PHP Database connection in DAO's
body: <p>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.</p>
  
  <p>An issue I have is around my DAO and how they get / use the database connection.</p>
  
  <p>This is what I have so far;</p>
  
  <pre><code>class DbConfig
  {
      protected $db_host = 'hardcoded_host';
      protected $db_name = 'hardcoded_dbname';
      protected $db_user = 'hardcoded_user';
      protected $db_pass = 'hardcoded_pass';
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>class Dao extends dbConfig 
  {
      private $dbh;
  
      public function __construct()
      {
          // create $dbh PDO connection here and assign to private $dbh
          $this-&gt;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
      }
  }
  </code></pre>
  
  <p>As you can see - I am performing CRUD operations on more than one database table / type - user and client.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>eg:</p>
  
  <pre><code>$dbh = new databaseConnection();
  $user = new UserDao();
  $user-&gt;createUser($dbh);
  </code></pre>
  
  <p>This seems like unnecessary additional coding to me.</p>
  
  <p>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?</p>
  
  <p>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.</p>
  
  <p>Thanks</p>