What is the most appropriate way to instantiate a database in an MVC standard

Asked

Viewed 337 times

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.

1 answer

2

Yes, it’s good practice, including this model is a standard known as DAO (Data Access Object), not in its entirety, but what you did there has many characteristics of it.

Some considerations of what you can improve:

Where do you put the connection data:

private static $db = null;
private static $dbHost = 'localhost';
private static $dbName = 'mini';
private static $dbUser = 'root';
private static $dbPass = '';
private static $dbCharset = 'utf8';

Ever put sensitive connection data into codes. What I advise you to do is create a file .env in format ini (you can even call him .env.ini and use the function parse_ini_files PHP to le it. In this file, put your connection settings and database.

Now for my second consideration, the DAO objects, ie, are your entity models, for example, you own the user class that has your model, the user class would have your UsuarioDAO which would be the model that would access the database. In this way it becomes necessary to use a connection manager class, a pool of connections as I call.

This model uses the standard Singleton to return only a single instance that is connected to the database so that all DAO objects use the same connection and do not open new ones over time.

I advise you to use the connection manager model (a new class) that will be responsible for serving a connection to all objects that connect to the database.

The last observation I have would be not to have a method that leaves "query open", as you did here:

   $getAll = $this -> getConnection() -> prepare("SELECT * FROM usuarios");

Notice the following, you’ve already named this action: getAll, i.e., a DAO object must contain all actions that are possible for the same, in this case you should have some of the type: getAll, getOne, getByName, getById, etc...

It is a bad practice to leave the query open, because if you do, the sense in creating object models is totally lost.

  • 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.

  • And in this example that I did,?

  • 1

    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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.