I'm working on a project where I have several different classes that need to connect to a MySQL database. My question is how do I accomplish this from inside the instantiated classes efficiently. I've read that opening and closing multiple connections is a bad idea and using globals also isn't a great option... So what other options are there? Is there a standard or best practive for accessing databases in this kind of situation? I'm still a beginning programmer.
1 Answer
Establish a connection then pass that connection object to each of the classes that require it as an argument to the constructor.
class myClass {
function __construct($db) {
$this->db = $db;
}
function doStuff($someQuery) {
$result = $this->db->query($someQuery);
// fetch data here...
return $someData;
}
}
Then
$db = new mysqli($host, $user, $password, $dbname);
$someObject = new myClass($db);
$data = $someObject->doStuff($myQuery);
6 Comments
Could you expand on that? If I create a class, should I create a static class just so I can ensure there's only one instance of that class? And would you say creating a class is a better option or just creating a normal connection like you specified in your answer? Is there any downsides, such as security concerns or anything?
|