Create a mvc engine from scratch. MVC: what it is and how it relates to the user interface. Styling Thanks View

      Many begin to write a project to work with a single task, not implying that it can grow into a multi-user management system, well, let's say, content or God forbid, production. And everything seems cool and cool, everything works until you begin to understand that the code that is written consists entirely of crutches and hardcode. The code is mixed with layout, queries and crutches, sometimes even unreadable. There is an urgent problem: when adding new features, you have to mess with this code for a very long time, remembering “what was written there that was?” and curse yourself in the past.

You might even have heard about design patterns and even leafed through these beautiful books:

  • E. Gamma, R. Helm, R. Johnson, J. Vlissides “Objective design techniques. Design Patterns ”;
  • M. Fowler "Architecture of corporate software applications."
  And many, not afraid of the huge manuals and documentation, tried to study any of the modern frameworks and faced with the difficulty of understanding (due to the presence of many architectural concepts artfully linked together) postponed the study and application of modern tools in a "long box".

This article will be useful primarily for beginners. In any case, I hope that in a couple of hours you can get an idea of \u200b\u200bthe implementation of the MVC pattern that underlies all modern web frameworks, as well as get “food” for further thought on how to do it. At the end of the article is a selection of useful links that will also help you figure out what web frameworks (other than MVC) consist of and how they work.

Hard-core PHP programmers are unlikely to find anything new for themselves in this article, but their comments and comments on the main text would be very helpful! Because without theory, practice is impossible, and without practice, theory is useless, then first there will be a little theory, and then we will move on to practice. If you are already familiar with the concept of MVC, you can skip the theory section and go straight to practice.

1. Theory

The MVC pattern describes a simple way to build an application structure, the purpose of which is to separate business logic from the user interface. As a result, the application is easier to scale, test, maintain, and of course is implemented.

Consider the conceptual scheme of the MVC template (in my opinion, this is the most successful scheme I've seen):

In MVC architecture, a model provides data and business logic rules, a view is responsible for the user interface, and a controller provides interaction between the model and the view.

A typical sequence of an MVC application can be described as follows:

  1. When a user enters a web resource, the initialization script creates an instance of the application and launches it for execution.
      This displays a view, say the main page of the site.
  2. The application receives a request from the user and determines the requested controller and action. In the case of the main page, the default action is performed ( index).
  3. The application creates an instance of the controller and launches the action method,
      which, for example, contains model calls that read information from the database.
  4. After that, the action forms a view with data obtained from the model and displays the result to the user.
Model   - contains the business logic of the application and includes methods of selection (these can be ORM methods), processing (for example, validation rules) and the provision of specific data, which often makes it very thick, which is quite normal.
  The model should not directly interact with the user. All variables related to the user request must be processed in the controller.
  The model should not generate HTML or other display code, which may vary depending on the needs of the user. Such code should be processed in views.
  The same model, for example: the user authentication model can be used both in the user and in the administrative part of the application. In this case, you can take the general code into a separate class and inherit from it by defining application-specific methods in the heirs.

View   - used to specify the external display of data received from the controller and model.
  Views contain HTML markup and small PHP code inserts for crawling, formatting, and displaying data.
  Should not directly access the database. This should be done by the model.
  Should not work with data obtained from a user request. This task must be performed by the controller.
It can directly access the properties and methods of the controller or models to obtain data ready for output.
  Views are usually divided into a common template containing markup common to all pages (for example, a header and footer) and parts of the template that are used to display data output from the model or display data entry forms.

Controller   - a connecting link connecting models, views and other components into a working application. The controller is responsible for processing user requests. The controller must not contain SQL queries. They are best kept in models. The controller should not contain HTML or other markup. It should be put into species.
  In a well-designed MVC application, controllers are usually very thin and contain only a few dozen lines of code. Well, you can't say about Stupid Fat Controllers (SFC) in Joomla CMS. The logic of the controller is quite typical and most of it is carried out in the base classes.
  The models, on the contrary, are very thick and contain most of the code related to data processing, because The data structure and business logic contained in them is usually quite specific for a particular application.

1.1. Front Controller and Page Controller

  In most cases, the user’s interaction with the web application is carried out by clicking on the links. Look now at the address bar of the browser - you got this text from this link. Other links, for example, to the right of this page, will give you different content. Thus, the link represents a specific command to the web application.

I hope you already managed to notice that different sites may have completely different formats for building the address bar. Each format can display the architecture of a web application. Although this is not always the case, in most cases this is a clear fact.

Consider two options for the address bar, which displays some text and user profile.

The approximate processing code in this case:
  switch ($ _ GET ["action"]) (case "about": require_once ("about.php"); // page "About Us" break; case "contacts": require_once ("contacts.php"); // contact page break; case "feedback": require_once ("feedback.php"); // feedback page break; default: require_once ("page404.php"); // page "404" break;)
  I think almost everyone did this before.

Using the URL routing engine, you can configure the application to receive the following requests to display the same information:
http://www.example.com/contacts/feedback

Here, contacts is a controller, and feedback is a contacts controller method that displays a feedback form, etc. We will return to this issue in the practical part.

It is also worth knowing that the routers of many web frameworks allow you to create arbitrary URL routes (specify what each part of the URL means) and the rules for processing them.
  Now we have enough theoretical knowledge to move on to practice.

2. Practice

  First, create the following file and folder structure:


  Looking ahead, I’ll say that the core classes Model, View and Controller will be stored in the core folder.
  Their descendants will be stored in the directors controllers, models and views. File index.php   This is the point in progress in the app. File bootstrap.php   initiates the download of the application, connecting all the necessary modules, etc.

We will go sequentially; open the index.php file and fill it with the following code:
  ini_set ("display_errors", 1); require_once "application / bootstrap.php";
  Here questions should not arise.

Next, let's go straight to the halyard bootstrap.php:
  require_once "core / model.php"; require_once "core / view.php"; require_once "core / controller.php"; require_once "core / route.php"; Route :: start (); // start the router
  The first three lines will include kernel files that do not yet exist. The last lines include the file with the class of the router and launch it by calling the static start method.

2.1. URL Router Implementation

  For now, let's deviate from the implementation of the MVC pattern and do routing. The first step we need to do is write the following code in .htaccess:
  RewriteEngine On RewriteCond% (REQUEST_FILENAME)! -F RewriteCond% (REQUEST_FILENAME)! -D RewriteRule. * Index.php [L]
  This code will redirect the processing of all pages to index.php, which is what we need. Remember in the first part we talked about Front Controller ?!

We will put the routing in a separate file route.php   to the core directory. In this file, we describe the Route class, which will run the methods of the controllers, which in turn will generate the appearance of the pages.

The contents of the route.php file

class Route (static function start () (// controller and default action $ controller_name \u003d "Main"; $ action_name \u003d "index"; $ routes \u003d explode ("/", $ _SERVER ["REQUEST_URI"]); // get the name of the controller if (! empty ($ routes)) ($ controller_name \u003d $ routes;) // get the name of the action if (! empty ($ routes)) ($ action_name \u003d $ routes;) // add the prefixes $ model_name \u003d " Model _ ". $ Controller_name; $ controller_name \u003d" Controller _ ". $ Controller_name; $ action_name \u003d" action _ ". $ Action_name; // hook the file with the model class (the model file may not exist) $ model_file \u003d strtolower ($ model_name). ".php"; $ model_path \u003d "application / models /".$ model_file; if (file_exists ($ model_path)) (include" application / models /".$ model_file;) // hook the file with the controller class $ controller_file \u003d strtolower ($ control ler_name). ". php"; $ controller_path \u003d "application / controllers /".$ controller_file; if (file_exists ($ controller_path)) (include" application / controllers /".$ controller_file; ) else (/ * it would be right to throw an exception here, but for simplicity we’ll immediately redirect to page 404 * / Route :: ErrorPage404 ();) // create a controller $ controller \u003d new $ controller_name; $ action \u003d $ action_name; if (method_exists ($ controller, $ action)) (// call the controller action $ controller -\u003e $ action ();) else (// it would also be more reasonable to throw an exception Route :: ErrorPage404 ();)) function ErrorPage404 ( ) ($ host \u003d "http: //". $ _ SERVER ["HTTP_HOST"]. "/"; header ("HTTP / 1.1 404 Not Found"); header ("Status: 404 Not Found"); header (" Location: ". $ Host." 404 ");))


  I note that the class implements a very simplified logic (despite the voluminous code) and possibly even has security problems. This was done intentionally, because writing a full-fledged routing class deserves at least a separate article. Consider the main points ...

The $ _SERVER ["REQUEST_URI"] global array element contains the full address to which the user accessed.
  For example: example.ru/contacts/feedback

Using function explode   the address is divided into components. As a result, we get the name of the controller, for the given example, this is the controller contacts   and the name of the action, in our case - feedback.

Next, the model file is connected (the model may be absent) and the controller file, if any, and finally, an instance of the controller is created and the action is called, again, if it was described in the controller class.

Thus, when going, for example, to the address:
example.com/portfolio
  or
example.com/portfolio/index
  the router will do the following:

  1. include the model_portfolio.php file from the models folder containing the Model_Portfolio class;
  2. connect the controller_portfolio.php file from the controllers folder containing the Controller_Portfolio class;
  3. will create an instance of the Controller_Portfolio class and call the default action - action_index, described in it.
  If the user tries to contact the address of a non-existent controller, for example:
example.com/ufo
  then it will be redirected to the "404" page:
example.com/404
  The same thing happens if the user accesses an action that is not described in the controller.

2.2. Back to the MVC implementation

  Go to the core folder and add three more files to the route.php file: model.php, view.php and controller.php


  Let me remind you that they will contain base classes, which we will now begin writing.

File contents model.php
  class Model (public function get_data () ())
  The model class contains the only empty data selection method that will overlap in descendant classes. When we create descendant classes, everything will become clearer.

File contents view.php
  class View (// public $ template_view; // here you can specify the general default view. function generate ($ content_view, $ template_view, $ data \u003d null) (/ * if (is_array ($ data)) (// convert array elements into the variables extract ($ data);) * / include "application / views /".$ template_view;))
  It’s not hard to guess what the method generate   Designed to form a view. The following parameters are passed to it:

  1. $ content_file - views displaying page content;
  2. $ template_file - a common template for all pages;
  3. $ data is an array containing page content elements. Usually populated in a model.
  The include function dynamically connects a common template (view), within which the view will be embedded
  to display the content of a specific page.

In our case, the general template will contain header, menu, sidebar and footer, and the content of the pages will be contained in a separate form. Again, this is done for simplicity.

File contents controller.php
  class Controller (public $ model; public $ view; function __construct () ($ this-\u003e view \u003d new View ();) function action_index () ())
  Method action_index   - this is the default action; we will override it when implementing descendant classes.

2.3. Implementing child classes of Model and Controller, creating View "s

Now the fun begins! Our business card site will consist of the following pages:
  1. home
  2. Services
  3. Portfolio
  4. Contacts
  5. And also - page "404"
  Each page has its own controller from the controllers folder and a view from the views folder. Some pages may use the model or models in the models folder.


  In the previous figure, the file is highlighted separately template_view.php   - This is a template containing common markup for all pages. In the simplest case, it could look like this:
home
  To make the site look presentable, we make up the CSS template and integrate it into our website by changing the structure of HTML markup and connecting CSS and JavaScript files:

  At the end of the article, in the “Result” section, there is a link to the GitHub repository with a project in which steps have been taken to integrate a simple template.

2.3.1. Create a home page

  Let's start with the controller controller_main.php, here is his code:
  class Controller_Main extends Controller (function action_index () ($ this-\u003e view-\u003e generate ("main_view.php", "template_view.php");))
  In method generate   the instance of the View class is passed the names of the files of the general template and view with the content of the page.
  In addition to the index action, the controller, of course, may contain other actions.

We reviewed the file with a general view earlier. Consider a content file main_view.php:

Welcome!

  OLAMOS TEAM - a team of first-class website development experts with many years of experience collecting Mexican masks, bronze and stone statues from India and Ceylon, bas-reliefs and sculptures created by masters of Equatorial Africa five to six centuries ago ...


  It contains simple markup without any PHP calls.
  To display the main page, you can use one of the following addresses:

  An example using a view that displays the data obtained from the model will be discussed later.

2.3.2. Create the Portfolio Page

  In our case, the Portfolio page is the only page using the model.
  A model typically includes data sampling methods, for example:
  1. pgsql or mysql native library methods
  2. methods of libraries that implement data abstraction. For example, PEAR MDB2 library methods;
  3. oRM methods
  4. methods for working with NoSQL;
  5. and etc.
  For simplicity, we will not use SQL queries or ORM statements here. Instead, we emulate real data and immediately return an array of results.
  Model file model_portfolio.php   put in the models folder. Here are its contents:
class Model_Portfolio extends Model (public function get_data () (return array (array ("Year" \u003d\u003e "2012", "Site" \u003d\u003e "http://DunkelBeer.ru", "Description" \u003d\u003e "Dark promo site Dunkel beer from the German manufacturer Löwenbraü produced in Russia by the CAN InBev brewing company. "), array (" Year "\u003d\u003e" 2012 "," Site "\u003d\u003e" http://ZopoMobile.ru "," Description "\u003d\u003e "The Russian-language catalog of Chinese Zopo phones based on Android OS and their accessories."), // todo);))

The model controller class is contained in the file controller_portfolio.php, here is his code:
  class Controller_Portfolio extends Controller (function __construct () ($ this-\u003e model \u003d new Model_Portfolio (); $ this-\u003e view \u003d new View ();) function action_index () ($ data \u003d $ this-\u003e model-\u003e get_data ( ); $ this-\u003e view-\u003e generate ("portfolio_view.php", "template_view.php", $ data);))
  To variable data   the array returned by the method is written get_datawhich we considered earlier.
  This variable is then passed as a parameter to the method. generate, to which are also transferred: the name of the file with a common template and the name of the file containing the view with the content of the page.

The view containing the content of the page is in the file portfolio_view.php.

Portfolio

  All projects in the following table are fictitious, so do not even try to follow the links provided. "; } ?>
YearProjectDescription
". $ row [" Year "]."". $ row [" Site "]."". $ row [" Description "]."


  Everything is simple here, the view displays the data obtained from the model.

2.3.3. Create the rest of the pages

  The remaining pages are created in the same way. Their code is available in the repository on GitHub, the link to which is provided at the end of the article, in the "Result" section.

3. Result

  And here is the result:

Screenshot of the resulting business card website



  GitHub Link: https://github.com/vitalyswipe/tinymvc/zipball/v0.1

But in this version, I sketched the following classes (and their corresponding types):

  • Controller_Login in which a view is generated with a form for entering a login and password, after filling in which an authentication procedure is performed and, if successful, the user is redirected to the admin panel.
  • Contorller_Admin with an index action in which it checks whether the user has previously been authorized on the site as an administrator (if there was, then the admin view is displayed) and the logout action to log out.
  Authentication and authorization is a different topic, therefore, it is not considered here, but only the link indicated above is provided so that there is something to start from.

4. Conclusion

The MVC template is used as an architectural basis in many frameworks and CMS, which were created in order to be able to develop qualitatively more complex solutions in a shorter time. This was made possible by increasing the level of abstraction, since there is a limit to the complexity of the structures that the human brain can operate on.

But, the use of web frameworks such as Yii or Kohana, consisting of several hundred files, when developing simple web applications (for example, business card sites) is not always advisable. Now we are able to create a beautiful MVC model so as not to mix Php, Html, CSS and JavaScript code in one file.

This article is more of a starting point for learning CMF than an example of something truly correct that you can take as a basis for your web application. Perhaps she even inspired you and you are already thinking of writing your microframework or CMS based on MVC. But, before you invent another bike with blackjack and whores, think again, can it be wiser to direct your efforts towards developing and helping the community of an existing project ?!

P.S .: The article was rewritten taking into account some of the comments left in the comments. Criticism has been very helpful. Judging by the response: the comments, appeals in PM and the number of users who added a post to your favorites idea to write this post was not so bad. Unfortunately, it is not possible to take into account all the wishes and write more and more in detail due to lack of time ... but maybe those mysterious individuals who minus the original version will do it. Good luck with your projects!

5. A selection of useful links for the subject

  The article very often touches on the topic of web frameworks - this is a very extensive topic, because even microframes consist of many components artfully linked together and it would take more than one article to talk about these components. Nevertheless, I decided to give here a small selection of links (which I followed when writing this article) that one way or another relate to the theme of frameworks.

Tags:

  • php
  • framework
  • cmf
  • mvc
  • site
   Add tags

Hello! We continue to build our own MVC application, and today we will begin to deal with the output of pages.

Create a file View.php   in folder libs.

   class View (

   echo "This is a view";
}
}
?>

Now open our main file index.php   and connect it.

Require "libs / View.php";

Having opened the page, we should see the inscription "This is a view."

Now let's change our view class by adding a method renderwho will deal with the conclusion.

   class View (
   public function __construct () (
   echo "This is a view";
}

Public function render ($ name) (
   require "views /".$ name.". php ";
}
}
?>

Now create folders index   and error   in folder views. They will be responsible for the submission. index   pages and error pages. In folder error   create a new index.php   file and write the following


  This is the error page!

Now create a file header.php   in the folder itself views   with such content


  Header

Let's go to the file error.phplocated in the folder error   and add a method call to the constructor render.

   public function __construct () (
   // the code
   $ this-\u003e view-\u003e render ("error / index");
}
?>

Now on the page we will see "Header This is the error page!"

Let's slightly improve our controller by adding to it before calling the method render   following:

   public function __construct () (
   // the code
   $ this-\u003e view-\u003e msg \u003d "The page does not exist!";
   $ this-\u003e view-\u003e render ("error / index");
}
?>

And now in the file index.php, which is responsible for the type of error, instead of our inscription "This is the error page!" print what is stored in the property msg.




msg; ?\u003e

Now we got our inscription.

Let's create a model now help_model.php   in folder models.

   class Help_Model extends Model (
   public function __construct () (
   echo "Model help_model";
}
}
?>

Now open the controller help.php   from folder controllers   and add a call to our model

   class Help extends Controller (
   // the code

Public function other ($ arg \u003d false) (
   // the code

Require "models / help_model.php";
   $ model \u003d new Help_Model ();
}
}
?>

   class Model (
   public function __construct () (
   // $ this-\u003e database \u003d new Database ();
}
}
?>

Our model will work with the database, but for now, comment on this, because we do not have a database yet.

Connect our base model in our main file index.php.

Require "libs / Bootstrap.php"; require "libs / Controller.php"; require "libs / model.php"; require "libs / View.php";

So, let's stop on this today. We have already made some conclusions on the page, and in future articles we will continue to improve this. Thank you for your attention and good coding!

Design Pattern Model-View-Controller (MVC)   Is a software architecture template built on the basis of preserving the presentation of data separately from methods that interact with data.

Despite the fact that the MVC scheme was originally developed for personal computers, it has been adapted and is widely used by web developers due to the exact differentiation of tasks and the possibility of code reuse. The scheme stimulates the development of modular systems, which allows developers to quickly update, add or remove functionality.

In this article I will describe the basic principles, and also consider the definition of a construction scheme and a simple MVC PHP example.

What is MVC?

The name of the design pattern is determined by its three main components: Model, View and Controller. The visual representation of the MVC template looks as shown in chart below:


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

Model

A model is called a permanent storage of data used throughout the structure. It must provide access to data for viewing, selection or recording. In the 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 transmitted to the “View” or “Controller” components. The only task of the “Model” is the processing of data in a permanent storage, search and preparation of data transmitted to other components of MVC.

The “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 pinnacle of the whole structure, since without it the connection between the “Controller” and the “View” is impossible.

Representation

A view is a part of the system in which the data requested from the Model is set to the final form of their output. In MVC-based web applications, “View” is the component in which HTML is generated and displayed.

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

There are several common misconceptions regarding the Presentation component. For example, many mistakenly believe that the "View" has no connection with the "Model", and all the displayed data is transmitted from the "Controller". In fact, such a data flow scheme does not take into account the theory underlying the MVC architecture. In his article, Fabio Chevasko describes this incorrect approach using one of the unconventional MVC PHP frameworks as an example:

“In order to correctly apply the MVC architecture, there should be no interaction between the“ Model ”and the“ View ”: all the logic is processed 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 errors of various developers, which lead to a common misconception. Then they incorrectly explain it to others. In fact, the "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 transmitted directly by the Controller. There is no direct connection between the "View" and the "Controller" - they are connected using the "Model".

Controller

Its task is to process the data that the user enters and update the "Model". This is the only part of the circuit 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 contains no other logic than the need to collect incoming data. A “controller” is also connected to only one “View” and one “Model”. This creates a system with a one-way data stream with one input and one output at data exchange points.

The “controller” receives tasks for execution only when the user interacts with the “View”, and each function depends on the interaction of the user with the “View”. The most common mistake made by developers is that they confuse the "Controller" with the gateway, so they assign functions and tasks that relate to the "View" to it.

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

MVC in PHP

We will write in PHP a web application whose architecture is based on MVC. Let's start with an example wireframe:

string \u003d "MVC + PHP \u003d Awesome!"; )))controller \u003d $ controller; $ this-\u003e model \u003d $ model; ) public function output () (return "

". $ this-\u003e model-\u003e string."

"; } } model \u003d $ 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 above PHP MVC example, 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 intended only for demonstration.

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

string \u003d “MVC + PHP \u003d Awesome, click here!”; )))controller \u003d $ controller; $ this-\u003e model \u003d $ model; ) public function output () (return "

model-\u003e string. "

"; } } model \u003d $ model; ) public function clicked () ($ this-\u003e model-\u003e string \u003d “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-\u003e output ();

Hello! Today I am writing the first article in a series dedicated to creating my own MVC applications.

First, it’s worth noting that if someone doesn’t know what is MVCthen read this article first:.

So what will we have in the end? We'll have enginecreated using mVC Design Pattern. This engine will be very simple, checks will be omitted somewhere, but this is all done so that you understand how to create applications on MVC, and then, having finalized our engine, you can use it for your projects. We will have the basic functionality:

  • authorization
  • small chat
  • adding articles
  • article editing
  • delete articles
  • user management

It all starts with the folder structure. We will have it like this:

  • index.php
  • .htaccess
  • controllers
  • models
  • views
  • libs

I think everything is clear here. In folders controllers, models, views   and libs   will be kept controllers, models, kinds   and other files. In the process of creation, we will add the folders and files we need.

To create our engine will be used object oriented approach. If you do not know him well, then you should also first read about this article on the site.

So, this is where I finish the introductory article, and in the next we will begin to create mVC engine. See you later!

Pattern Model-View-Controller (MVC), opened in the late 1970s, is a software architecture design pattern whose main task is to separate data functions from their presentation. Theoretically, a well-designed MVC application will allow front-end and back-end developers not to interfere in each other's areas of responsibility during work, that is, a front-end developer does not need to know anything about the “kitchen” of his back-end colleague and vice versa.

Although MVC was originally designed to develop desktop applications, it was adapted for modern tasks and is very popular among web developers, since due to the division of responsibilities, it became possible to create more clear, ready-to-use code. The MVC pattern leads to clear, modular systems that allow developers to make changes to existing code very quickly.

In this article, we will cover the basic principles of MVC, starting with defining a pattern and continuing with its application in a small example. This article will be primarily useful to those who have never encountered this pattern in life, and also, perhaps, to those who want to refresh their knowledge of MVC.

Understanding MVC

As already mentioned, the name of the pattern comes from the abbreviation of three words: Model View   and Controller. Briefly, the principle of the pattern can be illustrated by one scheme (can be found on Wikipedia):

This diagram illustrates the unidirectional flow of information in a pattern, and also describes the roles of each component.

Model

The model is used to access and manipulate data. In most cases, a model is what is used to access a data store (for example, a database). The model provides an interface for searching for data, its creation, modification and removal from the repository. In the context of the MVC pattern, the model mediates between the view and the controller.

An extremely important feature of the model is that, technically, it does not have any knowledge of what happens to the data in the controller and view. A model should never make or expect any requests to / from other components of the pattern.

However, always remember that a model is not just a gateway to access a database or other system, which only deals with the transfer of data back and forth. A model is a bit of a data checkpoint. The model in most cases is the most complex part of the system, partly due to the fact that the model itself is a connecting link for all other parts.

Representation

A view is where the data received from the model is displayed in the desired form. In traditional web applications developed as part of the MVC pattern, presentation is part of the system where HTML is generated. The view is also responsible for receiving actions from the user in order to send them to the controller. For example, a view displays a button in the user interface, and after pressing it calls the corresponding controller action.

There are some misconceptions regarding the purpose of the presentation, especially among web developers who are just starting to build their applications using MVC. One of the most commonly violated rules is that the presentation should in no way communicate with the model, and all data received by the view should only come from the controller. In practice, developers often ignore this concept, which lies at the heart of the MVC pattern. Fabio Cevasco's article illustrates this confusing MVC approach with the CakePHP framework, one of many non-standard MVC frameworks:

It is imperative to understand that in order to get the right MVC architecture, there should be no direct interactions between views and models. All the logic of data exchange between them must be implemented in controllers.

In addition, there is a common misconception that a view is just a template file. As noted by Tom Butler, this misconception is enormous due to the fact that many developers misunderstand the structure of MVC from the very beginning, after which they begin to pour this “knowledge” further, the masses of beginning developers. Actually, a presentation is much more than just a template, however, many frameworks built on the basis of the MVC pattern have distorted the concept of the presentation so much that nobody cares how correct their applications are from the point of view of the MVC pattern.

Another important point is that the view never works with “pure” data from the controller, that is, the controller never works with the view bypassing the model. In the process of controller and view interaction, the model should always be between them.

Controller

The controller is the last part of the MVC bundle. The controller's task is to obtain data from the user and manipulate the model. It is the controller, and only he, that part of the system that interacts with the user.

In a nutshell, the controller can be described as a collector of information, transmitting it to the model for processing and storage. He should not do anything with the data, but only be able to receive it from the user. The controller is associated with one view and one model, thus organizing a unidirectional data stream, controlling it at each stage.

It is very important to remember that the controller starts its work only as a result of user interaction with the view, which calls the corresponding function of the controller. The most common mistake among developers is that the controller is considered simply as a gateway between the view and the model. As a result, the controller is endowed with those functions that should be performed by the view (by the way, this is where the idea’s legs come from, that the view is just a template file). On top of that, many generally dump the entire logic of data processing, forgetting what the model is for in the MVC pattern.

MVC in PHP

I suggest trying to implement the above in a small application. Let's start by creating the model, view and controller classes:

string \u003d "MVC + PHP \u003d Awesome!"; )))controller \u003d $ controller; $ this-\u003e

". $ this-\u003e model-\u003e string."

"; } } model \u003d $ model; )))

Basic classes are ready. Now let's tie them together and launch our application:

output ();

As you can see, the controller does not have any functionality, since the user does not interact with the application. All functionality is placed in the view, because our application is designed exclusively for data output.

Let's expand the application a bit by adding a bit of interactivity to see how the controller works:

string \u003d “MVC + PHP \u003d Awesome, click here!”; )))controller \u003d $ controller; $ this-\u003e model \u003d $ model; ) public function output () (return "

model-\u003e string. "

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

And finally, we’ll slightly upgrade the middleware:

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

Summary

In this short article, we examined the basic concepts of the MVC design pattern and developed a simple application based on it, although of course, we are still very far from using this in real life. In the next article, we will consider the main difficulties that you will encounter if you are more closely involved in building the architecture of the application based on the MVC pattern. Stay tuned!


Top