Understanding the MVC Template

I'm having trouble understanding the MVC pattern. I understand that we are trying to separate the GUI from the business logic, although I am having trouble understanding how.

From what I understood, View is what the user sees. So this is usually a window / form. Controller is between the View and Model . The controller will transmit "stream" data in both directions. It will also be saved if necessary (if I have a wizard with 5 steps, this is answered by the Controller to make sure they are done in the correct order, etc.). Model, is where the core of my application logic lives.

Is this opinion correct?

To try to turn this into something more meaningful, I will try to outline a simple WinForms example (without ASP.NET or WPF, please!) In a java crowd, from what I understood, Swing works similarly to WinForms!) To find out Will I do it right, and I will raise questions that I always come to by doing this.




Suppose I have a model containing only a class (just to make it easier). I know that this will make this example stupid, but all the more simple):

 class MyNumbers { private IList<int> listOfNumbers = new List<int> { 1, 3, 5, 7, 9 }; public IList<int> GetNumbers() { return new ReadOnlyCollection<int>(listOfNumbers); } } 

Now it's time to make my Controller :

 class Controller { private MyNumbers myNumbers = new MyNumbers(); public IList<int> GetNumbers() { return myNumbers.GetNumbers(); } } 

View should have only ListBox which has as elements all numbers received in MyNumbers .

Now the first question arises:

Should the Controller be responsible for creating MyNumbers ? In this simple case, I find it acceptable (as MyNumbers will do the same, regardless of whether it has an associated state). But let's say that I would like to use for all different controllers my application has the same instance of MyNumbers . I would have to pass this Controller (and everyone else who needs it) this instance of MyNumbers , which I want to use. Who will be responsible for this? In WinForms examples, will it be View ? Or will it be the class that creates the View ?

Justification of the question: what is the procedure for creating these three parts? What is the code that the "owner" of MVC called to create it? Should the Controller create both a View and a Model ? Should View create an instance of Controller and Controller Model ?

Second question:

What should the main method look like if I want my application to have a Use Case this Portraits Controller ?

Third:

Why is there an arrow to Model in the following MVC View diagram? Should the Controller always be a bridge between View and Model ?

alt text




I will have one or two more questions, but they will probably be more clear if I understand this first detail. Or maybe, after I understand this first question, everyone else is separated.

Thank!

+42
java c # model-view-controller winforms
Jul 22 2018-10-22T00:
source share
10 answers

The easiest way to get an MVC descriptor is to use it in a framework that enforces it.

  • The model interacts with the data source (DB or any other) and gives you access to your data.
  • The view interacts with the outside world, it receives input from somewhere and transfers data to the controller, it also listens to the controller to make sure that it displays the correct data.
  • The controller is where all the magic happens; the controller manages data, pushes events and processes changes in both directions (to / from the view and to / from the model).

This diagram is very useful (it makes much more sense than Wikipedia): MVC diagram http://java.sun.com/developer/technicalArticles/javase/mvc/images/Figure4.gif

Source and great MVC article!

+25
Jul 22 '10 at 14:25
source share

As for the criticism in my post, I thought I would post a post about how I tend to create an MVC pattern in PHP

In PHP, I put the framework in several sections, because some of them are normal when it comes to MVC.

Primaries:

  • controller
  • Model
  • View

Secondaries - ModelLayer

  • ViewLoader
  • Library
  • ErrorLayer

Inside the controller, I usually allow everyone access to the secondary layers, and View and Model from Primary.

This is how I structured it

 |---------| |------------| |------------| | Browser | ----> | Controller | ----> | Model | |---------| |------------| |------------| | | | | | | |----------------| | | | |------------| -------------| View | |------------| 

From my diagram, usually bypass the View <-> Model connection and execute the Controller <-> Model , and then the link from the Controller <-> View assigns the data.

In my framework, I try to create an object storage system so that I can easily retrieve objects, etc. An example of my object store looks like this:

 class Registry { static $storage = array(); public static function get($key) { return isset(self::storage[$key]) ? self::storage[$key] : null; } public static function set($key,$object) { self::"storage[$key] = $object; } } 

Somewhat more advanced than the path, so when I initialize the objects for the first time, I store them as Registry::set("View",new View()); to always be available.

So, in my controller, witch is the base controller, I create some magic methods __get() __set() , so that any class that extends the controller, I can easily return the request, for example:

 abstract class Controller { public function __get($key) { //check to make sure key is ok for item such as View,Library etc return Registry::get($key); //Object / Null } } 

And user controller

 class Controller_index extends Controller { public function index() { $this->View->assign("key","value"); // Exucutes a method in the View class } } 

The model will also be placed in the registry, but only allowed to be called from ModelLayer

 class Model_index extends ModelLayer_MySql { } 

or

 class Model_index extends ModelLayer_MySqli { } 

or file system

 class Model_file extends ModelLayer_FileSystem { } 

so that each class can be specific to the type of storage.

This is not a traditional type of MVC pattern, but it can be called Adoptive MVC.

Other objects, such as View Loader, should not be placed in the registry, as they are not specifically intended for users, but are used by other objects, such as View

 abstract class ViewLoader { function __construct($file,$data) //send the file and data { //Include the file and set the data to a local variable } public function MakeUri() { return Registry::get('URITools')->CreateURIByArgs(func_get_args()); } } 

since the template file is included in the View loader, and not the View class, it separates user methods from system methods, and also allows you to use methods in the views themselves for general logic.

An example template file.

 <html> <body> <?php $this->_include("another_tpl_file.php"); ?> <?php if(isset($this->session->admin)):?> <a href="<?php echo $this->MakeUri("user","admin","panel","id",$this->session->admin_uid) ?>"><?php echo $this->lang->admin->admin_link ?></a> <?php endif; ?> </body> </html> 

I hope my examples will help you understand this a little more.

+3
Jul 22 2018-10-22T00:
source share

The answer to the third question :

When the model changes, it notifies the view, then the view receives data from the model using its getters.

+2
Jul 22 '10 at 14:23
source share

"From what I understand, the" view "is what the user sees. Thus, it is usually a window / form. The controller is between the view and the model. The controller will" process "data in both directions. Also keep the state when this is necessary (if I have a wizard with 5 steps, this answers the Controller to make sure they are done in the correct order, etc.). The model is where the core of my application logic lives. "

This is almost correct. The controller does not save data. It calls a service that stores data. The reason is that saved data is never just a call to save. You might want to perform data validation checks to make sure that it is normal according to the needs of your business. You might want to do some authentication to make sure that the data can be stored by the user. If you do this in a service, then you have a good set of functions that you can use again and again, say, for webapp and web service. If you do this in a controller, say, for a web application, when you go to write your web service, you will have to reorganize and / or duplicate the code.

In response to your comment, β€œI'm not sure I fully understood your question. Does the controller control user interface input, or is it the model that does this?”

The controller should control only those paths that are performed by business functionality. This is it. Controllers should be the easiest piece of code to write. You can do some validation on gui (i.e., View, for example, correctly formatting email addresses, text inputs do not exceed the maximums), but the business layer should also confirm the input - for the reason I mentioned earlier, that when you start to stand more endpoints, you don’t need to refactor.

+1
Jul 22 2018-10-22T00:
source share

This is from Java, but hopefully it helps.

For the main:

 public static void main(String[] args) { MyNumbers myNums = new MyNumbers(); // Create your Model // Create controller, send in Model reference. Controller controller = new Controller(myNums); } 

Your controller needs a link to your model. In this case, the controller actually creates all the Swing components. For C #, you can leave the form initialization here, but View / Form needs a link to Model (myNums) and Controller (controller). Hope some C # people can help on this front. A view must also be recorded as a model observer (see Observer Pattern).

Here is the constructor that I have (adjusted for your case):

 public NumberView(Controller controller, MyNumbers myNums) { this.controller = controller; // You'll need a local variable for this this.myNums = myNums; //You'll need a local variable for this myNums.registerObserver(this); // This is where it registers itself } 

The view transfers the work to the Controller for processing user actions (buttons, anything). The controller decides what needs to be called / done in the model. In general, the model then does something and changes its state (maybe there are more numbers on your list). Howbeit). In this case, the Model will let its Observers know that it has changed and updated. Then View opens and receives new data and updates itself. That is why the discussion of the model and presentation (your third question).

So the model will have:

 public void notifyObservers() { for (Observer o: observers) { o.update(); // this will call the View update below since it is an Observer } } 

So in the view you will have something like this:

 public void update() { setListBox(myNums.getNumbers()); // Or whatever form update you want } 

Hope this helps. I know this is Java, but the concept still applies. You will need to read a little Observer sample to get it completely. Good luck

+1
Jul 22 '10 at 14:27
source share

Should the Controller be responsible for creating MyNumbers?

I would say "definitely not."

If the MVC pattern is designed to decouple elements M, V, and C, how can this work if C just creates an instance of M using new MyNumbers() ?

In Java, we will use something like the Spring Framework here. You need a way to express the relationship of dependencies, or rather the details of its execution, in the configuration file or in another suitable place (i.e. Not in compiled code).

But there is another element to this problem: you probably should not define the variable myNumbers (inside C) with the specific type of runtime that you are going to use. Use an interface or abstract class and leave it open as to what the actual type of runtime is. So in the future you can reimplement the IMyNumbers interface to meet the new requirements (the ones you don't know today), and your C component will continue to work fine, not one wiser.

+1
Jul 22 '10 at 14:29
source share

Why does the View have an arrow to the model in the following MVC diagram? Should the controller always be a bridge between View and Model?

This is the MVC 2 model. You can usually see it in a Java application where CONTROL runs a business, also processes data from / to MODEL and selects which VIEW to display back to the client. When rendering to the client, VIEW will use the data from the MODEL:

alt text http://www.blogjava.net/images/blogjava_net/marco/7342/o_2.JPG

The following is an example of accessing data from a JSP file (VIEW), which is bean (MODEL):

 class Person {String name;} // MODEL My name is ${bean.name} // VIEW 
+1
Jul 22 '10 at 14:45
source share

I will try to answer this with a relatively less technical stand on what is worth. I will try to pass a general example.

Controller controls what view used. So, let's say if you write to a page, the Controller direct you to the input view (say), and if you read the same page, it will direct you to its success view (say).

After writing to the page, the Controller will pass these parameters to the appropriate model , where the logic related to what should be done with them is located. If there is an error, then the Controller direct you to the error view .

My knowledge is based on my one-month experience with Agavi. Hope this helps.

+1
Jul 22 '10 at 15:13
source share
  • View draws a model and presents it to the user
  • The controller processes the user input and converts it into modifications into a model.
  • The model contains data and modification logic.

It makes no sense to translate it into code. In any case, you will not get it correctly.

0
Jul 22 '10 at 14:46
source share

View

  • user interface / responsible with input output / some validation / should have a way to notify the outside world about user interface level events

  • only knows about the model

Model

  • data structure / represents data that is presented / should not contain business logic (perhaps only some validation of data / structure)
  • knows only about himself (think of the Person class, which has only a name and age)

Controller

  • He is responsible for business logic / he breaks down the views and glues the corresponding models to them / should be able to respond to event viewing / access to other layers of the application (persistence / external services / business layers, etc.)

  • knows everything (at least View and model) and is responsible for gluing everything together

0
Jul 22 '10 at 15:33
source share



All Articles