Database Connections – Is Using a Single Connection Good Practice?

databasePHP

The PHP codebase I'm working on has an utility class that returns a database connection. The implementation looks like this:

class Database {
  private static $conn;
  private static $init = false;

  public static function connect() {
    if (!self::$init) {
      $cnf = new Configuration();
      self::$conn = new DatabaseConnection($cnf->get('dbname'), $cnf->get('username'), $cnf->get('password'));
      self::$init = true;
    }

    return self::$conn;
  }
}

Things have been done this way to apparently spend lesser time on opening connections, which occur over a network.

Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?

Best Answer

No.

Unless you are on a really crappy O/S (or, to be precise, your ODBC library and/or database access drivers/library, which may or may not be part of the O/S proper), your code is not actually creating/using/closing database connections. It is creating/using/closing database connection objects, which are a wrapper for the underlying connections. The underlying connection, meanwhile, is being managed in a pool.

When your application code "opens" a connection, you are actually telling the system to go fetch a connection from the pool, check its status, and open new connections only when needed.

When you "close" a connection, you are actually telling the system to return a connection to the pool for re-use later, or until it times out.

You can manage the number of connections, life cycle, timeout, etc. via ODBC client settings, or by inserting parameters into the connection string. Each unique connection string results in a pool of connections with those settings.

If you really really want exactly one connection, you can configure it that way at the pool level-- however this would be a really bad idea in a web application, which sometimes has thousands of threads.

Let the underlying O/S manage these connections for you. It is going to be way better at it than any code that you write.

Related Topic