1
I’m studying POO and a little bit about the MVC structure, and I’m wondering where to create and instantiate the database to be used in the entire application, thought as the 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 it as follows, 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? Otherwise, why? as I am new to this, some concepts may be very advanced yet, so I ask you to explain in a simple and gradual way.
Thank you for the reply, about the first observation of the ini/env files, but so would not be unprotected for direct access? I usually put everything in a config.php as constant, in your second observation I didn’t quite understand the "your entity models" part what are these entities? and on the open querys, yes, I do generic methods in the Model for all "All, One, Byid", but had written the quick code just to clarify my doubts, thank you again for having answered.
– Thiago
And in this example that I did,?
– Thiago
Entities are tables, so the models of the tables must be specific and each have its own set of methods. When to ini file, ini format becomes unavailable to be served by webserver, so you have to take direct access
– KhaosDoctor