MVC: what is it and what does it have to do with the user interface. Creating a controller using the IController interface


Developing an application in accordance with the MVC (Model-View-Controller) design pattern is typical for Java and, in relation to DroidScript, seems incomprehensible and unnecessary. Why complicate things? MVC acquired a halo of complexity and "magic" due to the use of beautiful, but incomprehensible words (concept, model, business logic, pattern) and complex demonstrations in the context of Java when considering it. Everything is much simpler: MVC is one of the design patterns in which additionalcode separation in object-oriented environment.

The central element of the MVC model is the controller - regular application DroidScript, from which the code related to the visual markup and external design of widgets, as well as data and methods for accessing them, is taken out. By data, we are used to understanding information stored in arrays, files, databases. But in the MVC concept, data is understood in the broadest sense of the word - it's everything that is not application code:

  • external data from files and databases - metadata, text, graphics, sounds, music, etc.
  • internal application data - strings with labels on buttons and other controls, text in dialog boxes, style descriptions, constants, programmatically generated graphics, etc.

From the user's point of view, his work with the application has not changed when using MVC: he also clicks on buttons, selects data and how it is displayed. Changes may concern facilities this work. And on the development side, the changes are noticeable: the interaction between data and their display in the MVC concept takes place through the controller and under its control.

Let's start with a simple example of using MVC in a single file application.

Single file implementation of the MVC model

Let's take a simple application.

Function OnStart()( var _lay = app.CreateLayout("linear", "VCenter,FillXY"); var _btnShowVersion = app.CreateButton("Show version", 0.3, 0.1); _btnShowVersion.SetBackColor("#66778976"); _btnShowVersion.SetMargins(0, 0.05, 0, 0); _btnShowVersion.SetOnTouch(function()( _btnShowVersion.SetText("Application Version 1.0"); )); _lay.AddChild(_btnShowVersion); app.AddLayout(_lay); )

At first glance, everything seems good, but suppose that you need to change color scheme applications and display inscriptions in several languages. This will lead to complications, since all the data in the example shown are fixed values ​​(literals). This significantly reduces the flexibility of the code and complicates its debugging and maintenance.

Another drawback is that the data - the labels on the button, the markup - the methods for displaying widgets and the action - the block of code that changes the label on the button when it is clicked are in one block and in one file. That is, to change the inscription, you need to open this file and get access to the entire application code. It's like changing a car wheel requires taking the body of the car apart to gain access to everything inside. For what? In the process of disassembling the body of the car, you can accidentally catch something and bring it to a non-working state. It is also possible in the code: I wanted to replace the name of the line in one place, but the replacement occurred in the entire file, which led to a scattering of errors. Or I just wanted to change the color of the button, but accidentally hooked on the code next to it and the whole application stopped working.

One of the goals of the MVC pattern is precisely to restrict access: first, the module (or block of code) that is the source of the error is determined, and then only access to it is given. Why give access to the electronics and motor of the car if you need to change the wheel?

If development is carried out in one file, then this often happens like this: new functions are placed in place, at the very beginning or end of the code, which eventually leads to their mixing. Add here the mixing of code in the functions themselves, and in a month, even with comments, it will not be easy to figure it all out.

Let's implement the example shown above in the context of MVC. To do this, all code must be divided and grouped in the appropriate blocks. The order of the blocks in the code is not important, but it is better to stick to the logic: the controller needs both data and elements to display them, so it is placed last. At the time of displaying the data, they must exist. So the model block comes first:

  1. Model
  2. Performance
  3. Controller
//+++ model (function()( var _obj = ; //+++ data var _version = "Application version 1.0"; var _titleShowVersion = "Show version"; // --- data
//+++ public methods for accessing data _obj.getVersion = function()( return _version; ) _obj.btnGetTitle = function()( return _titleShowVersion; ) // --- open methods for accessing data window.model = _obj; // open access to the local object ))(); //--- model //+++ view (function ()( var _lay = app.CreateLayout("linear", "VCenter,FillXY"); var _btnShowVersion = app.CreateButton(window.model.btnGetTitle(), 0.3, 0.1); _btnShowVersion.name = "_btnShowVersion"; _btnShowVersion.SetBackColor("#66778976"); _btnShowVersion.SetMargins(0, 0.05, 0, 0); _lay.AddChild(_btnShowVersion); app.AddLayout(_lay);

))(); //--- view //+++ controller (function(p_object)( var _obj = ; // public object search method _obj.findObjectById = function(p_name)( var _objectList = app.GetObjects(); for (var _i in _objectList)( if(_objectList[_i].name == p_name)( return _objectList[ _i]; ) ) return null; ) window.control = _obj; ))(); function OnStart()( var _buttonShowVersion = window.control.findObjectById("_btnShowVersion"); //+++ action _buttonShowVersion.SetOnTouch(function()( this.SetText(window.model.getVersion()); )); / / --- action ) //--- controller

Due to the separation of functions, the application code has increased several times.

Initially, all variables are made private, and only at the end, if necessary, access to them is opened through the global window object, which makes it possible to do without global variables.

The example implements a widget lookup like in Java, but you can do it easier and make your code more efficient by making the object available through the global associative array:

Window.controls = ;
window.controls.buttonShowVersion = _btnShowVersion;

Data, its display and reaction to actions are in different blocks, without mixing with each other, which makes it easier for the developer to work with them. The easier it is to work with data and code, the less errors they will have, the easier it is to debug, maintain and scale.

It is not necessary to separate all three of these components from each other. There are several variations of MVC, as well as incomplete implementations of this model. For example, you can separate data and combine action code with controls using anonymous callbacks.

When working in an object-oriented environment, the separation of code and data is already present from the very beginning: data and actions are grouped in classes, objects interact with each other through public methods, and so on. Thanks to MVC, there is a more subtle and explicit separation of code and data according to their main functions.

For a deeper understanding of the advantages of using the MVC model, let's consider splitting the code into separate files.

Three-file implementation of the MVC model

Separation of code by different files used for more convenient operation with him. Great amount the small files you see in MVC projects might cast doubt on that claim, but seeing the files is one thing and working with them is quite another. At each moment in time, the developer interacts with one file from some small set of them. To do this, it is necessary to have a good understanding of the structure of the project organization and constantly monitor top three files- model, view and controller, so as not to accidentally edit third party code. Due to the limitations of the DroidScript editor, this grouping is possible only by filenames in the root directory, for example:

myproject_model.js - model
myproject_view.js - view
myproject_control.js - controller

Below is an example of splitting the code of the previous example into files.

myproject_model.js - model(function()( var _obj = ; //+++ data var _version = "Application version 1.0"; //--- data //+++ string resource var _titleShowVersion = "Show version"; //+++ string resource _obj.getVersion = function()( return _version; ) _obj.btnGetTitle = function()( return _titleShowVersion; ) window.model = _obj; ))(); myproject_view.js - view(function ()( var _lay = app.CreateLayout("linear", "VCenter,FillXY"); var _btnShowVersion = app.CreateButton(window.model.btnGetTitle(), 0.3, 0.1); _btnShowVersion.name = "_btnShowVersion" ; _btnShowVersion.SetBackColor("#66778976"); _btnShowVersion.SetMargins(0, 0.05, 0, 0); _lay.AddChild(_btnShowVersion); app.AddLayout(_lay); ))(); myproject_control.js - controller app.LoadScript("myproject_model.js"); app.LoadScript("myproject_view.js");(function(p_object)( var _obj = ; // object search method _obj.findObjectById = function(p_name)( var _objectList = app.GetObjects(); for (var _i in _objectList)( if(_objectList[_i].name = = p_name)( return _objectList[ _i]; ) ) return null; ) window.control = _obj; ))(); function OnStart()( var _buttonShowVersion = window.control.findObjectById("_btnShowVersion"); //+++ action _buttonShowVersion.SetOnTouch(function()( this.SetText(window.model.getVersion()); )); / / --- action )

Such a simple division of code into files was not easy. To do this, a connection with the model was previously established through the public property of the global root object - window.model, and communication with the view through the global array _map through the method app.GetObjects.

The advantage of separating the code into files is that it is now possible to replace the code with a whole block, for example, for quick start project to implement simple model, and then replace the file with another more functional one, but with the same name and interface. This approach is used, for example, when repairing equipment. If earlier the repair consisted in a slow and painstaking search and replacement of failed radio components, now standard blocks are being replaced. The cost of repairing a complex board is significantly higher than its quick replacement.

From what has been said, it follows that a well-designed interface can significantly simplify the subsequent integration of modules.

AT JavaScript objects passed by reference. Changing the properties of a widget in the controller will change the properties most widget. Theoretically, it is possible to separate view objects from code objects, as is done in Java, where xml structures are used as the first, but this does not make much sense for two reasons - the absence in DroidScript visual editor interface and a limited set of available properties of API objects.

Multi-file implementation of the MVC model

Depending on the tasks and complexity of the project, the detail of the separation of code and data, in the general case, may be different. You can additionally separate user data from resources, you can refine resources by type, group actions, etc. But, the DroidScript editor does not allow you to work fully using MVC.

Model-View-Controller (MVC, "Model-View-Controller", "Model-View-Controller") - a scheme for dividing application data, user interface and control logic into three individual components: model, view and controller - so that each component can be modified independently.

Encyclopedic YouTube

  • 1 / 5

    The concept of MVC was described by Trygve Reenskaug in 1978, who worked at the Xerox PARC research center on the Smalltalk programming language. Later, Steve Burbeck implemented the pattern in Smalltalk-80.

    Subsequently, the design pattern began to evolve. For example, a hierarchical version of HMVC was introduced; MVA, MVVM.

    After implementation by Apple WebObjects technology implemented in Objective-C began to popularize the pattern on the web [ ] .

    When WebObjects was ported to Java, the pattern became popular there as well. More recent frameworks like Spring (October 2002) still have an MVC implementation [ ] .

    A further round of popularity was brought by the development of frameworks focused on fast deployment, on Python languages and Ruby, Django and Rails, respectively [ ] . At the moment of 2017, frameworks with MVC have taken a prominent position in relation to other frameworks without this pattern.

    Template concept description differences

    With the development of object-oriented programming and the concept of design patterns, a number of modifications of the MVC concept were created, which, when implemented by different authors, may differ from the original. So, for example, Erian Vermi in 2004 described an example of a generalized MVC.

    In the preface to Richard Pawson's dissertation "Naked objects", Trygve Reenskaug mentions his unpublished most early version MVC, according to which:

    • The model referred to the "mind" of the user;
    • View was meant to be an editor that allows the user to view and update information;
    • The controller was a tool for linking views together and was used by the user to solve his problems.

    Purpose

    The main purpose of applying this concept is to separate the business logic ( models) from its visualization ( representation, kind). Due to this separation, the possibility of reusing the code increases. This concept is most useful when the user needs to see the same data at the same time in different contexts and/or from different points of view. In particular, the following tasks are performed:

    1. To one models you can add several species without affecting the implementation models. For example, some data may be presented simultaneously as a spreadsheet, a bar chart, and a pie chart;
    2. Without affecting the implementation species, you can change the reactions to user actions (clicking on a button, entering data) - for this, it is enough to use another controller;
    3. A number of developers specialize in only one of the areas: either developing a graphical interface, or developing business logic. Therefore, it is possible to ensure that programmers involved in the development of business logic ( models), will not be aware at all of what performance will be used.

    Concept

    The MVC concept allows you to separate the model, view and controller into three separate components:

    Model

    The model provides data and methods for working with them: queries to the database, checking for correctness. The model does not depend on the view - does not know how to render data - and the controller - does not have user interaction points - just providing access to the data and managing it.

    The model is built in such a way as to respond to requests by changing its state, and the notification of "observers" can be built in.

    The model, due to independence from the visual representation, can have several different representations for one "model".

    Performance

    The view is responsible for getting the required data from the model and sending it to the user. View does not process user input [ ] .

    The view can affect the state of the model by telling the model about it.

    Controller

    The controller provides "links" between the user and the system. Controls and directs data from the user to the system and vice versa. Uses a model and a view to implement the desired action.

    Functionality and discrepancies

    Since MVC does not have a strict implementation, it can be implemented in different ways. There is no generally accepted definition of where the business logic should be located. It can be in both the controller and the model. In the latter case, the model will contain all business objects with all data and functions.

    Some frameworks rigidly specify where the business logic should be located, others do not have such rules.

    It is also not specified where the validation of user-entered data should be located. Simple validations can even occur in a view, but they are more common in a controller or model.

    The internationalization and formatting of data also lacks clear guidance on location.

    Conditionally Mandatory Modifications

    To implement the "Model-View-Controller" schema, enough big number design patterns (depending on the complexity of the architectural solution), the main of which are “observer”, “strategy”, “linker”:

    The most typical implementation is in which the view is separated from the model by establishing an interaction protocol between them using the “event apparatus” (notation "events" certain situations that arise during the execution of the program - and sending notifications about them to all those who subscribed to receive): with each special change in the internal data in the model (denoted as an “event”), it notifies those views that depend on it, which are subscribed to receive such a notification - and the view is updated. This is how the "observer" pattern is used;

    When processing the user's reaction - the view selects, depending on the reaction, the desired controller, which will provide one or another connection with the model. This uses the "strategy" pattern, or may be modified using the "team" pattern instead;

    For the possibility of the same type of handling of sub-objects of a complex-composite hierarchical type, the “linker” template can be used. In addition, other design patterns can be used, such as the “factory method”, which will allow you to set the default controller type for the corresponding view.

    Most Common Mistakes

    Novice programmers very often interpret architectural MVC model as a passive MVC model: the model acts solely as a set of functions for accessing data, and the controller contains the business logic. As a result, the code of the models is in fact a means of obtaining data from the DBMS, and the controller is a typical module filled with business logic (see "script" in web programming terminology). As a result of this understanding - MVC developers began to write code that Pádraic Brady (known in community circles "Zend Framework") described as "TTUK" ("Fat Stupid Ugly Controllers"; Fat Stupid Ugly Controllers):

    The average TTUK was getting data from the database (using a database abstraction layer, pretending to be a model) or manipulating, validating, writing, and also passing the data to the View. This approach has become very popular because the use of such controllers is similar to the classic practice of using a separate php file for each page of the application.

    But in object-oriented programming, an active MVC model is used, where the model is not only a collection of data access code and

    The concept of MVC (Model-View-Controller: Model-View-Controller) is very often mentioned in the world of web programming in last years. Everyone who is in any way connected with the development of web applications, one way or another, has come across this acronym. Today we will understand what the MVC concept is and why it has become popular.

    ancient history

    MVC is not a design pattern, it is a design pattern that describes the way our application is structured, the responsibilities and the interaction of each of the parts in this structure.

    It was first described in 1979, of course, for a different environment. Then there was no concept of a web application. Tim Berners Lee (Tim Berners Lee) sowed the seeds world wide Web (WWW) in the early nineties and changed the world forever. The template we use today is an adaptation original template to web development.

    The frenzied popularity of this framework in web applications has developed due to its inclusion in two development environments that have become very popular: Struts and Ruby on Rails. These two development environments charted the paths for hundreds of production environments created later.

    MVC for web applications

    The idea behind the MVC design pattern is very simple: you need to clearly separate the responsibility for different functioning in our applications:

    The application is divided into three main components, each of which is responsible for various tasks. Let's take a look at the components in detail with an example.

    Controller

    Controller manages user requests (received as HTTP GET or POST requests when the user clicks on interface elements to perform various activities). Its main function is to call and coordinate the necessary resources and objects needed to perform user-defined actions. Typically the controller calls the appropriate model for the task and selects suitable look.

    Model

    Model is the data and rules that are used to work with the data that represent the application management concept. In any application, the entire structure is modeled as data that is processed in a certain way. What is a user for an application - a message or a book? Only data that must be processed according to the rules (the date cannot be in the future, the e-mail must be in a specific format, the name cannot be longer than X characters, and so on).

    The model gives the controller a representation of the data that the user has requested (message, book page, photo album, etc.). The data model will be the same no matter how we want to present it to the user. Therefore, we choose any available view to display the data.

    The model contains the most important part the logic of our application, the logic that solves the problem we are dealing with (forum, shop, bank, etc.). The controller contains mostly organizational logic for the application itself (much like housekeeping).

    View

    View provides various ways representations of the data that is obtained from the model. It can be a template that is filled with data. There can be several different kinds, and the controller chooses which one fits the best way for the current situation.

    A web application usually consists of a set of controllers, models, and views. A controller can be set up as a master controller that receives all requests and calls other controllers to perform actions depending on the situation.

    Let's take an example

    Suppose we need to develop an online bookstore. The user can perform the following actions: view books, register, buy, add items to the current order, create or delete books (if he is an administrator). Let's see what happens when the user clicks on a category fantasy to view the titles of books that are available in our store.

    We have a specific controller to handle all actions related to books (view, edit, create, and so on). Let's call it books_controller.php in our example. Also we need a model, for example, book_model.php An that handles the data and logic associated with the store item. Finally, we need several views to represent the data, such as a list of books, an edit page, and so on.

    The following figure shows how a user's request to view a list of related books is handled. fantasy:

    The controller (books_controller.php) receives the user's request ( HTTP request GET or POST). We can set up a central controller like index.php that receives the request and calls books_controller.php.

    The controller checks the request and parameters and then calls the model(book_model.php), inquiring she has a list of available books on the topic fantasy .

    The model gets the data from the database (or from another source that stores information), applies the filters and necessary logic, and then returns the data that represents the list of books.

    The controller uses the appropriate view to present data to the user. If the request comes from mobile phone, the mobile phone view is used; if the user uses a certain interface design, then the appropriate view is selected, and so on.

    What are the benefits?

    Most obvious advantage, which we get from using the MVC concept is a clear separation of presentation logic (user interface) and application logic.

    Support for various types of users who use different types devices is common problem our days. The interface provided should be different if the request comes from a PC or a mobile phone. The model returns the same data, the only difference is that the controller selects different kinds to output data.

    In addition to isolating views from application logic, the concept of MVC greatly reduces the complexity big applications. The code is much more structured, making it easier to maintain, test, and reuse solutions.

    Why use a workbench?

    When you use a workbench, the basic MVC structure is already in place, and all you have to do is extend the structure by placing your files in the appropriate directories to match the MVC pattern. In addition, you will have a set of functions that are already written and well tested.

    Let's take cakePHP as an example working environment MVC. After installation, you will have three main directories:

    • cake/
    • vendors/

    Folder app is the location of your files. This is the place to develop your part of the application.

    In folder cake hosts cakePHP files (workbench functionality).

    Folder vendors serves to store PHP libraries third party developers.

    Your workspace (app directory) has the following structure:

    • app/
      • config/
      • controllers/
      • locale/
      • models/
      • plugins/
      • tests/
      • vendors/
      • views/
      • webroot/

    You need to place your controllers in a directory controllers, models in directory models and views in the directory views!

    As soon as you start using the workbench, it becomes immediately clear where almost any part of your application that needs to be created or modified is located. This organization in itself greatly simplifies the process of developing and maintaining an application.

    Using the workspace for our example

    Since this lesson is not intended to show how to create an application with cakePHP, we will only show the code for the model, controller, and view, with comments on the benefits of using the MVC workbench. The code is deliberately simplified and unsuitable for use in a real application.

    Remember, we were considering a bookstore and a curious user who wanted to see full list related books fantasy. The controller received the user's request and coordinated the necessary actions.

    So, as soon as the user clicks the button, the browser requests the given url:

    www.ourstore.com/books/list/fantasy

    CakePHP template URL formatting /controller/action/param1/param2, where action is a function that is called by the controller. In the old classical form url will look like this:

    www.ourstore.com/books_controller.php?action=list&category=fantasy

    Controller

    In the cakePHP workspace, our controller will look like this:

    class BooksController extends AppController(

    Function list($category) (

    $this->set("books", $this->Book->findAllByCategory($category));

    function add() ( ... ... )

    Function delete() ( ... ... )

    ... ... } ?>

    Simple, right?. This controller will be saved as books_controller.php and placed in /app/controllers. It contains a list of functions that perform the actions for our example, as well as other functions for performing book-related operations (add a new book, delete a book, and so on).

    The working environment provides us with many ready-made solutions and we only need to create a list of books. There is a base class that already defines the basic functionality of the controller, so you need to inherit the properties and functions of this class ( AppController is the heir Controller).

    All you need to do in the action list is call the model to get the data and then select the view to present it to the user. Here's how it's done.

    this->Book is our model, and part of the code:

    $this->Book->findAllByCategory($category)

    tells the model to return a list of books on the selected topic (we'll look at the model later).

    Method set in line:

    $this->set("books", $this->Book->findAllByCategory($category));

    The controller passes data to the view. Variable books takes the data returned by the model and makes it available to the view.

    The only thing left to do now is to display the view, but this function is done automatically in cakePHP if we use the default view. If we want to use a different view, then we must explicitly call the method render.

    Model

    The model is even simpler:

    class Book extends AppModel(

    Why is it empty? Because it inherits from a base class that provides the required functionality, and we need to use CakePHP's naming convention in order for the workbench to do all other tasks automatically. For example, cakePHP is known from its name that this model used in BooksController, and that it has access to a database table named books.

    With this definition, we will have a model that can only read, delete, or store data in the database.

    Save the code as book.php in folder /app/models.

    View

    All we need to do now is create a view (by at least, one) for the action list. The view will have HTML code and a few (as few as possible) lines of PHP code to loop through the array of books provided by the model.












    Name Author Price

    As you can see, the view does not create a full page, but only a fragment of HTML (a table in this case). Because CakePHP provides another way to define a page template, and the view is inserted into that template. The workbench also provides us with some helper objects to perform common tasks while creating parts. HTML pages(insert forms, links, Ajax or JavaScript).

    Save the view as list.ctp(list is the action name and ctp means CakePHP template) in the folder /app/views/books(because it's a view for a controller action).

    This is how all three components are executed using the CakePHP workbench!

    MVC Principle in web programming (Model - View - Controller, Model - View (View) - Controller) - one of the most successful ideas to date. MVC principle intuitive at first glance, but not very easy to deepen. First, let's look at what it is intended for.

    MVC principle, allows you to separate the implementation of the application logic, appearance (GUI, GUI) and user interaction.

    This leads to more structured code, allows more specialized people to work on the project, makes the code easier to maintain, makes it more logical and understandable. A change in one of the components has minimal impact on the others. Can be connected to one model different types, different controllers.

    On the other hand, this requires greater performance of the executing machines, but in recent times it is not big problem- Increasingly complex programming solutions require support, and the cost of support will far exceed the cost of more powerful modern hardware.

    MVC principle used by almost all modern frameworks.

    Let's take a closer look at the components.

    Model(Model) - contains the so-called. "business logic" - data processing and verification, database access, represents internal organization systems. The model should not directly interact with the user.

    view(View, View) describes the appearance of the application.

    Controller- a link between the model and the view, receives data from the user, passes it to the model, receives the processed result and passes it to the view.

    The relationship can be seen in the diagram:

    Image source: http://www.wikipedia.org Component requirements:

    Models:

    • must contain properties that represent specific data;
    • should include business logic (for example, validation rules) to ensure that the data meets the requirements;
    • may contain code for working with data.
    Representation:
    • should primarily contain markup such as HTML, and simple php code used to crawl, format, and display data;
    • should not access the database directly. Models should do this;
    • should not directly access $_GET , $_POST and other variables obtained from the user's request. This task must be performed by the controller. Views should only be used to style data received from the controller and model;
    • can directly access the properties and methods of the controller or models. However, this should only be done for data display purposes.
    Controllers:
    • can access $_GET , $_POST and others PHP variables, obtained from the user's request;
    • can create and manipulate model instances. For example, in a typical model update action, the controller might first instantiate the model, then populate it with the data from $_POST, and if the model was successfully saved, redirect the user's browser to the page of the created model. It's worth noting that saving the model itself must be implemented in the model class, not in the controller;
    • must not contain SQL queries. They are best kept in models;
    • must not contain HTML or other markup. It deserves to be put on display.
    (Requirements borrowed from here: http://yiiframework.ru/doc/guide/ru/basics.best-practices)

    In addition to the MVC concept, there are many others, for example MOVE( M clothes, O operations, V iews and E vents) - sort of like an evolution MVC(taken from here: http://habrahabr.ru/post/147038/), but these concepts are less common.

    Design Pattern Model-View-Controller (MVC) is a software architecture pattern built around keeping the representation of data separate from the methods that interact with the data.

    Although the MVC scheme was originally designed for personal computers, it has been adapted and is widely used by web developers due to the precise delineation of tasks and the ability to reuse code. The scheme encourages the development of modular systems, which allows developers to quickly update, add or remove functionality.

    In this article, I will describe the basic principles, as well as look at the definition of a build scheme and a simple MVC PHP example.

    What is MVC

    The design pattern is named after its three main parts: Model, View, and Controller. The visual representation of the MVC pattern looks like shown in the chart below:

    The figure shows the structure of a one-way data flow and its path between various components, as well as their interaction.

    Model

    A model is a persistent store of data used throughout the structure. It should provide access to data for viewing, selecting or recording. AT overall structure The Model is the bridge between the View and Controller components.

    At the same time, the Model has no connection or information about what happens to the data when it is passed to the View or Controller components. The only task of the "Model" is to process data in persistent storage, search and prepare data transmitted to other components of MVC.

    "Model" Should act as a "gatekeeper", Standing near the data warehouse and not asking questions, but accepting all incoming requests. This is often the most complex part of an MVC system. The Model component is the top of the entire structure, since without it communication between the Controller and View is impossible.

    Performance

    The view is the part of the system in which the data requested from the "Model" is given the final form of their output. In MVC-based web applications, "View" is a component in which HTML code is generated and displayed.

    The view also intercepts the user's action, which is then passed to the "Controller". A typical example of this is the button generated by View. When the user clicks it, the action in the "Controller" is triggered.

    There are several common misconceptions about the View component. For example, many people mistakenly believe that " View"has no connection with" Model", And all the displayed data is transferred from" Controller». In reality, such a data flow scheme does not take into account the theory behind the MVC architecture. In his article, Fabio Chevasco describes this incorrect approach using the example of one of the non-traditional MVC PHP frameworks:

    “In order to properly apply the MVC architecture, there should be no interaction between the “Model” and the “View”: all logic is handled by the “Controller”.

    In addition, the definition of "View" as a template file is also inaccurate. But this is not the fault of one person, but the result of many mistakes by various developers that lead to a common misconception. Then they incorrectly explain it to others. In fact, "View" is much more than just a template. But modern MVC-oriented frameworks have absorbed this approach to such an extent that no one cares whether the correct MVC structure is supported or not.

    The View component is never given data directly by the Controller. There is no direct connection between “ View" and " Controller" - they are connected using " Model».

    Controller

    Its task is to process the data that the user enters and update the Model. This is the only part of the schema that requires user interaction.

    "Controller" can be defined as a collector of information, which is then transferred to the "Model" with subsequent organization for storage. It does not contain any other logic other than the need to collect incoming data. "Controller" Also connects to only one "View" and one "Model". This creates a one-way data flow system with one input and one output at the data exchange points.

    The "Controller" receives tasks to execute only when the user interacts with the "View", and each function depends on the user's interaction with the "View". The most common mistake developers make is that they confuse "Controller" with a gateway, so they assign functions and tasks to it that belong to the "View".

    Also a common mistake is to endow the Controller with functions that are only responsible for processing and transferring data from the Model to the View. But according to the structure of the MVC pattern, this interaction should be carried out between the "Model" and "View".

    MVC in PHP

    Let's write a web application in PHP, the architecture of which is based on MVC. Let's start with an example wireframe:

    string = "MVC + PHP = Awesome!"; ) )controller = $controller; $this->model = $model; ) public function output()( return "

    " . $this->model->string . "

    "; } } model = $model; ) )

    We have a project with several main classes for each part of the template. Now you need to configure the relationship between them:

    output();

    In the PHP MVC example above, there is no specific functionality for the controller because the user interactions are not defined in the application. The view contains all the functionality, as our example is for demonstration purposes only.

    Let's expand on the example to show how we'll add controller functionality, thereby adding interactions to the application:

    string = "MVC + PHP = Awesome, click here!"; ) )controller = $controller; $this->model = $model; ) public function output() ( return "

    model->string . "

    "; } } model = $model; ) public function clicked() ( $this->model->string = “Updated Data, thanks to MVC and PHP!”; ) )

    We have expanded the program with basic functionality. Setting up interactions between components now looks like this:

    ($_GET["action"])(); ) echo $view->output();







2022 gtavrl.ru.