tags:

views:

123

answers:

4

I have a database class which is constructed so that it opens a connection to the database when the first query is run. Should each of the other classes, used for the site's users, groups and so on, create one database object each? This makes the classes easy to deploy elsewhere; they will only depend on the database class. This will however need me to put the credentials in each class. Another approach which seems less messy for me is create a database object and keep it in a global variable. This reduces the active database connections at the same time as it makes it easier to config; the credentials only have to be set once.

Somewhere I've heard that global variables should be avoided. What's the best practice approach to this?

A: 

I would make a base class that only contains the connection management stuff and nothing table-specific. You can then put the credentials there.

Another option is using a static variable on such a base class for storing the credentials (instead of hardcoding them in a function, which is kind of dirty).

So BaseDBConnection::$username and BaseDBConnection::$password would contain the credentials, and your other DBConnection classes derive from BaseDBConnection and refer to self::$username, etc.

skrebbel
A: 

You could get your other classes to take a database connection object in their constructor. That way they don't have to know the credentials.

Another common way is to use singletons for database connections. Essentially this is still a global variable though, but it does mean that you can control the database object instantiation in one place.

Tom Haigh
A: 

You should avoid global database objects. Your database should be opened as late as possible and closed as early as possible.

You should use a database object internally per class and it should be only opened/closed when required.

James
A: 

I would create a 'configuration' file which would basically just store the credentials as variables and include it within the required Class files.

This way any credential changes only require alteration of the 'configuration' file.

EDIT:

I forgot to mention that this means a new instance of your database Class should be instantiated in every Class.

IllusivePro