1

I have a PHP application which is pretty simple: It allows the user to create, edit and read a post. Basic stuff.

I have a Database class which handles the connection and the queries execution. The thing is that I want my models (I am using a self-built MVC framework) to be clean, so I created in Database some functions such as CreatePost(), EditPost() etc., which contains all the SQL needed, so I can call them nicely from the model: $database->CreatePost(/* post data */);.

Should I keep those functions in the Database class, or should I put them elsewhere (let's say, a class)? Maybe I should even give up on the functions idea and write the code explicitly in the model?


EDIT:

the answer is probably opinion-based, but still - I am trying to figure out what most of the people would do according to well-accepted modern conventions.

1

Having the model creation process in your database class may look like a good idea now, but it will be a problem when you decide to change the place where your models are stored.

The database class should only provide basic interface, such as querying it, creating transactions, and/or fetching the data in multiple ways (single, multi, associative,...).

You then make a class (preferably implementing a generic interface), which will be using your database class and its interface to query the db, and in your app use this newly created class so your application will be database independent.

Also, your database class should implement a generic database interface, so you can potentially swap out the implementation, if you ever need to.

1

Your way of handling it is the common solution (in my opinion). But there are also other styles of design e.g. the domain-driven design. It's the basic paradigm for developing typo3 extensions and considering your problem you could build sth like this:

  • Model: These are your model object classes
  • Controller:This contains your controllers
  • View: Basically your frontend/your views
  • Repository: This contains a class which handles all db operations e.g. Database(it is used by a controller)
0

The way I look at this, the Database class should not know about what model the application uses. Also the Model should not be aware of the Database class. The class combining the two should be the Controller. It should contain code that would tell the Database class to create and edit stuff, based on the Model. The Model should contain business logic (in this case stuff like validations, etc).

  • Shouldn't the controller be just a bridge between the Model and the View? And what about the "Thin controller, fat model" principle? Also - are you related to Joost van de veen from this tutorial? – Sipo Oct 22 '15 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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