When is the controller needed?

Asked

Viewed 2,379 times

13

I rarely use MVC for the simple fact that me it seems that each person uses their way, I know that the MVC came before the web, while reading these links I had a feeling that it seems that one person’s understanding is not the same as another for the use of the MVC:

The second link mentions that Controllers are not mandatory and they should only be used in actions (user actions). If I understood what he said the View is directly responsible for delivering the data to the customer (visually speaking) and it communicates with the Model directly too (without interference from the Controller), whereas the Controller communicates with the Model only when there is user action and is not responsible for delivering anything (it seems that this point is the majority’s agreement).

Popular frameworks that use MVC (try to use?!?)

Three very popular frameworks are Codeigniter, Laravel and cakephp. Everyone works the Routes using the Controller, example with Laravel:

Routes.php:

<?php
Route::resource('', 'DemoController');

Democontroller.php:

<?php
    class DemoController extends BaseController
    {
        public function index()
        {
            //Chama o views/Demo/index.blade.php
            return View::make('Demo.index', compact('data'));
        }

    ...

Demomodel:

index.blade.php:

<!DOCTYPE HTML>
<html>
<body>
<div id='content'>
Output: {{ $data }}!
</div>
</body>
</html>

The equivalent in cakephp:

use Cake\Routing\Router;

Router::connect('/', ['controller' => 'DemoController', 'action' => 'index']);

and creates the file ctp

The equivalent in the codeigneter:

Routes.php:

$route['default_controller'] = 'DemoController';

controller:

class DemoController extends Controller {
    private $data;

    public function __construct(){
         parent::Controller();
    }

    public function index()
    {
        $this->data['helloworld'] = 'Hello World';
        $this->load->view('Demo', $this->data);
    }
}

Doubt

If me understood, although the Model data does not pass through the Controller yet the Controller is responsible for calling the Model and the View (at least in the frameworks cited), or the Controller calls the View and this calls the Model, anyway the controller is the trigger (if I understand correctly).

In other words, whether you want it on the Web or not, the Controller always goes if make necessary, not only for reasons of routes, but also for the simple reason of anything on a web page present the CRUD meaning (Create, Read, Update, Delete), when opening the home page of a website we are making a READ, no?

So my question is: Frameworks when using controllers are wrong or any HTTP request is considered a action and this would technically be user action (which would require routes to be Controllers)?

Or really nobody uses MVC strictly?

  • Personal opinion, I think that controller in backend is something that tends to cease to exist, since having model that defines rules of access and representation, you only need an interface to deliver in some protocol like REST, Websocket, or non-standard format (which is the only one that benefits from a controller, usually replaceable by a callback on the router). MVC is an interesting separation of responsibilities, but that made sense when we did not use SPA, nowadays adopt it tends to add unnecessary complexity in the backend. Already on the front is another story :)

  • @Gabrielgartz It seems very logical your comment, I searched SPA, but did not find, would SOA (Service Oriented Architecture)?

  • SPA is Single Page Application (where your website behaves like an application, loading date and modules as efficiently as possible and only crossing data to populate the interface and operations that can be done on the client instead of the server)is usually strongly related to a SOA or Saas. But these are another layer of architecture of your application, which can be developed by combining with MVC or other architecture patterns to get the desired results.

  • @Gabrielgartz I analyzed an unpopular framework and its documentation, the mini2, in version 1 it used controllers, but in version 2 it uses only Views and Models combined the functions Anonimas for routes.

  • @Guilhermenascimento very cool this framework, I did not know, I only knew the SLIM for PHP, I think it’s cool that PHP Developers are copying the functional style of Node (and their libs), I find simpler and less verbose than the frameworks that try to copy Java, And to this day PHP has no typed property and using magic methods for this is a terrible solution. But let’s not get away too much of the subject, if you want to have a chat about these issues out of the comments adds me on FB. :)

Show 1 more comment

3 answers

8

All web frameworks I know have Controllers, one way or another.

The role of the Controller

Think about the Controller as responsible for the browsing logic between pages.

For example, it is he who will decide which screen will be displayed after submitting a form, which may be the form itself with a validation error message or another screen with the success message.

Different types of Controllers

A controller is also one that contains the methods executed after some user request.

However, many frameworks, including those that use route schema, use the standard known as Front Controller, which would be a type of Super Controller that receives all requests, does some initial processing and then delegates the effective response to a specific application controller that implements the framework.

Accessing the Model

How to access the Model, whether or not you pass the Controller, the recommended form is exactly like the examples of the question.

Note that View is not accessing the model directly, in order to invoke a query to the database, but is receiving the objects already searched by the controller.

The Controller, knowing which is the user’s request, queries the model, retrieves one or more objects and passes as parameter or through a property map to the View. That is, it is not that the View can not access the model, but it is the Controller who has the necessary data to select which is the appropriate Model.

On the other hand, it would be wrong to implement, for example, a database query or direct call to model query methods from the View, because this would break several principles of a good architecture, such as division of responsibilities (cohesion)Crossing of layers and other).

Different mvcs?

In fact, I don’t see many different implementations of MVC for web.

There are common variations, for example in the way the controller passes information to the Model. Some implementations use hashes, other parameters, other attributes in the controller and so on. Other variations include how to map the Urls and controller methods (naming convention, annotations, routes) and how the Controller defines the View to be displayed.

On the other hand, there are also wrong. As a main example I cite the pages in PHP which, in the same script, contains parameter validation, database access and HTML writing.

Actions and Requests

Most of the time, an Action (Action) is equivalent to a Request in the sense that, after a user action like clicking a link or button, the browser will generate an HTTP request, which will be redirected to the controller method according to the configuration.

Take a look at this other answer talking about MVC frameworks action based.

However, often the term action is associated with frameworks

  • Does this include actions that are not necessarily from the user or is any HTTP request a "user action"? If I understood what you said (The Controller, knowing which is the user’s request, queries the model, retrieves one or more objects and passes as parameter or through a property map to the View), then it seems to me that the second link (mentioned in my question) is quite wrong. Sorry if I didn’t understand something.

  • @Guilhermenascimento I updated the answer with one last topic. From what I saw in the article, my answer is in full agreement, it is not wrong. Maybe what you’re confusing is the use of multiple terms to mean the same thing, or a term to talk about different things. Unfortunately, just reading a lot on the subject to make it easier to understand all this.

  • reading your answer now better, it seems that is right, only one I still have doubt (let me know if you need to formulate a question for this), the Model is responsible for selecting the appropriate View (it seems to me more logical) or does the Controller read the data and forward it to the View before handing it over? I say this because in the drawing Action Based I think the Controller returns the View, but I don’t know if this View came back from the Model or if the Controller checked the data from the Model and selected a suitable View.

  • @Guilhermenascimento The view is always triggered from the controller. In MVC, the Model can be accessed by the View to display the data, but the model never determines which View will be displayed, after all it is precisely the purpose of MVC to separate the data from the presentation.

  • Got it @utluiz, got it, I think the question that caused me confusion in understanding is not how frameworks are "proposed" and not because of Action, but because these frameworks allow a certain "freedom", ie the framework will not limit you if you do not follow the "standard". Could add your comment the answer, in my view is well pertinent to the understanding of the responsibility of the "controller", to which I understood the data of the Model can pass inside the controller, but are not linked :) Grateful.

3

The MVC is related in the organization of your application, the Controller is the intermediate layer between the Model and View. In the example you mentioned is not demonstrating the full potential of the Controller, in the controller you trigger Handlers ("triggers") and run several processes, related to other Models. In an e-commerce site purchase process, when a user finishes a purchase a process is generated: ->generate customer card account, credit card API process ->low in stock; ->sending purchase confirmation email; ->inform the carrier about the order( via email or system); ...

Hence if Controller is needed, it is the one who will start these processes, or start them triggers for these processes.

  • Are you describing the action that triggers a CRUD action (at least that’s what I understood), but did not explain in an action where supposedly there is no user action, where the scenario would be only the customer response and the routes (like the index page). Note that in all PHP frameworks cited, the routes are Controllers and basically they call the Views (and sometimes call the models too), as it would be in this sense?

  • Controller is not necessary when your application is an institutional site, so Laravel allows you to return to the view without using the controller. EX: Route::get('/', Function(){ Return view("site.home"); });

  • EX: Route::get('/', Function(){ Return view("site.home"); });

  • I understand, so is it possible to do a route in Laravel using only Routes, Model and View? So this makes use of Route::resource be wrong out of user actions, right? Codeignter and cakephp have similar functions?

  • I don’t know, I just Laravel, which incidentally an excellent framework.

  • I also agree, Laravel is very elegant compared to others, in fact Laravel is not even a framework, it is a set of frameworks :)

Show 1 more comment

2

A way to see the layers of MVC is as follows::

Imagine your system as a little box.

Visualization as a frontier

The display layer is the part of your system that communicates with the outside world. It’s the edges of the box, the walls. The whole core of your system is hidden inside the box and any interaction with the outside world (can be an interaction with the user through a graphical interface, browser, other systems, other external parts of your system) is managed by its borders. In MVC this layer is called View, or Visualization, because it is usually responsible for presenting data to the user through an interface and for receiving user entries (submission of forms, clicks, any kind of interaction) and translating into a format that your system understands. But it can be much more than that and be used as a layer that knows how to converse with the outside world to your system; the advantage of this approach is that you can design the inner workings of your system the way it is best, leaving the visualization layer (border) with the responsibility of transforming the data leaving your system into other formats (in a web application it could transform your data into an HTML page, or into a JSON that will be sent to another system for integration, etc.) and translates external data (data from forms, other systems) into a format that your system understands. That is, if the format in which you communicate with other units changes you only need that layer to be modified, without the need to move "inside the box".

Controllers as contexts

The data (or interactions) received by the display layer (boundary) is passed to your control layer that decides what to do with them. If you have received the submission of a form from a web page that requires updating of some data on your system the control layer will trigger this operation; if you need to send an email notification to the user after a certain request, this layer will be responsible for this.

It is also responsible for sending back to the border layer the result of these requests, in some format set as default on your system, so that this in turn can give an answer to the external agent who requested the request (an example would be the control layer sending the display layer a list of data for it to render an HTML page in the browser). But note that the control layer should not worry about the format in which this data will be presented in the outside world, this is a boundary responsibility. Your system doesn’t know anything outside the box.

You can think of the control layer as the layer that orchestrates the functioning of the system: it controls the execution flow of things and passes data from one side to the other.

Note that although often some object-oriented frameworks draw their entire control layer as a single object/method, a layer execution stream can (and in many cases must) be broken into several small objects, each with its well-defined responsibility.

Templates as domain entities

Your system models represent your application domain within your system. They represent the data that is manipulated by the interactions triggered by the control layer.

Unlike what is imposed or suggested by many frameworks, your model layer does not need (nor should) to be intrinsically linked to a database. A healthy application development practice is to define your model layer according to application needs and maintain an additional mapping layer between the data model and the storage solution itself (which can be a single relational database, a nosql database, a cache, an external api, or a mix of all). This allows more flexibility in your system and makes changes in storage strategies easier, by decoupling these two functions (data manipulation and storage).

A great feature that better explains this kind of approach in application development is this Uncle Bob’s lecture at the 2011 Ruby Midwest conference. Although he uses some concepts of Ruby as an example I think the content is accessible even to those who do not know the language and very useful regardless of the technology you use to develop applications.

  • I’m starting to find MVC less functional than HMVC in web applications, such as calling more than one controller in a request and sub-controllers, etc. What do you think?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.