Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

I've read a few articles on the MVC pattern and tried to understand what it exactly is. But till now, what I get is a plain diagram showing 3 modules of Model, View and Controller. Some say that it helps increase code reuse (DRY), while I think it does the opposite.

I currently separate my application code into different directories, one for Viewing part (presentation: Html/Css/Js + client side req) and the other one for Core related functions. I haven't found any disadvantage to this approach yet. Maybe because I haven't developed big applications yet, just small hobby ones.

So, apart from this separation, what I find in MVC is some sort of url rewriting, which I think can be achieved if necessary. Is there something I am missing? There must be a reason developers are so inclined towards the MVC pattern.

share|improve this question

marked as duplicate by Mathew Foscarini, Robert Harvey, MichaelT, GlenH7, DougM Jul 19 at 21:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Just want to point out that code reuse isn't the same as repeating code. –  jcm Jul 17 at 6:32
4  
Please read this article - the answer you accepted is incorrect. –  Benjamin Gruenbaum Jul 17 at 8:31
1  
I would also encourage you to read up on MVP (Model View Presenter) and how it differs from MVC –  karancan Jul 17 at 20:17
    
@BenjaminGruenbaum , great article and does presents insight into MVP too. Thanks! –  Abhinav Gauniyal Jul 18 at 9:25

6 Answers 6

up vote 10 down vote accepted

Model The model represents the domain you are trying to model, and also encapsulates the business logic of your application. For example, using the good old blog example, think about all the things your make up your blog: Posts, Comments, Tags, Categories, Authors, Commentors, Editors, Feeds, etc.

This is your domain, and depending on which of those you want to work with in your application, you model them as the M in MVC. For example, you would create a Post model to represent a post that a user makes or a Comment model to represent a comment that a user makes. Most frameworks allow models to have have relationships with other models. For example, a model can 'own' one or more other models, or belong to one or more other models, or both at the same time. These relationships are typically expressed as:

  • One-to-One
    • The simplest type of relationship, a one-to-one relationship between two models simply says that one model owns the other.
  • One-to-Many
    • Since your authors create posts, you could reason that your Author model owns many Post models. This is expressed as a one-to-many relationship where your Author model is the one side of the relationship and your Post model is the many
  • Many-to-One
    • The opposite of the above relationship, one or more Post models belong to one Author model. Here, your Post model is the many side of the relationship and the Author model is the one
  • Many-to-Many
    • Sometimes, you have the scenario where you want many models to belong to or own many other models. Think about tags on your blog post. You would want to be able to associate many tags with many posts. Therefore, your Post/Tag models have a many-to-many relationship with each other.

Models are where you want your business logic to go. For example, lets say you wanted authors to be able to upload an image along with their posts, but you only wanted images of a certain size/dimension. The business logic for checking the images file size or changing its dimensions would go in the Post model, since that image is a property of the Post model and belongs to it. This leads to the saying that your models should be fat and your controllers skinny. A common mistake that new comers to the MVC pattern make is putting all the business logic in the controller and having empty models that just represent rows in a database (e.g., doing the image re sizing logic in the controller rather than the model).

Normally, you'll interact with databases using an ORM (Object Relational Mapper). If you are using a popular framework like Ruby on Rails, Laravel, Symfony, the ORM typically uses the ActiveRecord pattern. Some would argue that ActiveRecord is a bad pattern because it means that your models are responsible for persisting themselves to the database as well as their own internal business logic. Models don't have to be persisted to the database, but when they are their values are stored a row in a table in a database. They are not the row or even the database as another answer suggests. Typically the model's values will be stored in just one row, but you can (if you really, really want to) store them across multiple rows in different tables/databases. Other frameworks handle this differently. For example in ASP.NET MVC models are not responsible for persisting themselves to the database. Whether one is better than the other is debatable. I use both Rails and ASP.NET MVC and appreciate both approaches where it makes sense (simple applications with simple models ActiveRecord is great). The main problem with the ActiveRecord approach is that your model has to be the same as the table that you are saving it to in your database. If you have a much larger table and you want to extract data from it and map it to a model (think pre-existing/legacy data) becomes tricky.

View Views are the simplest part to understand, because they are simple by nature. The convention with most MVC frameworks is that your views should be dumb. That is, they should not perform any business logic (that is done by your models, remember?). All they do is receive data from the controller and display in a way that looks nice to the user.

While your view shouldn't be performing business logic, you can have some client side logic in there. For example, if you have a view to display a list of posts or authors, you can use JavaScript to allow users to do things like dynamically change the ordering of the list (without having to make another HTTP request to your application). The point is that they can apply some processing to the data they receive, it should be only for the purposes of displaying the data in a different way, not changing it.

Controller The controller is the glue that holds your application together. Think of them like the conductor in an orchestra. While they don't actually play any instruments, the orchestra wouldn't be able to function without them. Your controllers are the same. They interpret requests from the user and perform the necessary operations to produce a desired result.

Typically, when your user enters a URL (let us say posts/show/my-first-post) your MVC framework (Rails/Laravel/ASP.NET MVC/whatever) will have a routing engine that will parse the URL and determine the correct controller to invoke. Usually, your URLs will follow some sort of convetion that makes this easy. Let us say you are using a convention where the URL segments relate to {controller}/{action}/{id} where the first segment is the controller to invoke, the second segment is the action on that controller to use, and the third (or however many parameters you wish to pass to the controller) are passed to that controller's action as parameters. So, if you had a post controller with a show action that took one parameter, id the routing engine would pass along the HTTP request to it.

Typically, your controller will invoke a model (which performs some business logic and returns a result) and then passes that result along to the view for your user to see (in the form of a web page).

share|improve this answer
2  
Please stop confusing "active records" and "model". –  teresko Jul 17 at 13:34
1  
For the record, ASP.NET MVC is not an MVC framework, neither do they claim it is one. It's an extremely poor name choice. –  Benjamin Gruenbaum Jul 17 at 16:58
1  
-1: model is not a row in a database. –  teresko Jul 18 at 12:20
1  
@BenjaminGruenbaum, I think Microsoft does consider ASP.NET MVC to be an "MVC Framework". Take a look at weblogs.asp.net/scottgu/asp-net-mvc-framework. Now, whether it's any good is a separate question. –  user1172763 Jul 18 at 16:24
1  
One line proof - in MVC the view observes the model which is definitely not the case in asp.net mvc. –  Benjamin Gruenbaum Jul 18 at 16:27

I'm going to try to explain this with an example.

Lets say you want to build a website that shows people a list of friends. So it starts with a list of your friends (A,B,C..). When you select one, it shows a list of their friends (A1, A2, etc) and so on.

The "View" is an implementation of what the user can see. In this case, we need only one view i.e. a table to show a list of people. The view does not care who these people are, where they came from or how they are related. It just displays a list of people and relays any user actions (clicks, etc) to the controller.

The Model has a list of people and their relationships. It doesn't know what to do with them or how an action on the view affects them. It simply has a list of people.

It is the Controller's job to "take a list of people and give it to the view for display". When a user clicks on a person, the view will relay that action to the controller, the controller will look into the model for relationships for this person and extract a new list of people, which it will then give to the view for display, and so on.

I hope you can see how this sort of architecture would be beneficial in large projects. It greatly simplifies code, promotes reusability (I can use the same View to display a list of any "people" objects) and makes it easier to change one aspect of the project (data or UI) without affecting the other.

share|improve this answer
3  
-1: no, controllers job is NOT to pass data from model layer to view. Controllers job IS to alter the state of model layer. –  teresko Jul 17 at 15:00
1  
While I agree with teresko, this is the best answer here by far –  CurlyPaul Jul 17 at 16:52
1  
@teresko I was trying to simplify the example. If you could improve the paragraph about the controller, I'd love to hear your inputs. –  user1349663 Jul 17 at 17:24

The idea is simply to create a clear separation between business logic and the UI.

The Model is the data and the business logic of the application. The View is UI logic, and creates a visual representation of the Model. The Controller is mediating between the two to keep them loosely coupled.

Here's an example to help you understand. This relates more to desktop MVC, not web MVC, but the general idea is the same:

Imagine a text processing application. The user has just selected some text and pressed the 'Bold' button.

The View knows that a button was pressed, but doesn't (and shouldn't) know how to handle this event. So it notifies the Controller (e.g. controller.boldPressed()).

The Controller 'knows' what this means for the Model. Sometimes it would mean simply doing model.makeTextBold(), and sometimes it would mean something more complex, such as first fetching the selected text from the view, and then making several method calls on the model.

The Model then receives the method calls from the Controller, and performs the desired actions, i.e. making a piece of text bold. Note that the text is kept inside the Model - this is where the data is kept. The View is merely a visual representation of this data, i.e. a visual representation of the Model.

At the last step, the View has to be notified that the state of the Model has changed, so it can update itself (it's a visual representation of the Model). This is often done via the Observer pattern (learn it if your'e not familiar with it). Or, it can be done by the Controller.

The View is notified that the Model has changed and updates itself. And we got some bold text.

This is the idea. As you can see, the View knows nothing about how the Model operates, and more importantly, the Model knows nothing about the View. This loose-coupling makes things easier to maintain, because you don't have business logic in your UI event handlers, and no intimate knowledge of the UI in your business logic. And it can even mean that you can replace different Views or Models with minimal changes to the other parts of the system.

One last thing: note that sometimes the Controller may feel unnecessary, like all it does is pass method calls to the Model. In small applications, this will often be the case. But it's still good to have this separation layer, in case the application gets bigger.

Hope this helps.

share|improve this answer
    
Coming from WPF background , this answer made me understand MVC in best way. Thanks :) –  Abhinav Gauniyal Jul 18 at 10:45
    
@AbhinavGauniyal You're welcome :) –  Aviv Cohn Jul 18 at 11:02

I learnt about this once but not from a book.. but hopefully this is not inaccurate.

MVC stands for Model, View, Controller.

The View is the GUI

The model is most of your program, and the controller is part of your program that interfaces between your model and your GUI/view.

The benefit to that is that e.g. if there is a sudden change in requirements, and a new GUI is required, then when you have separated your program into those components, you only have to change one component. The Model part of the program won't have to be rewritten or amended. (perhaps the controller will need a little amendment but not much). And you just focus on writing the view portion. So your program is built to have different views.

Furthermore if you had to structure your program differently, in terms of how you store data, then you wouldn't have to rewrite code that describes the GUI.

share|improve this answer
    
The model is not "most of your program". It's the encapsulation of the data needed to be displayed on the single View. –  krillgar Jul 17 at 15:26
    
@krillgar I disagree, I think the model is "most of your program". It's not only data for a single view, it can be the data of the entire program, viewed by several views. –  Aviv Cohn Jul 17 at 16:09
    
That's confusing the data as a whole with the data for a single view. –  krillgar Jul 17 at 16:22
    
@krillgar Neither prog nor I have made any confusion. I suppose you can have one model for one view and another model for another view(if that's what you want) But you can also have one model and multiple views(and that doesn't 'confuse' anything). You have your model(s) and your view(s). You can have multiple of each. And if you want(and you seem to), you could place restrictions on what view can access what model. But otherwise there's no reason to say this model or THE model(if you just have one) is for a single view only. –  barlop Jul 17 at 21:37
    
@krillgar I am not sure if one could or should say the data is separate from the model but perhaps it makes good sense to. I suppose you could say there's the permanent stored data. and the models(which work with data in RAM), and the views. There is still no need to say this data is only for this view, unless you want to make that restriction. Two views could be two alternative designs(as mentioned), in which case there is not just overlap but complete overlap in what they are displaying. –  barlop Jul 17 at 21:54

I suggest you the "book" I am writing about MVC. It's far from complete, but it may give you an idea.

MVC on the web is a strange beast, however. If you check most resources, they will present MVC for a GUI, but on the web you have a different structure: the View is isolated from the Model and the Controller, can only push requests, and the communication is slow. For this reason, the entry point is on the controller, which acts more like a mediator. The View does not talk to the Model directly, like in traditional MVC.

share|improve this answer
    
Great resource , I'll leave comments soon. ;) –  Abhinav Gauniyal Jul 18 at 9:29

Models are essentially objects that wrap databases, and instances of those models are essentially objects that wrap rows in the database. Model instances have functions that allow them to change their internal state and interact with other model instances of a different type. This is where most of your business logic should live.

Controllers are essentially urls/routes that capture POST/GET data and perform LIMITED logic depending on the state of the application, such as redirection or displaying different views. They provide a shared scope for views and models to pull/store data. Controllers can be as simple as just passing the GET/POST data straight to the model and having the model figure out what to do from there (such as when saving data), and then telling the application which view to display. The model should not be allowed to determine what what parts of the view are displayed directly (models should not generate HTML directly, but should be passed to the view and the view can determine which attributes of the model to display).

Views are your simple HTML/CSS/JS templates with placeholders for certain variables. Most of the point of MVC is to make sure people stop putting logic in their views. Logic within the view should be minimal, mostly "if" statements and loops to display arrays of data.

Controllers help views by ensuring that logic in the views are minimized. For instance, if you have 10 different sidebars depending on the user type, it should be the controller that checks this and tells the view which one to display.

Models help controllers by ensuring that all business logic is contained. This way, logic dictating interactions between model instances is contained within the definition of the model. It helps ensure that the instance's current state is maintained by variables within the scope of that instance, instead of spread out over a bunch of global variables or variables that belong to other instances.

share|improve this answer
1  
@AbhinavGauniyal: MVC is a design pattern and that means that it is a particular way of designing a part of an application that has been given a name for easy communication. Lots of frameworks follow the pattern (and advertise that), but you can certainly implement it yourself without using any framework. –  Bart van Ingen Schenau Jul 17 at 6:27
7  
This is widely inaccurate and mostly incorrect - although it's what a lot of frameworks advertise. A key point in the MVC pattern is that the views observe the models for changes and this does not hold here. What you describe is a sensible way to structure db skins but is NOT MVC. –  Benjamin Gruenbaum Jul 17 at 8:30
16  
You lost me at "Models are essentially databases". Models are most definitely not databases. "Instances" of these models are most definitely not rows in the database. –  Madara Uchiha Jul 17 at 8:30
3  
Take it easy guys. He's a new member. Just downvote it if you disagree. –  Mathew Foscarini Jul 17 at 15:49
2  
@unyo Please correct your first paragraph to prevent further downvotes. Models are not Databases. However, you're correct about Models being the place for business logic. Please expand more on this idea. –  Roman Mik Jul 17 at 16:31

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