I'm studying OOP and a little bit about the MVC structure, and I'm not sure where to create and instantiate the database to be used in the entire application, I thought how Model relates to data processing would be the best place to create the scope of the class, and as only the classes that extended the Model would also use the database, I did the following, for example:
Class Model {
private static $db = null;
private static $dbHost = 'localhost';
private static $dbName = 'mini';
private static $dbUser = 'root';
private static $dbPass = '';
private static $dbCharset = 'utf8';
protected function __construct() {
$this -> setConnection();
}
protected function getConnection() {
return self::$db;
}
private function setConnection() {
if (self::$db == null) {
$op = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
self::$db = new PDO('mysql:host=' . self::$dbHost . ';dbname=' . self::$dbName . ';charset=' . self::$dbCharset, self::$dbUser, self::$dbPass, $op);
return self::$db;
}
}
}
class userModel extends Model {
function __construct() {
parent::__construct();
}
public function getUser() {
$getAll = $this -> getConnection() -> prepare("SELECT * FROM usuarios");
$getAll -> execute();
$test = $getAll -> fetch(PDO::FETCH_ASSOC);
return $test;
}
}
And the call, in a controller, for example would be as follows:
$userModel = new userModel;
$getUsers = $userModel -> getUser();
Is this a good practice? and if not, why? as I am new to this, some concepts can be very advanced still, so I ask you to explain in a simple and gradual way.