What is the controller task in MVC?

I am trying to learn the architecture of MVC. But I can’t understand why a controller is needed. See the code below for my model and view.

model.php connects to the database and receives a message. view.php will just show the message.

model.php

<?php $db = mysql_connect("somehostname", "someuser", constant("somepassword")); mysql_select_db("somedatabase", $db); $result = mysql_query("SELECT post FROM posts WHERE postid='" . $_POST['id'] . "'"); $row = mysql_fetch_array($result); $post = $row["post"]; mysql_close($db); ?> 

view.php

 <?php require "model.php"; echo $post; ?> 

I set the location of my browser http: //whateverhost/view.php? Id = 5

This loads the message with identifier 5. I do not need a controller here. So I'm confused, why do you need a controller?

Note. Please explain with reference to the example above. I am not a programmer, and learning something like CakePHP, etc. Amazing for me.

Edit: It would be great if you added controller.php to the above code. This would help me understand the role of the controller and how it communicates with the model and views.

+7
model-view-controller
source share
6 answers

You do not need a controller because your example is trivial. Example from a real-case scenario:

Suppose you have a CAD application. The CAD application is organized as an MVC. You have:

  • A view that is responsible for drawing the current model and providing interactive objects.
  • a model that stores current data
  • a controller whose role is to get events from the view and convert them into appropriate objects in order to change the model.

For example, a user clicks on a square and deletes it. The controller will receive an event from the view, create an object representing the command (via the command template), add it to the queue for the possibility of cancellation, and execute the command. Then the team will change the model, but the responsibility for translating the viewing events into a complex technique that modifies the model is under the control of the controller.

Of course, you could say, why then the representation of Command objects is not created? well, nobody forbids you, but in the end you will have presentation logic mixed with operational logic. This goes against a good design, although for the most trivial occasions you can live with this design. For example, if your CAD application allows you to display a list of objects both as 3D representations and as a list of entities, and you can remove them from both, you clearly see that either both represent the same logic for processing ( bad design), or they just send the same message to a common controller (good design, MVC).

+12
source share

MMO ...

MVC is a very general design pattern that does not necessarily say what is good and what is bad. There is a model, view and controller. The responsibilities of each of these things depend on the taste of MVC, and the taste of MVC that you choose should depend on the complexity of your project. For example, if you have a domain-driven project, then the examples given by others here will not work very well.

So, in the database itself:

Model: an object that has data that will be displayed in the view. Whether this is a DTO or a domain model is not really defined here, but I will share my thoughts about it in a second.

View: this is what the user sees and how the user interacts. Any code or logic here should directly support the view. In other words, the ZERO business logic, the ZERO data access logic, ZERO knows anything other than what the user physically sees. Either a web form, a desktop window form, or activity (mobile), etc.

Controller: Probably the most ambiguous piece of this puzzle. One thing is certain, it acts as an intermediary between the representation and the “model”, and also decides what happens next or, rather, “controls” the flow. But it’s important not to get too detailed with this description. That this thing really depends on your understanding of MVC. Therefore, I will describe how I look at it in a web context; but basically, just draw a line between flow control of the service and the actual execution of the service.

MVC, for me, is not another way to describe the N-level, as some people may require. There are no layers in MVC, since MVC is actually in your view layer . Each MVC element actually lives in the presentation layer, and the MVC pattern simply says that you should separate the problems between getting the data and displaying it:

  • Model: what the data looks like. It’s actually just a structure that a view will use to retrieve its data.
  • View: Actually displaying it
  • Controller: determining where to get data for the model or even the model itself.

If you can accept this statement, then this should help clarify that the model is valid in this context. The model is NOT a data access object, and the model is NOT a domain model, because none of these things should be in your view layer. So this leaves us with either a ViewModel (MVVM) or a DTO. I'm going to go with the DTO for the sake of simplicity.

So, if we adopted the DTO as the type of model we are talking about when we say “model” in MVC, then where do we get it? If the controller should not bother with data access, then where? How about your level of service? Your service layer contains everything “how” to your application. This is the "Do stuff" layer. Therefore, if your view wants to create a user, it will collect data and pass it to the controller. The controller decides which services to call to complete the task and sends a request with the necessary data. The level of service meets the DTO. This DTO can either be used directly or added to another model (if, for example, there were several services called).

Important points:

  • The controller does not know anything about your domain (if you have one), it only knows about your available services and how to call them.
  • Absolutely no business logic is executed by the controller. For example, if you need to send a greeting letter as part of a CreateUser operation that will not be initiated by the controller, as this is technically a business rule. It will be processed between your service and domains.
  • In my opinion, your controller should not perform any data access. This should be delegated to the service level. Many tutorials, as a rule, show that the controller interacts with repositories, which, I think, are beautiful, because the abstraction, but the direct access to the data should be absolute, nowhere at the presentation level.

Again, this is in a web context. If you work with MVC in an Android app, you may not have a service level or domain. Perhaps you will interact with another breed of objects. Personally, I always use service levels or applications and for several reasons that may or may not be considered valuable to others.

So, in MVC.Net, the controller is more like an API; Presentation and API are two different presentation media designed for collaboration (the internal controller represents the data, the external controller builds models with this data and acts as an intermediary with the presentation). In Angular, the controller is more like what we are talking about here. It seems layers are layers of layers. This confuses conceptualization a bit, but the concept never goes beyond the level of presentation.

But to summarize: The controller “controls” the operations and data coming in and out of your system, into and out of the view, but actually does not do business . The details of this process depend heavily on your design philosophy for the project.

N-Level MVC

So here, in this diagram, I have grouped concepts to show MVC at the N-level in a typical monolithic application. The connection is performed from left to right and does not skip to any other layer (see: "Onion architecture"). At the presentation level, the controller knows about the model and presentation, but the presentation and model know nothing for the most part. However, in many versions of MVC, including ASP.Net and MVVM, the view may know about the model interface or prototype (but not the model instance) so that it can bind to it.

The controller will handle manipulations with the model (or view model in this context), which means that it may need to know about domain objects and domain services. You can optionally add an application layer between the presentation layer and the domain if you want to use a reusable application (for example, your application can have several chapters: web API and desktop application and mobile application, etc.) to provide a transactional boundary and further isolation. It is important that the view does not have any knowledge / dependencies on domain objects in this architecture - why there is a separate model for the view. The point of the model in MVC is to create a model for presentation. That is, it is a model specifically designed to serve a view, not a domain. This is normal for a view model for transferring / adapting a domain model if it has never been published and / or accidentally serialized.

On the other hand, the "presentation level" in the web API, in my opinion, is a serialized contract (for example, JSON or XML). Therefore, treat this accordingly.

+3
source share

I think that in this case there may be a use for the controller, and it is bad to show the code for it.

MODEL:

 <?php $db = mysql_connect("somehostname", "someuser", constant("somepassword")); mysql_select_db("somedatabase", $db); $result = mysql_query("SELECT post FROM posts WHERE postid='" . $_POST['id'] . "'"); $row = mysql_fetch_array($result); $post = $row["post"]; mysql_close($db); function getPost() { return $post; } ?> 

VIEW:

 <html> <head></head> <body> <input type="submit" onClick="postToScreen();" value="Post"> <p id="post"></p> </body> </html> 

CONTROLLER:

 <?php $controllerPost = getPost(); ?> <script type="text/javascript"> function postToScreen() { document.getElementById("post").innerHTML="<?php echo $controllerPost; ?>"; } </script> 

my javascript is rusty. I think I got this code correctly, but id double-checking it before embedding it in anything. the controller controls how the view looks, and under certain circumstances, what data this model contains.

+2
source share

model.php is , in this case you have a controller.

The roles of the model, view, and controller are not easy to distinguish unless you have a good MVC structure (simple PHP is not good).

A model is your data structure that becomes constant in the database. In terms of code, if it mainly consists of a data structure as a class.

Only data is displayed in the view. Mostly html with some script tags.

The controller controls what happens. For example, a user edits a message. The data is received by the controller, maybe a little changed (timestamp added, ip users) and the model was sent to save it. The controller then decides which view to display next, and what data is retrieved for the new view.

A small example.

+1
source share

IMHO in the MVC controller has two main goals :

  • testability of the GUI logic or something that runs the GUI. In most cases, you can write unit tests for a controller relatively easily, much more difficult for graphical interfaces, for example, for PHP or Windows Forms. The first depends on the browser, and later depends on Windows messages, and this does not make your life easier when writing unit tests. This is almost the same with any other presentation-level technology.
  • interchangeability of the presentation level or (in some cases) the controller. There are scenarios in which you can use the same controller in two graphical interfaces ("light" form for a special case and a "rich" form for another case) or vice versa (not so often).

In a scenario with much more functionality than in your example, you will see the benefits. But you have to decide for or against MVC and use the same approach in all forms of your application without mixing it. I would prefer MVC, you almost always need controller logic.

0
source share

I will try to answer only the question in the title. So what is the role of the controller in MVC?

This should be a model format for viewing the format translator so as not to have a UI-driven model and database structure based on UI.

The idea is to develop a database structure based on business logic, and then develop an independent user interface. Now that we add or move some UI control, our model and database structure should not change.

0
source share

All Articles