Model view controller in clear language. Introduction to MVC online lesson


Many people start writing a project to work with a single task, not implying that it can grow into a multi-user management system, for example, content or, God forbid, production. And everything seems great 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. A pressing problem arises: when adding new features, you have to tinker with this code for a very long time, remembering “what was written there?” and curse yourself in the past.

You may have even heard about design patterns and even leafed through these wonderful books:

  • E. Gamma, R. Helm, R. Johnson, J. Vlissides “Objective techniques oriented design. Design Patterns";
  • M. Fowler "Architecture of Enterprise Software Applications."
And many, undaunted by the huge manuals and documentation, tried to study any of the modern frameworks and, faced with the complexity of understanding (due to the presence of many architectural concepts cleverly linked to each other), put off the study and use of modern tools “on the back burner.”

This article will be useful primarily for beginners. In any case, I hope that in a couple of hours you will be able to get an idea of ​​the implementation of the MVC pattern, which underlies all modern web frameworks, and also get “food” for further reflection on “how to do it.” At the end of the article there is a selection of useful links that will also help you understand what web frameworks consist of (besides MVC) and how they work.

Seasoned 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 MVC concept, you can skip the theory section and go straight to the practice.

1. Theory The MVC pattern describes a simple way to structure an application, 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, implement.

Let's look at the conceptual diagram of the MVC pattern (in my opinion, this is the most successful diagram I have seen):

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

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

  • When a user visits a web resource, the initialization script creates an instance of the application and launches it for execution.
    This displays the view, say home page site.
  • 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).
  • The application instantiates the controller and runs the action method,
    which, for example, contains model calls that read information from the database.
  • After this, the action creates a view with the data obtained from the model and displays the result to the user.
  • Model - contains the business logic of the application and includes methods for sampling (these can be ORM methods), processing (for example, validation rules) and providing 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 that can change depending on the user's needs. Such code should be processed in views.
    The same model, for example: the user authentication model can be used in both the user and administrative parts of the application. In this case, you can put the general code in separate class and inherit from it, defining sub-application-specific methods in its descendants.

    View - used to specify the external display of data received from the controller and model.
    Views contain HTML markup and small inserts of PHP code to traverse, format, and display data.
    Should not directly access the database. This is what models should do.
    Should not work with data obtained from a user request. This task must be performed by the controller.
    Can directly access properties and methods of a controller or models to obtain output-ready data.
    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.

    The controller is the glue that connects models, views and other components into working application. The controller is responsible for processing user requests. The controller should not contain SQL queries. It is better to keep them in models. The controller should not contain HTML or other markup. It’s worth bringing it into view.
    In a well-designed MVC application, controllers are usually very thin and contain only a few dozen lines of code. What can't be said about Stupid Fat Controllers (SFC) in CMS Joomla. The controller logic is quite typical and most of it is transferred to base classes.
    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 within it are usually quite specific to a particular application.

    1.1. Front Controller and Page Controller In most cases, user interaction with a web application occurs through clicking on links. Look now at the address bar of your browser - you received this text from this link. Other links, such as those on the right side of this page, will provide you with different content. Thus, the link represents a specific command to the web application.

    I hope you have already noticed that different sites can have completely different construction formats address bar. Each format can display the architecture of a web application. Although this is not always the case, in most cases it is a clear fact.

    Let's consider two options for the address bar, which display some text and a user profile.

    Approximate processing code in this case:
    switch($_GET["action"]) ( case "about" : require_once("about.php"); // "About Us" page break; case "contacts" : require_once("contacts.php"); // "Contacts" page break; case "feedback" : require_once("feedback.php"); // "Feedback" page break; default: require_once("page404.php"); // page "404" break; )
    I think almost everyone has done this before.

    Using a URL routing engine, you can configure your application to accept requests like this to display the same information:
    http://www.example.com/contacts/feedback

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

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

    2. Practice First, let's create the following file and folder structure:


    Looking ahead, I will say that the core classes Model, View and Controller will be stored in the core folder.
    Their children will be stored in the controllers, models and views directories. The index.php file is the entry point into the application. The bootstrap.php file initiates the loading of the application, connecting all the necessary modules, etc.

    We will go sequentially; Let's open the index.php file and fill it with the following code:
    ini_set("display_errors", 1); require_once "application/bootstrap.php";
    There shouldn't be any questions here.

    Next, let's immediately go to the bootstrap.php file:
    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 currently non-existent kernel files. Last lines connect the file with the router class and launch it for execution by calling the static start method.

    2.1. Implementing a URL Router For now, let's deviate from the implementation of the MVC pattern and focus on 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 all page processing to index.php, which is what we need. Remember in the first part we talked about Front Controller?!

    We will place the routing in a separate file route.php in the core directory. In this file we will describe the Route class, which will run controller methods, which in turn will generate the page view.

    Contents of the route.php file

    class Route ( static function start() ( // controller and default action $controller_name = "Main"; $action_name = "index"; $routes = explode("/", $_SERVER["REQUEST_URI"]); // get the controller name if (!empty($routes)) ( $controller_name = $routes; ) // get the action name if (!empty($routes)) ( $action_name = $routes; ) // add prefixes $model_name = " Model_".$controller_name; $controller_name = "Controller_".$controller_name; $action_name = "action_".$action_name; // hook up the file with the model class (there may not be a model file) $model_file = strtolower($model_name). ".php"; $model_path = "application/models/".$model_file; if(file_exists($model_path)) ( include "application/models/".$model_file; ) // hook up the file with the controller class $controller_file = strtolower ($controller_name)..php"; $controller_path = "application/controllers/".$controller_file; if(file_exists($controller_path)) ( include "application/controllers/".$controller_file; ) else ( /* it would be correct to throw an exception here, but to simplify things, we’ll immediately redirect to the 404 page */ Route::ErrorPage404(); ) // create a controller $controller = new $controller_name; $action = $action_name; if(method_exists($controller, $action)) ( // call the controller action $controller->$action(); ) else ( // here it would also be wiser to throw an exception Route::ErrorPage404(); ) ) function ErrorPage404( ) ( $host = "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 very simplified logic (despite the voluminous code) and may even have security problems. This was done intentionally, because... writing a full-fledged routing class deserves at least a separate article. Let's look at the main points...

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

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

    Next, the model file (the model may be missing) and the controller file, if any, are connected 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 to, for example, the address:
    example.com/portfolio
    or
    example.com/portfolio/index
    The router will perform the following actions:

  • will include the model_portfolio.php file from the models folder, containing the Model_Portfolio class;
  • will include the controller_portfolio.php file from the controllers folder, containing the Controller_Portfolio class;
  • will create an instance of the Controller_Portfolio class and call the default action - action_index, described in it.
  • If the user tries to access the address of a non-existent controller, for example:
    example.com/ufo
    then he will be redirected to the “404” page:
    example.com/404
    The same thing will happen if the user accesses an action that is not described in the controller.2.2. Let's return to the MVC implementation Let's 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.

    Contents of the model.php file
    class Model ( public function get_data() ( ) )
    The model class contains a single empty data fetch method, which will be overridden in descendant classes. When we create descendant classes everything will become clearer.

    Contents of the view.php file
    class View ( //public $template_view; // here you can specify the default general view. function generate($content_view, $template_view, $data = null) ( /* if(is_array($data)) ( // convert array elements into variables extract($data); ) */ include "application/views/".$template_view; ) )
    It is not difficult to guess that the method generate intended to form a view. The following parameters are passed to it:

  • $content_file - views displaying page content;
  • $template_file - template common to all pages;
  • $data is an array containing page content elements. Usually filled in in the model.
  • The include function dynamically connects a general 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 page content will be contained in a separate form. Again, this is done for simplicity.

    Contents of the controller.php file
    class Controller ( public $model; public $view; function __construct() ( $this->view = new View(); ) function action_index() ( ) )
    Method action_index- this is an action called by default; we will override it when implementing descendant classes.

    2.3. Implementation of the descendant classes Model and Controller, creation of View "s Now the fun begins! Our business card website will consist of the following pages:
  • home
  • Services
  • Portfolio
  • Contacts
  • And also - the “404” page
  • Each page has its own controller from the controllers folder and a view from the views folder. Some pages may use a model or models from the models folder.


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

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

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

    We reviewed the general view file earlier. Consider the content file main_view.php:
    Welcome!

    OLOLOSHA TEAM is a team of first-class specialists in the field of website development with many years of experience in collecting Mexican masks, bronze and stone statues from India and Ceylon, bas-reliefs and sculptures created by masters of Equatorial Africa five or six centuries ago...


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

    We will consider an example using a view displaying data obtained from the model below.

    2.3.2. Create a “Portfolio” page In our case, the “Portfolio” page is the only page that uses the model.
    The model usually includes data sampling methods, for example:
  • methods of native pgsql or mysql libraries;
  • methods of libraries that implement data abstraction. For example, methods of the PEAR MDB2 library;
  • ORM methods;
  • methods for working with NoSQL;
  • and etc.
  • For simplicity, we will not use SQL queries or ORM statements here. Instead, we will emulate real data and immediately return an array of results.
    Place the model file model_portfolio.php in the models folder. Here are its contents:
    class Model_Portfolio extends Model ( public function get_data() ( return array(array("Year" => "2012", "Site" => "http://DunkelBeer.ru", "Description" => "Promotional site of the dark Dunkel beer from the German manufacturer Löwenbraü produced in Russia by the brewing company "SUN InBev."), array("Year" => "2012", "Site" => "http://ZopoMobile.ru", "Description" => "Russian-language catalog Chinese phones Zopo company based on Android OS and accessories for them."), // todo); ) )

    The model controller class is contained in the controller_portfolio.php file, here is its code:
    class Controller_Portfolio extends Controller ( function __construct() ( $this->model = new Model_Portfolio(); $this->view = new View(); ) function action_index() ( $data = $this->model->get_data( ); $this->view->generate("portfolio_view.php", "template_view.php", $data); ) )
    To a variable data the array returned by the method is written get_data which we looked at earlier.
    This variable is then passed as a method parameter generate, which also contains: the name of the file with the general template and the name of the file containing the view with the page content.

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

    All projects in the following table are fictitious, so do not even try to follow the links provided.
    YearProjectDescription


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

    2.3.3. Creating the remaining pages The remaining pages are created in the same way. Their code is available in the GitHub repository, a link to which is provided at the end of the article, in the “Result” section.3. Result Here's what happened in the end:

    Screenshot of the resulting business card website



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

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

    • Controller_Login in which a view is generated with a form for entering login and password, after filling which the authentication procedure is performed and, if successful, the user is redirected to the admin panel.
    • Contorller_Admin with an index action that checks whether the user was previously authorized on the site as an administrator (if so, the admin panel view is displayed) and a logout action for logging out.
    Authentication and authorization is a different topic, so it is not discussed here, but only the link given above is provided so that you have something to start from.4. Conclusion The MVC pattern is used as an architectural basis in many frameworks and CMSs that were created in order to be able to develop higher quality complex solutions in a shorter period of 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 with.

    But, using 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 can 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 use as the basis for your web application. Perhaps it even inspired you and you are already thinking about writing your own microframework or CMS based on MVC. But, before reinventing the next wheel with “blackjack and whores,” think again: maybe it would be more reasonable to direct your efforts to the development and helping the community of an already existing project?!

    P.S.: The article was rewritten taking into account some comments left in the comments. The criticism turned out to be very useful. Judging by the response: comments, PMs and the number of users who added the post to favorites, the idea of ​​writing this post turned out to be not so bad. Unfortunately, it is not possible to take into account all the wishes and write more and in more detail due to lack of time... but perhaps those mysterious individuals who downvoted the original version will do this. Good luck with your projects!

    5. A selection of useful links on the subject The article very often touches on the topic of web frameworks - this is a very broad topic, because even microframeworks consist of many components cleverly interconnected and it would take more than one article to talk about these components. However, I decided to present here a small selection of links (which I followed while writing this article) that in one way or another relate to the topic of frameworks.

    Tags: Add tags

    MVC (Model-View-Controller) is a widely used development technique (pattern).

    Today this is the most popular pattern used in web development.

    In this course of lectures we will create an MVC framework and simple CMS, which is based on it.
    This CMS will have several controllers for working with articles, users and a feedback form, as well as an admin panel.

    Models, Views, Controllers are special required parts of a web application.

    Key principles of MVC:

    Models - responsible for application data and database access;

    Controllers are responsible for user interaction with the system.
    If necessary, controllers receive data from models.

    Representations (in other words, HTML templates) - simply display the data received from the controller.

    There is no direct connection between views and models.

    MVC applications have many advantages such as:
    - ease of understanding and ease of development;
    - high degree flexibility;
    - simple code support;
    - fast development.

    That is why numerous applications and world-famous frameworks
    based on MVC.

    Let's take a look at a commercial website as an example:

    As a rule, it consists of at least several main modules:
    - Products module, which is responsible for displaying products, searching and displaying;
    - Cart module, which is responsible for placing and processing orders;
    - Users module – responsible for registering users and managing accounts.

    In MVC terms, this application has the following structure:

    ProductsController class with methods (functions) index (show a list of products),
    show (shows one product), search (search by product). These methods are called actions.
    This controller interacts with the Product class (model), which will contain methods for
    access and manage product data, such as getProductsList, search, getProductById,
    save, delete, etc.

    ProductsController also contains methods for the admin panel. For example, admin_edit is for
    editing the product or admin_view - to view the product in the admin panel.

    The structure of the Cart and Users modules is similar to the structure of the Products module.

    Using this standard structure allows us to separate the code of different
    logical parts or “modules” of our application in order to increase
    productivity and avoid mistakes.
    We can be sure that if this is a Products model, then it does not contain code for managing users and vice versa.
    In addition, in this way we separate PHP, HTML, JS and SQL codes.

    This way the code is cleaner and more understandable.

    Let's look at how requests are processed in MVC.

    An MVC application requires that the URL be built in a specific form.

    Regarding the example of a commercial site that we mentioned above, if we want
    to get to the product listing page, we need to go to the following URL:
    http://your-site.com/products

    IN in this case, products is the name of the controller, and the name of the action is index, by
    default. If we want to view a specific product it will be
    http://your-site.com/products/view/11.

    We believe you have already seen similar URLs.
    Such URLs are called User Friendly (i.e., user-friendly URL), or CNC (human-readable URL).

    Therefore, here product is the name of the controller, and the name of the view and action is index.
    In the URL, 11 is the parameter for action. In this case it will be the product id.

    Actually, a controller is a part of an application that is responsible for certain
    plots. For example, Users, Products, Pages will be different controllers. All operations
    which can be produced in the application are implemented in controllers as public methods.

    For example, the Users controller will contain methods register, login, logout, etc.
    All data that is displayed to the user is passed from the controller to views, i.e. V
    HTML templates. Typically, each controller method has a corresponding view.

    Let's look at how requests are processed in an MVC website.

    It's pretty simple.

    1. Using a special .htaccess file, all requests that are not
    file requests are redirected to the index.php file.

    2. The next step is to call the dispatcher. The dispatcher parses the URL in order to get
    controller and action name. Other parameters are also obtained from the request. This
    maybe, for example, a language code.

    3. Once a suitable controller and controllers method names are determined,
    The controller method is called.

    4. The controller method then calls the models methods to get the data.

    5. When the time comes to provide data to the user, the
    display the corresponding view. All data that is returned
    by the controller method are passed to the view in the form of an array and there
    are displayed.

    6. Finally, the user receives an html page.

    So now we're ready to start. In the next lecture we will start developing our project
    from creating a directory structure.

    In the Model-View-Controller pattern, the model represents the application data and the associated business logic. A model can be represented by a single object or a complex graph of related objects. In a Java platform application, its data is encapsulated in objects subject area, often deployed in an EJB module. Data is transferred to and from the database in data transfer objects (DTOs) and accessed using data access objects (DAOs).

    A view is a visual representation of the data contained in a model. A subset of the model is contained in a separate view, so the view acts as a filter for the model data. The user interacts with the model data using the visual display offered by the view and accesses the business logic, which, in turn, affects the model data.

    The controller connects the view to the model and manages the application's data flow. It selects which view to render to the user in response to the user's input and according to the business logic being executed. The controller receives the message from the view and forwards it to the model. The model, in turn, prepares a response and sends ero back to the controller, where the view is selected and ero is sent to the user.

    The MVC pattern logically spans the client and middle layer of a multi-tier architecture. IN Java environment Its model is located in the business layer, usually in the form of an EJB module.

    The controller and view are located in the web layer. The view will most likely be created from JavaServer Faces (JSF) or JavaServer Pages (JSP) using an Expression Language (EL). The controller is typically a servlet that receives HTTP requests from the user.

    MVC is often combined with other patterns such as Command (or Action), Strategy, Composer, and " ".

    This pattern was first mentioned before the creation of the Internet in its modern form, in an article published in December 1979 by Trygve Reenskaug, a programmer then working at Xeror SmallTalk.

    And although the MVC elements of this pattern were described more than 35 years ago, they surprisingly closely correspond to their modern use in web applications.

    The following figure shows a user making a request to a controller. The controller processes the request by updating the model and rendering a new view, which is then sent to the user.

    MVC Pattern Diagram

    The MVC pattern comes in many different forms. The two most famous are usually called type I and type II.

    MVC pattern types:
    • MVC type I. This type is a page-centric approach in which the view and controller exist as a single entity called the view-controller. In this approach, the controller logic is implemented in a view such as JSF. All tasks performed by the controller, including retrieving HTTP request attributes and parameters, calling business logic, and managing the HTTP session, are built into the view using scriptlets and tag libraries. Type I strongly couples the formation of the view to the sequence of actions performed by the application, thereby making maintenance difficult.
    • MVC type II. The maintainability problems of Type I are overcome in Type II by moving the controller logic out of the view and into the servlet, leaving the data visualization to the view.

    The main difference between Type I and Type II is the location of the controller logic: in Type I it is in the view, and in Type II it is in the servlet.

    Many frameworks such as Spring MVC, Struts, Grails and Wicket implement their own version of the MVC Type II pattern. For example, Spring MVC includes the concept of a dispatcher servlet that interacts with HTTP requests and performs delegation to the controller, and also contains a view (and view resolver) and handlers.

    The following figure shows an implementation diagram of the MVC pattern in Spring.

    Diagram of the implementation of the MVC pattern in Spring

    There are millions of web applications scattered throughout the internet world. There are some that are quite simple, and there are those that “the architect of the matrix himself would break his leg.” But they have one thing in common - MVC.

    The most popular architectural pattern in the world among web applications is model-view-controller ( Model View Controller or just MVC). For the first time, it was used back in the late 70s of the twentieth century, in applications in the Smalltalk language. And then, it was adopted by Java programmers and shared with the whole world and all programming languages. PHP was no exception. Today, only a small part of programmers who collect rare PHP code can afford not to look towards MVC.

    It became so popular for a reason. It was simply born to create flexible and scalable applications that are easy to maintain and expand.
    The purpose of our tutorial is to show simple example how the MVC pattern works.

    To complete the tasks, you will need the following programs:

    Notes:

    MVC pattern

    Now let's talk about everything in order. First, let's reveal the great secret of the abbreviation, which obviously reflects the fact that the application will consist of three interacting parts:

    • The model is responsible for data management, it stores and retrieves the entities used by the application, typically from a database, and contains the logic implemented in the application.
    • The view is responsible for displaying the data given by the controller. Closely related to presentation is the concept of a template, which allows you to change the appearance of the information shown. In a web application, the view is often implemented as an HTML page.
    • The controller connects the model and the view. It receives a request from the client, analyzes its parameters, and accesses the model to perform operations on the request data. Already assembled objects come from the model. They are then redirected to the view, which passes the generated page to the controller, which in turn sends it to the client.

    The data flows in this model can be schematically represented as follows:

    Entering reality

    Let's finally formulate the real problem. Let us say they ordered us to build a social networking site. This gigantic task has a small subtask: using the existing database of friends, ensure that they are viewed full list, as well as detailed information for each friend.

    We will not now consider the architecture of the entire social network. We will take only a small subtask, imagine its seriousness and apply the MVC pattern to it.

    As soon as we start using it, we immediately think - how can we arrange the scripts of our solution so that everything is at hand? To do this, we will place each of the three sections of our MVC system according to separate folders and thus we get simple structure catalogs in which it is easy to find what we need. In addition, we will place these three folders in the lib directory, and move it above the root www web directory:

    /lib --/controller ---- FrendCnt.php --/model ---- Frend.php ---- FrendList.php --/view ---- frendlist.php ---- frendone.php / www -- index.php -- .htaccess

    Uploading the catalog lib(containing the engine of our site) from the web directory gives us greater security, making our system inaccessible to the encroachments of the playful hands of hackers.

    Controller

    Now let's talk about everything in order. Let's start with the controller, since it is the first of the three components of the pattern that meets the client request, parses it into elements, and initializes model objects. After the model processes the data, it accepts its response and sends it to the presentation layer.

    In our simple example, the controller will be concentrated in a single FrendCnt class. We will describe it in more detail later. And now a little about the entry point into the web application - this, of course, will be a file index.php. In it, we will determine the starting point for connecting our scripts. Let's create an instance of the controller and call a method on it that will begin processing the HTTP request and determine what to do next.

    Listing No. 1 (file index.php):

    $baseDir = dirname(__FILE__) . "/.."; include_once($baseDir . "/lib/controller/FriendCnt.php"); $controller = new FriendCnt(); $controller->invoke();

    Now about the controller. For us, this is the FriendCnt class. You have already noticed that an instance of this class is created in index.php. It has only one invoke() method, which is called immediately after the instance is created. In the controller constructor, an object is created based on the model class - FrendList (list of friends) for operating with data.

    In the invoke() function, based on the incoming HTTP request, a decision is made: what data is required from the model. Then the method that retrieves the data is called. Next, templates for display are connected, to which data is transferred from the controller. Note that the controller doesn't know anything about the database or how the page is rendered.

    Listing No. 2 (controller file FriendCnt.php):

    Require_once($baseDir . "/lib/model/FriendList.php"); class FriendCnt ( public $oFriendList; public function __construct() ( $this->oFriendList = new FriendList(); ) public function invoke() ( global $baseDir; $oFriendList = $this->oFriendList; if(isset($_GET ["key"])) ( $oFriendList->setKey($_GET["key"]); $oFriend = $oFriendList->fetch(); include $baseDir . "/lib/view/friendone.php"; ) else ( $aFriend = $oFriendList->fetch(); include $baseDir . "/lib/view/friendlist.php"; ) ) )

    Model and Entities

    A model is an image of reality, from which only what is needed to solve a problem is taken. The model focuses on the logic of solving the main problem. Many call this business logic; it bears a great responsibility:

    • Saving, deleting, updating application data. This is implemented through database operations or through calls to external web services.
    • Encapsulation of all application logic. Absolutely all application logic, without exception, must be concentrated in the model. There is no need to move any part of the business logic into a controller or view.

    Our model includes two scripts, each of which has its own class defined. The central FriendList class and the Friend entity class. In the central class, data manipulation occurs: receiving data from the controller and processing it. The entity class serves as a container for transferring data between the model and the view, and also defines its format. In a good implementation of the MVC pattern, entity classes should not be referenced in the controller, and they should not contain any business logic. Their purpose is only to store data.
    In the FriendList class, which works with a list of friends, we created a function that models the interaction of this class with the database. The getFriendList() method returns an array of objects created from the Friend class. To ensure ease of working with data, a function was also created that indexes an array of objects. Only two methods were available to the controller: setKey() - sets the key field by which detailed data about the friend is returned; fetch() - returns either a specific object or the entire list of friends.

    Listing No. 3 (model file FriendList.php):

    Require_once($baseDir . "/lib/model/Friend.php"); class FriendList ( private $oneKey; private function getFriendList() ( return array(new Friend("Alexander", "1985", " [email protected]"), new Friend("Yuri", "1987", " [email protected]"), new Friend("Alexey", "1989", " [email protected]"),); ) private function getIndexedList() ( $list = array(); foreach($this->getFriendList() as $val) ( $list[$val->getKey()] = $val; ) return $list; ) public function setKey($key) ( $this->oneKey = $key; ) public function fetch() ( $aFriend = $this->getIndexedList(); return ($this->oneKey) ? $aFriend [$this->oneKey] : $aFriend; ) )

    Depending on the implementation of Entity objects, data about it can be formatted as an XML document or a JSON object.

    Listing #4 (Friend.php entity file):

    Class Friend ( private $key; private $name; private $yearOfBirth; private $email; public function __construct($name, $yearOfBirth, $email) ( $this->key = md5($name . $yearOfBirth . $email) ; $this->name = $name; $this->yearOfBirth = $yearOfBirth; $this->email = $email; ) public function getKey() ( return $this->key; ) public function getName() ( return $this->name; ) public function getYearOfBirth() ( return $this->yearOfBirth; ) public function getEmail() ( return $this->email; ) )

    Performance

    Now we need to present the data in the best possible light for the user.

    It's time to talk about the Presentation. Depending on the task, data can be passed to the view in different formats: simple objects, XML documents, JSON objects, etc. In our case, an object or an array of objects is passed. At the same time, we did not worry about the output of the base layer - what applies to the footer and header of the generated page, this code is repeated in both view files. But for our small example this is not important.

    The main point here is to show that the view is separate from the controller and model. In this case, the controller is responsible for transferring data from the model to the view.

    In our example, the view contains only two files: for display detailed information about a friend and to display a list of friends.

    Listing No. 5 (file for displaying a list of friends friendlist.php):

    My friends

    Name Year of birth




    

    2024 gtavrl.ru.