MVC Pattern – Where to Process User Input: Controller vs Model

language-agnosticmvcweb-development

I'm new to MVC and I'm not using a framework (and I'm not going to).

I'm designing my new web application using MVC.

I have the user input received in Controller. Suppose I have form data and an action to do with it, which can be "insert", "delete" or "update".

Must I have process that action in Controller or in the Model? That is: must I do:

# Controller
if (action == "insert") Model.insert(data)

or

# Controller
Model.process(data, action)

# Model.process
if (action == "insert") self.insert(data)

(language-agnostic example).

What is the "MVC way" to do it?

Best Answer

Your first example is the right one.

if (action == "insert") Model.insert(data)

But you should try to think of it this way: You have an application, and any interface to it (UI, tests, CLI, etc) is simply that - just an interface.

Interfaces to an application tell it what to do, and get data back from it. That's all they do.

So your interface in this example is the controller. The fact that the controller takes the application's output and renders it inside an HTML template is allegedly "coincidental".

On another note, I know you said you're not going to use any existing framework, but you should at least keep the following in mind:

  1. Learning how to use a framework is not always smooth and easy, but it's going to take you less time than trying to implement the set of features yourself.
  2. You might not be aware yet of all the pitfalls you're going to encounter. These are all covered, in one way or another, in big MVC frameworks.
  3. You might not (and probably don't) know all of the current or future requirements for your application. But frameworks already let you develop something simple today and make it easy to add new features tomorrow (because they're built-in, and built so they'll be easily integrated at any point).

I saw your "language-agnostic" examples were pretty much Python. If you like the language, you should know that Django is one of the biggest and most documented MVC frameworks (in general, not just in Python).