When is the controller necessary?

10

I've rarely used MVC just because me seem like every person uses his own way, I know that MVC came before the web, by reading these links I had a feeling that it seems that understanding one person is not the same as another for the use of MVC:

The second link mentions that Controllers are not mandatory and should only be used in actions (user actions). If I understand what he said View is the direct responsible for delivering the data to the client (visually speaking) and he communicates with the Model directly as well (without Controller interference), since the Controller communicates with the Model only when there is action of the user and is not responsible for delivering anything (it seems that this point is majority agreement).

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

Three popular frameworks are CodeIgniter, Laravel, and CakePHP. All work 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 cakePHP equivalent:

use Cake\Routing\Router;

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

and creates the file ctp

The codeigneter equivalent:

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);
    }
}

A doubt

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

In other words, whether or not in the Web, the Controller will always need to do so, not only because of routes, but also because of the simple reason that anything on a web page has the meaning CRUD (Create, Read, Update, Delete), when opening the homepage of a site we are doing a READ, right?

So my question is: Are frameworks using Controllers wrong, or is any HTTP request considered a action and this would technically be user action (which would force the routes to be Controllers)?

Or does anyone really use MVC strictly?

    
asked by anonymous 30.04.2015 / 19:29

3 answers

6

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

The role of the Controller

Think of the Controller as responsible for navigational logic between pages.

For example, it will decide which screen to display after submitting a form, which can be the form itself with a validation error message or another screen with the message of success.

Different Types of Controllers

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

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

Accessing the Model

As for the access mode to Model , whether or not it passes through the Controller, the recommended way is just like the examples of the question.

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

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

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

Different MVCs?

In fact, I do not see many different implementations of MVC for the web.

There are common variations, for example in how 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 you map the URLs and methods of the drivers (naming conventions, annotations, routes), and how the Controller defines the View to display.

On the other hand, there are also wrong implementations . As a main example I mention the PHP pages that, in the same script, contain parameter validation, bank access and HTML writing.

Actions and Requisitions

Most often, an Action is equivalent to a Request in the sense that, after a user action such as 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 by talking about MVC frameworks action based .

However, the term action is often associated with frameworks

    
30.04.2015 / 20:21
1

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

If you need the Controller, it is the one who will start these processes, or initiate triggers for those processes.

    
30.04.2015 / 20:16
1

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

Imagine your system as a box.

Display as border

The visualization layer is the part of your system that communicates with the outside world. They are the edges of the box, the walls. All the core of your system is hidden inside the box and any interaction with the outside world (may 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 Preview , as it is usually responsible for presenting data to the user through an interface and receiving user input form submissions, clicks, any kind of interaction) and translate to a format that your system understands. But it can be much more than that and be used as a layer that knows how to talk to the outside world to your system; the advantage of this approach is that you can draw the inner workings of your system the way that is best, leaving the view layer (border) with the responsibility to transform the data coming out of your system to other formats (a web application it could transform your data into an HTML page, or a JSON that will be sent to the other system for integration, etc.) and translate 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 there being any need to move "inside the box".

Controllers as contexts

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

It is also responsible for sending the result of these requests back into the boundary layer, in some format defined as standard on your system, so that the system can respond to the external agent requesting the request (a example would be the control layer send a list of data to the view layer so that it renders an HTML page in the browser). But note that the control layer should not worry about the format in which such data will be presented in the outside world, this is a border responsibility. Your system knows nothing that is out of the box.

You can think of the control layer as the layer that orchestrates the workings of the system: it controls the flow of execution of things and passes data back and forth.

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

Models as domain entities

The models in your system are the representation of your application domain within your system. They represent the data that is manipulated by interactions triggered by the control layer.

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

A great feature that best explains this type of approach in application development is this lecture by Uncle Bob in Ruby Midwest Conference 2011 . Although he uses some Ruby concepts 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.

    
01.05.2015 / 08:22
___ ___ erkimt How the semantic / indexing with AngularJS? ______ qstntxt ___

I always wonder, AngularJS is a framework that is constantly being used.

But I have a question about how it works for crawlers (example googlebot).

Do they even run the javascript and interpret the code to get the information and show the site developed on the platform?

  

With the angular HTML theoretically does not have information "yet", it is first necessary to trigger the controllers and such.

The question is: How does semantics / indexing work with Angular?

    
______ azszpr71758 ___

According to this post , Google's crawler renders pages that have Javascript and browse the listed states.

Interesting parts of the post (free translation):

  

[...] we decided to try to interpret pages by running JavaScript. It's hard to do this on a grand scale, but we decided it was worth it. [...] In recent months, our indexing system has been serving a large number of web pages the way a regular user would see them with JavaScript enabled.

     

If features such as JavaScript or CSS in separate files are blocked (say with %code% ) so that Googlebot can not retrieve them, our indexing system will not be able to see your site as a regular user.

     

We recommend allowing Googlebot to retrieve your JavaScript and CSS so that your content can be better indexed.

Recommendations for Ajax / JS can be found at this link .

If you want to serve Angular application content for crawlers that do not support the same kind of functionality, you need to pre-render the content. Services such as Prerender.io are intended for this.

    
______ azszpr71790 ___

Crawlers (example googlebot) use pure text reading, meaning they first validate meta tags, then comments, then they remove all encoding and then read the whole text without code. Reason: Increase processing speed and reduce errors by having fields that hide, or have nodes (nodules) that are removed during execution. Crawlers do not run any kind of technology (Browser), they only read the file. The Angular does not stop being a Javascript like any other, for that reason its elements are ignored. Only items relevant to SEO (Optimization) are brought into question in their indexing.

Part of my explanation you find in this Google article Understanding Web Pages Better

To better understand the process of viewing plain text, make a requestion of the page in question by CURL, Lynx which are technologies commonly used by Crawlers.

For better indexing we recommend creating robots.txt and XML sitemaps .

    
______ azszpr71766 ___

One tip I can give you is, take the course they offer, it's quick and easy, you'll better understand how semantics work:

link

    
___ Vertical text alignment with CSS