MVC, difference between controller and model? - ios

I was watching some Swift instructional videos from Stanford on youtube. The instructor (Paul Hagerty, great teacher!) speaks about how iOS is built around the idea of MVC (model-view-controller). I've read some people say on stack overflow that the idea is dead, and others say that a lot of web developers use this terminology now.
I'm having trouble differentiating between controller and model. I've read MVC described as user interface (web page/UI), controller (server), and model (database). But the instructor described it as view (UI, which is easy to understand), model (data and logic that does a calculation for example), and controller (which connects model and view with your specific programming logic).
What I don't understand is if there is no database in the case of a standalone application (not web), aren't we also creating the data and logic of how our program works at the same time? What is the difference between controller and model in this situation?

At the risk of being crucified for over-simplification: you can think of MVC as a way to separate "concerns" - in English - each has it's own "responsibility" (separation of concerns).
So in your "simple example" you could "separate" the concepts as a client and a server - risking even more shame, a browser and some web site.
controller: The browser takes user input and makes a request to;
model: A web site that responds with some data which could simply be a HTML document
view: The browser renders that data to user
So:
The browser doesn't "know" how the data was created/built, it just manages the request/response and displays the result
All the web site does is build some data and give it (back) to the requester. It doesn't care how it's used/rendered/displayed/filtered etc.
All the view does is render/display data in some meaningful way to the user. It doesn't care where the data came from, nor how it was built.
Hth.

The model is the data. Imagine a table view controller. The view is the table view. The controller is the UITableViewController. The model can be as simple as an array of strings.
The controller mediates between the model and the view. It picks the data that it wants to display and installs it in the view.
For a really simple view controller that just shows some text, the model could be as simple as a string. If the text is static, a view controller might not even have a true, separate model. It would just display the text that's baked into the storyboard.

Related

Why does the View know about the Model?

I have done some work on ASP.NET MVC 3 but I'm no expert.
So, based on the pattern definition, the view has no direct awareness of the model and does not communicate with the model directly; only controller is directly dealing with model.
However, in ASP.NET MVC 3, I can access the model data directly from the view using Razor engine. Isn't that breaking the pattern design or am I missing something?
the view has no direct awareness of the model and do not communicate with the model directly
Not exactly. Exactly how to interpret this statement might depend on the reader.
I've read quite a bit on model-view-controller and asp.net-mvc and I find similar statements scattered around and so the way it's worded can be a bit confusing.
A view knows what the model is. That is, it should know what the model type is, what the model contains or by some means know how to use the model to display what is necessary.
If we have a page called UserProfile then the view knows that it should display the user's name, email address, age and favourite website.
The view might be told to expect a UserProfileViewModel. Such a class would contain exactly the properties that the view needs so that it can easily display them.
What is better to say is that the view should not modify the model. In fact, the view should not do much of anything. Views are supposed to be stupid - they aren't for processing business rules, modifying data, connecting to databases, and so on. They just display stuff.
The model contains the data, the controller manipulates the data and the view displays the data (model). The view therefore is the interaction with the user.
The view must know what to show, so it has the model (with its data) to do so. It never manipulates directly, but sends information to the controller which in turn will manipulate the data.
I guess you have mistaken the concept of MVC. MVC does not say that "View is not aware of Model". In practice, each view is tightly coupled with a model (unless view is coupled to dynamic model or base type).
MVC is actually separation of concerns.
Controller decides the business rule and decides what data to be shown to user.
Then it populates the Model.
Then pass on the Model to View. (Think of it like passing on some data to be displayed on view).
Now View is not aware how model is created and validation rules of model.
Model is not aware which view will consume it. There can be many views coupled to a model.
Controller is not aware of model validation or what property of model is being displayed on view.
And MVC is just a pattern to follow, it does not stop you from writing business logic inside view or make db calls from view.
Refer to this article to read about the three different types of "models" introduced by ASP.NET MVC.
What it sounds like you are referring to is the view model. This model is simply a container or a way provide structure around the data that the view is responsible for displaying. It is simply a data-transfer object (does not have any behavior).

MVVM ViewModel vs. MVC ViewModel

ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.

Is there any dependency between view and a model?

Normally in the MVC Pattern, when a user clicks on a page the request would be sent ,then controller would handle the request ,then process it using the model and route it to the appropriate view.
I have read the post about the passive model and active model,but is there a possibility where the view directly interacts with the model, would that be a bi-directional relationship (i.e Model<->View) or one-directional (i.e Model->View).
Is it appropriate to have a relationship between Model and View? Well in a ASP.NET MVC project should i have a relationship between model and view, or have it independent of the model?
I think it's almost always preferable to have your views be model-specific, that is, strongly-typed. Where models share related data, you can reuse partial views that are specific to that subset of data. In ASP.NET MVC, your model is -- or should be -- ignorant of the view since they only way they can interact is through a web request, which is a controller function. No you may say that you could interact through web services, but I would consider those to just be another flavor of controller. In fact, with MVC, I see very little need to develop a separate web service at all, using REST-based controller actions instead.
I always see the View as the way to present the Model. According to this point of view, the View is Model aware and in ASP.NET MVC you should inherit pages from ViewPage to avoid abusing from ViewData or castings.
With that in mind, the Model is not view aware and is just an object that is used from the view to present data to the user.
Finally, you can share the same Model from different Views, for example an XML output can share the same model as the HTML output but the views can be very different.
The cycle is more or less, Controller generates Model, passes it to the View, that shows de Model and in case there's interaction, posts the input to the Controller and the cycle starts again.
In Java Swing MVC is implemented as the View and Controller combined, with a View that both reads from the model and registers for events from it which effectively makes them loosely dependent on each other.
Usually web applications don't do this as the real view is rendered on the client and can't receive events from the model as easily, so in those cases the relationship only goes one way. Its certainly not a bad thing to have a relationship between the model and the view as long as the Model does not dependent directly on and view classes. In that case a dependency cycle would be set up and that harms maintenance and especially testing.
For example the way this is achieved in Swing is via a Listener interface, which the view can then implement/provide an implementation of to the model.

What is MVC in Ruby on Rails?

Could someone please explain MVC to me in Ruby on Rails, in layman terms. I am especially interested in understanding the Model in MVC (can't get my head around the model).
Some background, MVC is a (compound) design pattern and was developed in 1979 by Trygve Reenskaug (Smalltalk).
True MVC was primarily planned for use in n-tier (non web) systems and it splits a system into 3 distinct parts, a Model, View and Controller
The Model
Contains data for the application (often linked to a database)
Contains state of the application (e.g. what orders a customer has)
Contains all business logic
Notifies the View of state changes (** not true of ROR, see below)
No knowledge of user interfaces, so it can be reused
The View
Generates the user interface which presents data to the user
Passive, i.e. doesn’t do any processing
Views work is done once the data is displayed to the user.
Many views can access the same model for different reasons
The Controller
Receive events from the outside world (usually through views)
Interact with the model
Displays the appropriate view to the user
** Classic MVC is not suited to web applications, as the model cannot send all changes to the view in an observer fashion (the view is a web page). The Model2 was introduced to overcome the changing infrastructure by JSP team in 90s . MVC Web frameworks are really not MVC, but Model2 (this is true of Ruby on Rails).
Here is a description of GUI patterns including MVC from the master, Martin Fowler
GUI Architectures
The best book I have found so far is Agile Web Development with Rails. It begins by assuming no knowledge, and is quite comprehensive.
Hope this helps to shed some light for you!
MVC basically indicates Model-View-Controller. And MVC used by many languages like PHP, Perl, Python etc. Generally MVC works like this:
Request first comes to the controller, controller finds and appropriate view and interacts with model, model interacts with your database and send the response to controller then controller based on the response give the output parameter to view.
Your Model is the data structure that your program uses.
The View is the part that interacts with the screen or the next level up.
The Controller generally processes data between the model and view
MVC structures are often nested, so a "Model" or "View" may contain its own MVC (Think of a component on the screen. You may just fill it with a string, but behind the scenes the code of the component draws its own little view, has it's own little model (the string you pass in) and has a little controller drawing the data onto the view.
In Rails, the roles of the model, view and controller are well-defined by the framework, any tutorial will point out the three components as it walks you through the files it created.
In other systems, those pieces may be harder to identify. Also, MVC is not "Perfect", just keep in mind that there are valid alternatives, but it's a good way to start organizing.
The Model View Controller principle divides the work of an application into 3 separate but closely cooperative subsystems.
Model (ActiveRecord ):
It maintains the relationship between the objects and the database and handles validation, association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
View ( ActionView ):
It is a presentation of data in a particular format, triggered by a controller's decision to present the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate with AJAX technology.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.
Controller ( ActionController ):
The facility within the application that directs traffic, on the one hand, querying the models for specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).
Check the links below for clear understanding of mvc in rails:
http://www.bogotobogo.com/RubyOnRails/RubyOnRails_Model_View_Controller_MVC.php
https://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
I think the best way to wrap your head around MVC is by example. Try coding up a simple Rails app using MVC. There are many tutorials online, such as the blog example at "Getting Started with Rails".
If chose to learn by coding an example, check out the answers to Where can I find clear examples of MVC?
MVC isn't specifically just for Ruby on Rails. It was actually created awhile before Ruby on Rails ever came around. It's mainly just a way of organizing your code so that you have some code that's responsible for your models (the Class version of a database table), some code that's responsible for your views (what's visually being displayed to the user) and code that's responsible for your controllers (what ties the views to the models and performs the bulk of your logic.
That's the non-framework-specific description. Each framework that uses MVC has a different way of implementing it. For Ruby on Rails each model represents a database table as a class that can communicate directly in code with other objects without needing to write any SQL. All the SQL is being taken care of in the background and you just have to think of it as though it were a normal class (well almost, it's not seamless yet). The view is mostly HTML and represents what will be sent to the browser. The controller is just the code that communicates the models and views together.
All in all, MVC isn't specific just to Ruby on Rails...that's just the most popular.
Ruby on Rails does not implement the MVC design pattern. Ruby on Rails has folders called controllers, models, and views. The views folder has HTML files. The controllers and models folder have ruby files. The controllers map to a URL and a method in the controller gets executed upon requesting that URL, the associated view (HTML file) gets loaded and the model (data structure) for it is used to populate the view. Thats the extent of it's likeness to the MVC design pattern. It's a shame that people say it's MVC because it's caused a generation of confusion and misunderstanding of the MVC design pattern.
In Rails, the model is a data structure.
Here's a brief overview at a high level on how the MVC Pattern works:
Controller:
Listens on some kind of interaction/event stream.
Controller can send the model that type of interaction/event.
Controller can also communicate with the the view.
Model:
Models will listen in on the interaction/event from the controller.
Is an abstraction of a data source.
Handles data logic and manipulation.
After it is done with logic, it then sends to controller which will then communicate with the view.
View:
View can communicate with the controller.
Knows how to render data from the Model to the browser visually.
The Controller tells to View to do something with something from the
Model.
A couple of things to note is that models can't communicate with views directly and vise versa. Only the controller can communicate with the view and model, so the controller acts as the delegator for the interaction/event retrieved from users interaction on the browser.
check this link for more clear understanding
one more link to get clear

What's the difference between a ViewModel and Controller?

What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond
The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.
The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.
The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!
I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations
Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.
Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.
MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.

Resources