Similar questions have been asked but I believe they do not cover my case.
I experimented with a few ways to pass db class to other classes for access and found that the below works well. My question is: is there anything wrong with that approach and whether Dependency Injection will be a better solution?
class Database{
private $db_host = "localhost";
private $db_user = "root";
private $db_password = "";
private $db_name = "dbName";
private $pdo;
public $instance;
function __construct() {
try{
//create a PDO connection and assign it to some handler
$this->pdo = new PDO('mysql:host='. $this->db_host.';dbname='. $this->db_name, $this->db_user, $this->db_password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// echo "connected";
} catch (PDOException $e) {
exit("Error connecting to database". $e->getMessage());
}
}
public function getPDO(){
return $this->pdo;
}
}
class OtherClass{
require_once 'Database.php';
private $db_instance;
private $dbh;
function __construct() {
$this->db_instance = new Database();
$this->dbh = $this->db_instance->getPDO();
}
}
How about a simple class from which you can create and destroy a connection to the database if its not needed. Lets refractor your code abit.
First create a classname that can be identified easily, something like
Its a pdo class, but based on mysql, next declare some variables, (The explanation in the comments)
Then lets define the constructor for our class:
Note that when the class is instantiated, most class variables are set. Then our connection function:
And finally a function to disconnect our connectio to the database:
And a finally a function to query the database:
This class will use data that is pre populated, so lets create for it a function to initialize it: (this should be in a different file/class)
A case usage of the above code:
This is just a shaddy example from my head to give you some rough ideas, but its fully guaranteed to work if coded correctly, with the above classes and functions, you can change the engine to either
PDO_mysqli
or another another by changing the value in your config file. Hope you get the idea