Controller vs. Model - Need explanation

M. A. picture M. A. · Jan 11, 2011 · Viewed 15.5k times · Source

I'm on the beginning of my "Learn MVC" way. Basically, I don't have big problems with object-oriented programming however there's one technical aspect that needs clarification. It seems that my theory isn't quite good enough.

Currently, I'm using KohanaPHP framework, version 3.

Example situation: I have a website, where user can submit an article.

So I have following structure:

classes/
    /controllers/
        article.php
    /models/
        articles.php

So far so good. I don't have problems with models that extends Kohana_Model however I'm not sure if I'm using the correct way models that are using ORM.

Basically when using models extending Kohana_Model I'll put all logical operations in model. Should I do the same for models using ORM? In many example over the Net I saw controllers that was performing logical operations on user input/data from database which is incorrect in my opinion.

Let's say I need to get few rows from database so I create proper method in model and returning the object. I think it's correct, isn't it?

Basically, all operations on user input/data (select from db, insert into db, validation) I put in the models. That's the way I understand MVC design pattern. Models should take care about all "mechanic" operations and controller is only a "bridge" between models/views and it's a "front" engine.

Is it a correct approach?

I know that might be a silly question for more advanced users however I want to learn only good practices. If anyone could deliver some clarification, I'll be delighted.

Answer

Poelinca Dorin picture Poelinca Dorin · Jan 11, 2011

In short terms, your model performs all operations on the data (be it incoming, outgoing, database, files ... data), and your view should take care of displaying the data. The controller should call the necessary model methods to get the data ready to be passed to the view. The controller shouldn't perform any changes to the data, but it should test it to get the necessary action done properly.

Hope I made it clear enough, let me know if this doesn't clear things for you.