I was wondering if there's a common best practice for setting up a mysql connection object in a php program so that you don't write redundant connection code over and over in your classes.
I'm currently doing this via a factory pattern:
class DBFactory {
public static function get() {
static $db = null;
if( $db === null ) {
// setup $db here
}
return $db;
}
}
So I can just run DBFactory::get()->query()
(or whatever) and the method will automatically instantiate my database connection the first time it's requested.
In practice my get()
method actually accepts a named database connection, and I store an array of database connection objects in my static, but the principle is the same.
There is no absolute right way of doing it but you can take other people's suggestions and perhaps combine them.
My idea is that you could require a file that prepares a connection and then declare a Global Variable and use that variable to execute all of your queries.
I use the Repository Pattern ( http://martinfowler.com/eaaCatalog/repository.html ) to put all of my database and SQL code into a small set of classes that are responsible for translating between the database and domain objects. This keeps all of the other code from having redundant db connection code or SQL queries.
I use it like this:
$criteria = new UserCriteria();
$criteria->active = true;
$repository->getUsers($criteria); // repo connects to DB and returns array of user objects