What's the controller in MVC pattern and why does it exist? - model-view-controller

While working with Unity, I realized that separating Model and View would make my code more readable and straightforward. Constructing the whole model, all I had to do is just create some UI and bind it to Model.
But I still don't understand what 'Controller' is, and why does it exist. I don't think I had trouble when I directly bound View to Model, not through Controller.
So the question is if we can bind View to Model directly, why do we need Controller? What's the benefit of having Controller between Model and View?

At the highest level the Controller is the link between the View (displaying the UI/UX) and the Model (creating and managing your database and its tables).
True, it is possible to write code without any Controller usage but your Views will quickly get very cluttered and each file will be full of logic that is much more nicely stored somewhere else hint hint.
The Controller (and Model and some other places such as helpers) is thus the perfect place to sort out all the back-end code so that all you need to do is send a single field or object to your View to display.
An example is somewhat painful because by its nature the Controller is where you go to sort out your code as things get more complicated but this is a great article to get you on the right track! HTH
https://www.toptal.com/unity-unity3d/unity-with-mvc-how-to-level-up-your-game-development

I don't have years of experience, but in my understanding controllers provide a bridge across view and models. While view contain the pretty part and models contain useful parts the controller do the calls of functions passing values from database to view or inputs to model. That provide a way to avoid lots of injection like class A calling class B, calling class C, etc.
You can put rule business in controllers or in view, but thats not the expected in MVC architecture. The first important thing (for me) in software programming is readability, whats MVC provide.
if you've interest, search for other architectures like MVVM, to compare then.

Related

What is the advantage of Model-View-Controller (MVC) over Model-View?

Could anyone give an example of why it would be advantageous to use MVC instead of a simpler Model and a View only.
Note: whether it's called MVC or MVP (Model-View-Presenter), I'm talking about the one where the View receives input, then the Controller will respond to the input event by interpreting the input into some action to be done by the Model. When the model changes, the View will update itself by responding to events from the model.
What is disadvantageous of simply letting the Model respond to events in the View and vice versa?
In MVC, if I changed the model in a way that affects the controller then I'll have to do changes in the controller. In Model-View, if I change the Model, I'll have to update the view.
So, it seems like we are introducing complexity by adding the "controller" part?
In MVC, the Model is blind to its environment, the view can be too - passing off (blindly) its events to the controller, which knows more about the view and model. So when all is said and done, the controller is the 'non-reusable' disposable part of the system, since it is the most context aware component.
if I changed the model in a way that affects the controller...
The the model should expose simple CRUD methods in such a way that those using the methods do not have to know anything about the passed update object, nor what really happens inside the model.
This means that the view, IMO, has to do a bit of work by creating the passed record, since Controllers are supposed to be stateless and the view is more persistent. Controllers get triggered and 'kick-in' do their work with a passed object and do not have a state.
The passed data is created by some sort of generic convention.
Let me go even further. Suppose you have a view, a tablegrid, and a control whose enabled property is dependent on item is selected in the grid -- you COULD create a view that handles both those controls and this logic internally, and that would probably be the way to go in such a simplified example.
But the more atomic your views are, the more reusable they become, so you create a view for every, yes every, control. Now you are looking at a situation where views have to know about each other in order to register themselves for the right notification...
This is where the controller steps in, since we want to stick all these dependencies onto him, the long term disposable one. So the controller manages this type of view-to-view notification scheme.
Now your views are ignorant as they can be and independent, thus reusable.
You can code a view without having to know about the system, or the 'business logic' as they like to call it. You can code a model without having to know too much about your goals (though it does help to tweak the model to enable it to return the datasets you have in mind).... but controllers, they are last and you have to have the previous two firmed up before you can wire things together.
Here is another thing to think about -- just as the Model is supposed to abstract-away and provide a generic interface to the underlying implementation of the data it is managing (the client does not know if the data comes from a DB, a file, a program setting, etc) -- the view should also abstract away the control it is using.
So, ultimately this means a view should not (caveat below) have functions/properties that look like this:
public property BackgroundColor{get;set}
Nor
public function ScrollBy(x,y){}
But instead:
public SetProp(string name, object val){}
And
public DoCmd(string name, object val){}
This is a bit contrived, and remember I said ultimately... and you ask why is this a good idea?
With reusability in mind, consider that you may one day want to port things from WinForms to, say, Flex, or simple want to use a new-fangled control library that may not expose the same abilities.
I say 'port' here, but that is really not the goal, we are not concerned with porting THIS particular app, but having the underlying MVC elements generic enough to be carried across to a new flavor -- internally, leaving a consistent and ability-independent external interface intact.
If you didn't do this, then when your new flavor comes along, all your hard references to view properties in the (potentially reusable/refactorable/extendable) controllers have to be mucked with.
This is not to mean that such generic setters and cmds have to be the interface for all your views abilities, but rather they should handle 'edge case' properties as well as the normal props/cmds you can expose in the traditional hard-link way. Think of it as an 'extended properties' handler.
That way, (contrived again), suppose you are building on a framework where your buttons no longer have buttonIcon property. Thats cool because you had the foresight to create a button view interface where buttonIcon is an extended property, and inside the view your conditional code does a no-op now when it receives the set/get.
In summary, I am trying to say that the coding goals of MVC should be to give the Model and View generic interfaces to their underlying components, so when you are coding a Controller you don't have to think to hard about who you are controlling. And while the Controllers are being (seemingly unfairly) set up to be the sacrificial lamb in the long run of re-usability -- this does not mean ALL your controllers are destined for death.
They are hopefully small, since a lot of their 'thinking' has been shoved off into semi-intelligent Models and Views and other controllers (ex: Controller to Sort a Grid or Manipulate a TreeView) -- so being small they can be easily looked at and qualified for reuse in your next project -- or cloned and tweaked to become suitable.
It actually reduces complexity by separating the workflow logic from the domain logic. It also makes it easier to write unit tests and makes your application easier to maintain and extend.
Imagine if you wanted to add a new data type. With the approach above, you would probably duplicate a lot of the workflow logic in the new class as it would be likely to be tightly coupled to the domain logic.
The discipline involved in separating the workflow logic into the controller makes it more likely that you will have fewer dependencies between workflow and domain logic. Adding a new data type would then be more simple, you create the new domain object and see how much of the controller you can reuse, e.g. by inherited from a controller super class.
It would also make it easier to change frameworks in future - the model would probably not change too much and so would be more portable.
Having said that, you might want to look into MVVM depending on what you are using as your presentation layer: Benefits of MVVM over MVC
Advantages of MVC/P (I am talking about Supervising Controller here) over MV include:
You can handle complex data binding code in the controller, if required.
You can test that complex presentation logic without a UI testing framework.
You can also have a graphic designer make your views, and not see your code, and not mess up your code when they fix your views.

Is Model-Glue's model in Coldfusion the same as the model in other MVC frameworks?

If you follow the quickstart guide provided by the official Model-Glue docs, found here:
http://docs.model-glue.com/wiki/QuickStart/2%3AModellingourApplication#Quickstart2:ModelingourApplication
It will seem like the "model" is a class that performs an application operation. In this example, they created a Translator class that will translate a phrase into Pig Latin. It's easy to infer from here that the program logic should also be "models", such as database operation classes and HTML helpers.
However, I recently received an answer for a question I asked here about MVC:
Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?
In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view, and the view uses it as a strongly-typed object to render the data. This means that, for the Model-Glue example provided above, there should've been a translator controller, a translator view, a PigLatinTranslator class, and a Translation model that looks like this:
component Translation
{
var TranslatedPhrase = "";
}
This controller will use it like this:
component TranslatorController
{
public function Translate(string phrase)
{
var translator = new PigLatinTranslator();
var translation = new Translation();
translation.TranslatedPhrase = translator.Translate(phrase);
event.setValue("translation", translation);
}
}
And the view will render it like this:
<p>Your translated phrase was: #event.getValue("translation").TranslatedPhrase#</p>
In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view.
My question is, is ColdFusion Model-Glue's model different than a MVC model? Or is the quickstart guide they provided a poor example of MVC, and the code I listed above the correct way of doing it? Or am I completely off course on all of this?
I think perhaps you're getting bogged down in the specifics of implementation.
My understanding of (general) MVC is as follows:
some work is needing to be done
the controller defines how that work is done, and how it is presented
the controller [does something] that ultimately invokes model processing to take place
the model processes handle all data processing: getting data from [somewhere], applying business logic, then putting the results [somewhere]
the controller then [does something] that ultimately invokes view processing to take place, and avails the view processing system of the data from the model
the view processes grab the data they're expecting and presents that data some how.
That's purposely very abstract.
I think the example in the MG docs implement this appropriately, although the example is pretty contrived. The controller calls the model which processes the data (an input is converted into an output), and then sets the result. The controller then calls the view which takes the data and displays it.
I disagree with the premise of this question "Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?" The view should not care where the data comes from, it should just know what data it needs, and grab it from [somewhere]. There does need to be a convention in the system somewhere that the model puts the data to be used somewhere, and the view gets the data it needs from somewhere (otherwise how would it possibly work?); the decoupling is that model just puts the data where it's been told, and the view just gets the data out from where it's been told. The controller (or the convention of the MVC system in use) dictates how that is implemented. I don't think MG is breaking any principles of MVC in the way it handles this.
As far as this statement goes "In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view." Well... yeah... all a model IS is some code. So PigLatinTranslator.cfc models the business logic here.
And this one: "In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view"... I don't think that is correct. The controller just wrangles which models and which views need to be called to fulfil the requirement, and possible interchanges data between them (although this could be done by convention, too). The controller doesn't do data processing; it decides which data processing needs to be done.
Lastly, I don't think the "strongly-typed" commentary is relevant or an apporpriate consideration in a CF environment because CF is not strongly typed. That is a platform-specific consideration, and nothing to do with MVC principles.
I think one of the common confusions around MVC is that there are multiple Views, multiple Controllers but only one Model. cfWheels has a "model" object for each persistent domain object which I think is very confusing - but of course cfWheels is drawn from Ruby on Rails which also uses "model" in that context.
In general, in MVC, "The Model" represents your business data and logic as a whole. The Model is made up of a number of domain objects (which are typically persistent) and a number of service objects (which exist to orchestrate operations across multiple domain objects). In real world applications, you typically have a data layer that manages persistence of domain objects - which may be partitioned in a number of ways.
It may also help to think of the input data that the view needs as it's "API" and it is the controller's job to satisfy that API by providing compatible data. Think of it more that the controller needs to know what type of data will satisfy the view rather than the other way around.

In MVC, why should the model notify the views, and why should the view have the model?

In my world, the model notifies only the controllers subscribed to the model's event. Then the controller tells the view what to do, for example adding a new row to a list.
The same with the view: the view notifies the controller subscribed to the view's event. Then the controller modifies the model as needed, for example setting the name of a person, and call the Save() method on the model.
Okay, I know I'm wrong, I don't think every article about MVC is wrong because I'm thinking in another way. The point in MVC is to seperate the UI from the data model. How does this come true when the view and the model reach each other? Why should they do so?
Thanks for Your answer!
Model-View-Controller is seen different ways by many people, but I like to think of it as a combination of several other patterns rather than as a single pattern. This may come originally from this note
The connection of the view to the model is an Observer Pattern, with the model notifying the view when it has changed. There's no need for the controller to be involved in this.
I completely agree with you on this one.
For every project i work on, i try to enforce this:
View --> Controller --> Model
So that every action or event in the view call a specific controller method. This controller method will do his job (validate, call other service, etc) then if persistence is needed, it will the call the associated ModelService to persist the data.
in my world, a view component should never call a ModelService without going thru a controller.
But that's just me ;-) (and almost 100% of the good architect and designers i worked with)
I like to think of the model as a transparent thing, adhering to some sort of scheme. Very easy to "read" by a view. I never make my views programmatic, in the sense that you can call all sorts of methods on it. Usually my view is HTML, my model has methods but is also capable of presenting itself as a plain data structure, and there is an intermediate: in the form of a template engine.
But, there are lots of variants for MVC. I don't think there are 2 developers who would exactly, exactly, agree on what MVC actually is. MVC is -in my view - a pattern to help you. It is not a law that is trying to hold your creativity back by exactly defining up to the last bit what you have to do.

Why is MVC so popular?

I was originally going to make this a longer question, but I feel like the shorter I make it, the better you'll understand what I mean.
The MVC architectural pattern has 3 dependencies. The View depends on the model. The Controller depends on the View and Model. The Model is independent.
The Layers architectural pattern defines N - 1 dependencies, where N is the number of Layers.
Given three Layers: Model, View, and Controller, there are only 2 dependencies, as opposed to 3 with traditional MVC. The structure looks like this:
View ---> Controller ---> Model
[View depends on Controller, Controller depends on Model]
It seems to me that this style accomplishes the same goals and produces looser coupling. Why isn't this style more common? Does it truly accomplish the same goals?
Edit: Not ASP.NET MVC, just the pattern.
With regard to griegs's post:
As far as mocking, Layers still allows you to use the Command Processor pattern to simulate button clicks, as well as any other range of events.
UI changes are still very easy, perhaps even easier. In MVC, the Controller and View tend to mesh together. Layers creates a strict separation. Both Layers are black boxes, free to vary independently in implementation.
The Controller has 0 dependencies on the View. The View can be written, and time can still be saved with loose coupling.
Because you decouple the interface from the controller making changes easier.
Also consider the scenario where you need to get started on a project but the artwork won't be ready for weeks or months. Do you wait or do you write all the code required for the pages and simply then wire up the view to the controller.
At least that's what we did and we saved months.
Also it made UI changes easier to cope with because there wasn't any code in our aspx pages that did anything.
Our tests were also better as we could mock up anything including button clicks etc.
And if you're talking about the asp.net-mvc framework, there is no code in the aspx files and no viewstate etc.
In proper MVC the controller doesn't depend on the view afaik. Or maybe I'm not understanding it correctly.
The model defines the data.
The view defines what the output looks like.
And the controller is a translator from a model-understood grammar to view-understood grammar.
So essentially the controller is independent. The view is independent. And the model is independent.
Yes? No?
I'll be bold, and try to explain why your method didn't catch on.
The MVC pattern basically requires the view and model layers to agree on an API.
Since one serves the other and there are no dependencies inside the code it leaves the controller to behave generically, all it needs to do is take a certain structure in the view layer and call the matching API on the model layer.
You'll note that agreeing on an API between the view and model isn't really such a big deal it has to happen anyway. And what you get is good separation between back-end front-end development.
In your proposed solution a lot of development is required on the controller side. The controller will be required to understand all the elements in the view and to map them to the specific calls required on the model layer.
Since the controller is a single access point connecting many views to many models this can quickly get out of hand and end up being an incomprehensible controller module.
Look at some Struts2 examples to see what I mean...
I think I'm understanding your point:
Yes you can make the View only depend on the Controller only by making the Controller transform (using PHP as an example) the Model objects to non-Model objects like simple arrays.
As we already know, performing this transformation can be more effort than it's worth if the decoupling isn't actually needed. If the View uses the Model objects then it has this dependency. However, this can be relieved a bit by having the View depend solely on the Controller for its required input, which can be Model objects.
The Symfony PHP framework promotes this style of skinny controller shuffling between Model and View. You can still directly call upon the Model layer to retrieve objects within the View layer but it's strongly urged against for the coupling issues you bring up. Within the View you can call include_component() which actually goes back up to the Controller if you need to query the Model.
I haven't gotten back to this in a long time, mostly because I was still thinking. I was unsatisfied with the answers I received, they didn't really answer my question.
A professor, recently, did steer me in the right direction. Essentially, he told me this: Layers which separate Model, View, and Controller is MVC. In the vanilla MVC architectural pattern, the dependency between the View to the Model is often not used, and you effectively end up with Layers. The idea is the same, the naming is just poor.
Choosing a presentation pattern for a new or enterprise web development on the Microsoft platform is a daunting task, in my opinion there are only three; View Model, Model-View-Presenter (MVP) or ASP.NET MVC (a Model2 derivative).
You can read the full article here ASP.NET MVC Patterns
I'd like to add some more things. First of all for my point of view is we use the model as container for the information we want to pass and show on the view. Usually the action method into the controller ends with return view("viewName",model).The view itself probabily will change its layour against the model :
on the view :
if(model.something==true) {
%>
somethign to show
<%
}
At this poinf the definition of model is hard to find.
I can say (especially on enterprise conext) the are two "model"
one is the domain model/entity model or how you want to call it that wraps the data coming from the lower layers (database,etc) and the view-model who contain the information we wants to show plus any other information we need to hide/show portion of interface
The controller orchestrate the the views and is indipendent from the view but a bit dipendent from the model:
into the controller
pulic actionResult Index(){
....
if(model.BoolProperty==true){
return ("firstView);
}
else
{
return ("secondView");
}
}
I hope it makes sense
In my opinion ,you'd better try it in your programme , you can use ruby on rails ,or codeigniter( for php ),these great framework may be helpful to your understanding the MVC.

MVC: Structuring Feed Output

The framework I'm using on my project follows the MVC Pattern. I"M building JSON feeds and need to structure them in a different way then what the system gives me by default from the ORM. Where should I be handling the task of mangling and shaping my data that I'll serve up, in the model, view or controller?
Right now I'm doing it in my controller, then passing that data to the view. I can see this fitting better under the Model or the View but not sure which one.
If this different structure is only relevant to the view, you should keep it in the view.
If this structure is used in more than one view, make a Helper for it.
Internally your app should standardize on one data format, so models should always return a standardized format. If you were to do something with that data in your controller, you'd need to change the logic for interacting with the data just in that one controller function, which in this case doesn't make much sense. If you later decide to change the format in the model, you'd also need to change code in the controller that interacts with it. Don't create dependencies when there's no advantage to do so.
I'd write a model method to do it if I were you. Having it in the controller will make your controller fat, which is bad, and means you can't call that functionality from other controller actions or anywhere else. Although it could be considered presentation logic, I prefer to keep my views really simple with just conditionals and iterators at most. There may be an argument for having it in a helper, but I'd still stick with the model.

Resources