-1

I am experienced with OOP but I am just starting to use the MVC model.

I would like to know what are the recommended practices to use PDO within the model and still keep a high level of abstraction. I have seen on the internet various approaches, the ones I liked the most were:

Making the model extends a specialized class for SQL queries, something like this:

class Car extends Model{...}
class Model extends SQLQuery{...}

Passing around a global database connection

class Car extends Model{
    private $connection;
    __constructor($pdo ...){
        $this->connection = $pdo;
        ...
    }
}

I also read some folks saying that all the queries should be made in the controller and use the model only to structure the data. I did not like much this one because it would not allow me to do such things like making a object change his self and update the database.

So, what are your recommendations?

  • You are getting one thing wrong right off the bat, that is thinking a Model in MVC is actually a class, which is wrong. Model in MVC is an entire layer - multiple classes working together. So depending on where exactly you are in the model layer within your systems determines the actual interaction with database. All in all, this question is too broad. – Andy Aug 5 '17 at 19:34
2

Does all of your models need to be connected to your database ? Do your models actually need to know the database object ?

You could abstract the way your models retrieve the data. maybe some will use direct file read, maybe some will use user input or session, or database.

I wouldn't tie my model class directly to my mysql connector, especially when those can be changed from one project to another.

One suggestion could be to make a recordable interface that makes the promise to setRecorder (record $record), with an app-specific recorder.

This way, (bonus) your model doesn't have to know how to build itself.

Not the answer you're looking for? Browse other questions tagged or ask your own question.