I’m sure what i’m currently doing is not optimal, but I would really like to hear some opinions regarding how you should handle all db queries on a web application including the connection string.
At the moment, I have a classes directory that has a file for each class and I have another directory called db that includes a conn.php which has the connection string and the other files on the db directory are like in the classes directory, one for each class but to handle the mysql queries.
So basically I have all db queries per class in one file and whenever I need to query something from the class file, I call the function on the db file
I include each db file in the corresponding db file, for example in the user.class.php file you will find include('db/user.db.php').
Also, I include the conn.php file to each db file.
user.class.php:
include('db/user.db.php');
class User {
public $fname;
public $userid;
function __construct($userid) {
$this->user_id = $userid;
$this->fname = DB_GetFirstName($userid);
}
}
user.db.php:
include('conn.php');
function DB_GetFirstName($userid) {
$result = mysql_fetch_array(mysql_query("SELECT USR_FName FROM users WHERE USR_ID = '$userid'"));
return $result[0];
}
conn.php:
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("dbname", $conn);
How do you handle it?
You are doing the right thing already by separating your Domain Layer from the Database Access Layer. But the way you put it together could be improved. Have a look at the Table Data Gateway (TDG) pattern.
In the Table Data Gateway pattern one class encapsulates all the access to a specific table. This is kind of like your User.Db.php with the difference that the TDG is an actual class. Instead of a bunch of functions you group any related db access into that particular class. This has the immediate benefit that you can pass the instance to any class that needs it instead of hardcoding function calls into them.
Whenever you need to work with a specific table you use the TDG to fetch/modify rows from it. You can then either work with the returned recordsets. Or use a DataMapper to map the data from the recordset onto your Domain classes, e.g. your User class. For simple DataMappers crafting your own is fine. Once it gets more complex, you’ll better of using an existing ORM.
An alternative to the TDG would be the Row Data Gateway pattern.
There is a good introduction to TDGs (with a Zend Framework example) at
and for Row Data Gateway