Understanding Model-View-Controller

What is MVC (Model View Controller)?

You might want to take a look at what Martin Fowler has to say about MVC, MVP and UI architectures in general at Martin Fowlers site.

Understanding Model-View-Controller

MVC is a big, broad idea. It's more a guiding philosophy than a specific rule, and it's not always implemented the same way. Read Apple's discussion of MVC to appreciate the difference between traditional MVC and MVC in Cocoa.

It's hard to say how to apply MVC to your app because you haven't told us what the app should do, and also it doesn't sound like a realistic application. So I'll do my best here and make some assumptions along the way. An app that just draws a bunch of circles in fixed locations on a background isn't very interesting -- it could be almost all views, barely any need for a controller at all. So lets say that the circles are all moving in different directions, are drawn in different colors, and change in size over time. Now you start to have a need for a model, so that you can keep track of the data that these circles represent, and a controller to translate the model into terms that can be represented by the views.

Since you asked specifically about drawing circles, lets start with the view. It seems like a good idea to have a custom view that knows how to draw a circle given the necessary parameters: area, color, and position. You'd probably make these things properties, and override -drawRect: such that it draws a circle of the given area in the given color.

We don't know what these circles represent, but it's not much fun if they don't represent something, so let's postulate that the app's job is to help us compare corporations. We have data on revenue, market capitalization, number of employees, credit rating, name, ticker, etc. You could create a custom object to store all the data for each corporation, or you could put it all in a dictionary. Our model is a set of these custom objects or dictionaries.

Notice that the circle views don't know anything about corporations, and the model doesn't know anything about circles. This is A Good Thing. It's also where the controller comes in. The controller is where you put the code that expresses the model visually using the views. It also interprets events from the views, updating the model as necessary. So, our controller knows both about the particulars of the corporations, and the properties of the circle view. It creates a circle view for each corporation in the model. I want the area of a circle to correspond to the corporation's market cap, the vertical position to represent the revenue, and the horizontal position to indicate number of employees. We'll assign a color based on the corporation's credit rating. The controller should, of course, keep track of all the circle views and some way to map between circle views and corporations.

Now you've got something. It's still a pretty simple application, but you've got a useful chart comparing corporations in several dimensions. Let's improve it.

First, it's hard to know which circle represents which corporation. It would be nice if a circle view could optionally display some text. Let's add title and subtitle properties, and modify -drawRect: to draw these strings above and below the circle, respectively. We'll also change the controller so that a tap or click on a circle sets the title and subtitle of that circle to it's corporation's name and ticker symbol, or clears them if they were previously set.

Second, it's nice to compare corporations at a moment in time, but more interesting if we can show changes over time. Let's change the model to include historical data for revenue, market cap, employees, and rating. We can update the controller so that it can uses the historical data to animate the circles.

The first change related to how we draw information on the screen, and didn't require any modification to the model at all. The second change was about what data we have to work with, and didn't require any change to the view at all. You could easily re-use the circle view to represent some other kind of data, or maybe even to be the puck in an air hockey game. It's just a colored circle. And you could re-use the model in another app that deals with the same kind of data.

I'm sure the hypothetical application in this very long-winded explanation-by-example bears roughly zero resemblance to your own application, but perhaps it'll help to explain why MVC is useful and inform the structure of your own application. Good luck.

Simple explanation for MVC (model view controller) pattern

If I were explaining this to my grandmother who is not a programmer, I'd explain it with sugar, a cup of coffee, and herself:

(Disclaimer:This is not an actual photograph of my grandmother! I am not a perfect painter with Microsoft Paint!)

Why is the MVC concept important?

Well, like doing many things in life, it always helpful to be well organized. Models, Views and Controllers are distinctly different pieces of code that helps to provide different functions to your overall project. Because of that, they are kept separate and organized.

Imagine if you were designing a program. You wouldn't put all your code into one function, would you? No, you would divide them up into separate smaller functions that solve very specific tasks. Likewise, as programmers, we're constantly looking for ways to separate and divide our large applications to smaller bits of pieces. One of these organization design patterns is MVC, where, the model (the data) exists in one section, the view (the UI) exist in one section, and the controller (logic) exists in another section.

What problems does this solve? Well, just as how having separated functions solve the problems of readability, modularity, and coupling, so does MVC. Say if you wanted to change a piece of code, you can tackle it in a smaller subset that is more or less isolated from the larger piece of code. This allows you to add, modify or remove code more effeciently and logically. It also helps in testing, since similar code is sectioned into groups, you may be able to have better coverage of your tests cases. Also very important is that you end up writing a lot less code.

Hope this helps.

Understanding relations between model view and controller

The most basic explination of MVC would be that you have each of the 3 layers.

Model

  • This contains your data. i.e database or set of classes.

View

  • This displays data to the user i.e your HTML page.
  • Contains controls for user interaction.

Controller

  • All access to data should go through this layer. i.e load data from your data source(model) and save data to your data source.
  • Carries out any data manipulation before saving or loading.

This create a separation of concerns theoretically allowing you to change anything in either layer without the other layer knowing or caring making for far more maintainable and readable code.

In practice this can become more complicated depending on how you wish to access data and display it although the basic principles still apply, occasionally meaning that each part of MVC pattern could be made up of smaller parts.

In terms of implementing it a good example would be ASP.Net MVC http://www.asp.net/mvc. the following could be a simple implementation of displaying some data via MVC using C#.

Model (C# class)

public class Person{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Controller

public ActionResult Index(){
return View(new Person() { FirstName = "Person", LastName = "1" });
}

View (Index.cshtml)

@model Person

Full name: @Html.Raw(Model.FirstName + " " + Model.LastName)

This would output onto the web page

Full name : Person 1

Please forgive me for any syntax errors, not tested.

More detailed post: http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm

Understanding MVC on PHP with real application implementation

If you want to create your own framework or just want to develop app with following oops and MVC concepts then you have to read about the concept of MVC.
Please read

  1. http://phpro.org/tutorials/Model-View-Controller-MVC.html - You can also
    download source from http://phpro.org/downloads/mvc-0.0.4.tar.gz
  2. http://php-html.net/tutorials/model-view-controller-in-php read and get
    download link from that page.

Please let me know if this is helpful and enough to create our own small MVC Framework.

Thanks

MVC design pattern. How does View fit it?

A view's job is to display data and to report events.

The controller's job is to coordinate communication between views and models.

The data's job is store data and also to provide business logic around that data.

You asked:

I'm having trouble understanding were the "Views" fit in.

In your example, the UIPickerView is the view.

In iOS/OSX, a view controller is just the controller of MVC. It just so happens that a view controller also contains an empty view container that you can add all of the other views to. But there is still a clear separation of MVC in iOS/OSX.

All of the classes like UIButton, UIPickerView, UITableView, etc. represent the view. A view controller's job is to provide those views with data from data models as well as respond to events from those views giving you a chance to update other views and the data models.

You also stated:

However every view requires that a View Controller be connected to wire up all the outlets to the view. How am I suppose to keep the View and the View Controller separated?

They are separate. If you add a UITableView, that is a separate view. You connect it to a class so that class can implement the data source and delegate methods. That class is a controller class. It is common for this controller class to be a view controller but it doesn't have to be. You can write all kinds of custom view classes that are independent of any specific view controller (or generic controller). But eventually that view class needs to be hooked up to a [view] controller class so data and events can be processed properly.

You asked:

How or why would I want to have this View Class separated from my View Controller class?

Look at UITableViewController. This is a clear example of the separation but it is provided in a fairly neat package. You actually have a separate UITableView class which is the view. This view is responsible for rendering the view and gathering user interaction. It is the actual table view controller that provides the data to the view and handles the user events from the view.

You can add UITableView views to any view. This is a fully reusable view component. Each controller you hook up to a table view can provide any appropriate data and properly handle user interactions.

In the Model-View-Controller principle, what is the Frontend and what is the Backend?

OK.. first the terms:

  • Frontend - are the parts, which are visible to users: HTML, CSS, client-side Javascript. It all is basically "frontend". In a desktop application frontend would be the GUI.
  • Backend - is the invisible part. In web applications that is your java, ruby, php or any other serverside code. It can be either interpreted or compiled, because "how" it works has no impact on "what" it is.

If you read GUI Architectures and research the MVC pattern in general, you will understand that MVC is not about separation of backend and frontend. Especially when it comes to MVC-inspired patterns, that we use for web applications.

The goal of MVC and related patterns is to separate presentation from domain business logic.

Here are the basic responsibilities of MVC parts:

  • Model - business logic
  • View - presentation logic
  • Controller - changing state of model and view (based on user input)

Let's take an example:

  • alternative client application for twitter
  • uses OAuth for authentication
  • user can input different search phrases
  • takes information via Twitter's REST API
  • validates data
  • parses the JSON responses
  • manipulates DOM to present the information

This all can be done with client-side JavaScript. You can have MVC triad running "frontend"! At the same time, the "backend" which provides REST API is an MVC-like structure. Only this time the View is generating JSON responses, instead of HTML.

*Conclusion: You can use MVC pattern both on backend and frontend.**

Post Scriptum

Since you have been building some applications with Rails, your understanding of MVC might be a but distorted. The reason I say this is because, since RoR was initially made as a prototyping framework (notice all the scaffolding and other features for generating throw-away code), and because of its origin, Rails is actually implementing a very anemic version of MVP.

I call it "anemic", because they nerfed both View (it should be a passive object in MVP, not a simple template) and Model Layer (yes, it is supposed to be a complicated layer, not a collection of ORM instances).

I would recommend for you to read two publications to get a much better grasp on the subject:

  • Patterns of Enterprise Application Architecture.. mandatory reading for serious developers
  • A Description of the Model-View-Controller User Interface Paradigm in the Smalltalk-80 System

The second one is as close as you can get to initial definition of pattern. That, together with "GUI Architectures" article, should provide you a solid footing on the subject. And the PoEAA book (hard read, btw) would give you context in which to expand it.



Related Topics



Leave a reply



Submit