As of right now I have a database connection string included at the top of each of my pages. I’m then passing my database connection to the methods in my class like this:
public function select($db) {
//Code here
}
Code on page:
$login_user->select($db);
My thought is that if I ever want to query a different database I can just create a new connection string in my include file called $db2 and then I just pass that value instead of $db.
Is this a standard way of doing this or do you have a different recommendation?
Passing a connection string to your classes has lots of disadvantages and no benefits. You are on the right track, but you want to pass the database object instead of a connection string.
Dependency Injection is a good way of giving your classes access to the database, which simply means to pass dependencies (ie database object) to the objects that need them, rather than the object itself obtaining the dependency from a global variable of some kind.
I would suggest that you use a method like
setDb()on your classes to pass the database objects, and then store it as a property for any internal use.For example, assuming you have created the database object
$dbin an initialisation script:DI gives you the benefits that you mentioned: the ability to easily switch the db without having to do lots of work in your methods. There are other benefits, namely ease of testing.