title: Database class design
body: <p>I'm creating a web app with various classes for things like the user, Smarty template control, etc.</p>
  
  <p>I already have a database class which is all well and good, but I'm concerned about the performance of it.</p>
  
  <p>Currently, in another class, I'm doing <code>$this-&gt;db = new DB()</code> to create a local database instance, however the database class's <code>__construct()</code> function creates a new connection to the MySQL server every time I make a new <code>DB()</code> instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don't have a vast amount of classes, but I only want one per page load.</p>
  
  <p>This is a stripped down sample of what I have at the moment:</p>
  
  <pre><code>// Database class used by multiple other classes
  class DB {
      private $dbh;
  
      function __construct() {
          $this-&gt;dbh = // PDO connection here
      }
  
      public function query($str) {
          // Do a query
      }
  }
  
  // Example class User
  class User {
      private $db;    // Stores local instance of DB class.
  
      function __construct() {
          $this-&gt;db = new DB();    // Makes a new connection in DB::__construct()
      }
  
      public function login() {
          $this-&gt;db-&gt;query('SELECT * FROM users');
      }
  }
  </code></pre>
  
  <p>I'm looking for the "best" or most common practice of doing this. I don't want to make 10-ish separate connections for each page load.</p>
  
  <p>I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:</p>
  
  <ol>
  <li>Would using a persistent connection to the MySQL server solve this multiple connection issue for me? </li>
  <li>Should I use a static factory class and return a DB instance instead of using <code>new DB()</code>?</li>
  <li>Is the proper solution to use an entirely static class and just do <code>DB::query()</code> (for example) every time I reference it?</li>
  <li>I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to <code>extend</code> each class somehow?</li>
  </ol>