title: What's the best way to abstract the database from a PHP application?
body: <p>My question is how does one abstract a database connection from the model layer of an application? The primary concern is to be able to easily change from different types of databases. Maybe you start with a flat file, comma-delimited database. Then you want to move to a SQL database. Then later you decide an LDAP implementation would be better. How can a person easily plan for something like this?</p>
  
  <p>For a simple example, let's say you have a user with a first name, last name, and email. A very simple PHP class representing it might look like this (please ignore the problems with public instance variables):</p>
  
  <pre><code>&lt;?php
  
  class User {
    public $first;
    public $last;
    public $email;
  }
  
  ?&gt;
  </code></pre>
  
  <p>I have frequently seen where people have a DAO class which has the SQL embedded in it as such:</p>
  
  <pre><code>&lt;?php
  
  class UserDAO {
    public $id;
    public $fist;
    public $last;
    public $email;
  
    public function create( &amp;$db ) {
      $sql = "INSERT INTO user VALUES( '$first', '$last', '$email' )";
      $db-&gt;query( $sql );
    }
  }
  
  ?&gt;
  </code></pre>
  
  <p>My problem with strategies like this is when you want to change your database, you have to change every DAO class' create, update, load, delete functions to deal with your new type of database. Even if you have a program to auto-generate them for you (which I am not particularly a fan of), you would have to edit this program to make it work now.</p>
  
  <p>What are your suggestions for how to handle this?</p>
  
  <p>My current idea is to create a super class for DAO objects with its own create, delete, update, load functions. However, these functions would take arrays of the attributes of the DAO and generate the query itself. In this manner, the only SQL is in the SuperDAO class rather than being scattered about several classes. Then if you wanted to change your database layer, you would only have to change how the SuperDAO class generates the queries. Advantages? Disadvantages? Foreseeable problems? The good, the bad, and the ugly?</p>