Detailed description of MVC architecture in PHP

Source: Internet
Author: User
MVC is short for MODEL_VIEW_CONTROL. MODEL_VIEW_CONTROL is a typical structure of software design. In this design structure, an application is divided into three parts. 1. MVC overview
1.1 What is MVC

MVC is short for MODEL_VIEW_CONTROL. MODEL_VIEW_CONTROL is a typical structure of software design. In this design structure, an application is divided into three parts: model, view, and controller. each part is responsible for different functions. Model refers to the data of the application and the operations on the data. view refers to the user interface. the controller is responsible for the synchronization between the user interface and program data, that is, to complete the two actions: 1. update the program data (model) based on the user interface (view) operations. 2. reflect the changes of the program data (model) to the user interface (view) in a timely manner).

1.2 Advantages of MVC

The program structure is clearer and the code stability is enhanced.
Under the MVC mechanism, applications are clearly divided into three parts: model, view, and controller, the three parts correspond to the business logic and data, user interface, user request processing, and data synchronization respectively. We know that for the business logic and data, user interface, user request processing, and data synchronization functions, the user interface is most likely to change, followed by some changes in control, the business logic is the most stable. Therefore, the division of such module functions is conducive to selecting the focus in the code modification process, rather than mixing the code with different functions to cause confusion.

Facilitates division of labor among development teams
The application is divided into three parts: model, view, and controller. it also facilitates the division of labor among the project team members based on their respective expertise, and facilitates parallel development of the three parts and accelerates the project progress.

2. implementation of the MVC mechanism

2.1 Overview

2.1.1 Application Technology
The implementation of MVC in a specific application is closely related to the specific technology of the application. In terms of website development, JAVA is relatively mature and typical. taking an EJB project as an example, most systems may adopt HTML technology and J2EE (Java2, Enterprise Edition) related technologies, including HTML, JSP, JavaBean, EnterpriseJavaBean, and Servlet. These technologies are distributed in the model, view, and controller modules: view uses HTML, JSP, and JavaBean technologies; controller uses Servlet, StatelessSession Bean, and JavaBean technologies; entityBean, Stateless Session Bean, and JavaBean technology may be used in the model section.

However, we are using PHP technology in this project. Therefore, we need to make some trade-offs. On the one hand, we should try to make the logical implementation of the program smoothly migrate to another technical implementation (such as J2EE), but at the same time, we should also consider the limitations of the PHP script language. In terms of object-oriented support, PHP is not of the same grade as the OO language of JAVA, and is much worse than PERL. Fortunately, we are lucky because PEAR in PHP is an object-oriented extension. Using PEAR specifications, we can use some existing PEAR modules, and on the other hand, we can enable our programs to implement business logic according to OO ideas. Therefore, we will discard the modular and procedural programming method, change our thinking, and package everything in a class.

Before introducing the actual design, let's take a look at the requirements of this project.

2.1.2 project requirements
The purpose of this project is to build a website publishing system. The publishing system should be able to support channels, subchannels, topic division, privileged area division, user role division, customization of various channel templates, and article publishing process control ......

2.1.3 hierarchy
Our applications can be divided into three layers: model, view, and controller based on the MVC mechanism. at the same time, we should be able to divide the implementation technology and logical relationship into page presentation modules and business control modules, the transaction management module and the tool module can be divided into four modules according to the specific business. The following describes the two classification methods:

By business module
It consists of five parts: user management, article publishing, template maintenance, foreground display, and system management. Each part corresponds to an aspect of the publishing system. In this way, the model, view, and controller implementation components are distributed in five business modules.

By implementation technology
Because our implementation technology uses HTML and PHP related technologies, we divide the entire application into the page presentation layer, business control layer, transaction management layer, and tool module. In this way, the three-layer structure of MVC is further refined into the above four logic layers.

2.2 page presentation layer

The implementation of this part is the simplest. The template and the render class that instantiate the template.
A template is written in pure HTML without any PHP code or control logic. to be precise, this layer does not involve any commercial logic. its purpose is to select a template, and instance data to generate a complete HTML page.

2.2.1 Template mechanism
We use the IT and ITX modules in PEAR as our TEMPLATE engine because the ITX class is a pure PEAR class and is similar to the TEMPLATE in PHPLIB, however, it is easier to use. In addition, some features of ITX are especially suitable for template customization. considering that our page performance is not so special, the use of ITX can meet our needs.

For more information about ITX, see ITX source code. here is a simple usage description:

New IntegratedTemplateExtention ($ root = "")
Build a function. $ root is the directory for loading template files. Note: There may be a BUG. when using the following function to load the template file, if the file name to be loaded contains a path, the file cannot be found, therefore, we recommend that you set $ root as the template directory and then use the following function to load the template.

LoadTemplatefile ($ filename, $ removeUnknownVariables = true, $ removeEmptyBlocks = true)
To load a template from a specified file, $ removeUnknownVariables indicates whether to remove unused variable identifiers, and $ removeEmptyBlocks indicates whether to remove unused blocks.

SetRoot ($ root)
Set the template directory

SetTemplate ($ template, $ removeUnknownVariables = true, $ removeEmptyBlocks = true)
Load the template from the specified string. This function is useful if you plan to store template data in the database (recommended.

SetCurrentBlock ($ blockname)
Set the block name to be parsed

SetVariable ($ variable, $ value = "")
Set the variable ID value

Parsecurityblock ()
Parse the current block

TouchBlock ($ block)
Sets the specified block so that it is displayed in the output even if it is not used.

Parse ($ block = "_ global _", $ flag_recursion = false)
Parse the specified block

GetBlocklist ()
Obtain the list of blocks in the template.

BlockExists ($ blockname)
Determine whether a specified block exists in the template

2.2.2 template definition

Because ITX is used, the template definition is very simple. To define an HTML block to be instantiated, use {varname} to define the variable to be instantiated. For loops, we do not need to display them on the page, but place them in the render class. we can generate the cyclic HTML code by selecting an HTML block and instantiating it repeatedly. The following is an example:









$ Obj-> setCurrentBlock ('list ');For ($ I = 0; $ I <3; $ I ++ ){$ Obj-> setVariable ('name', 'panfan ');$ Obj-> setVariable ('Sex', 'Boys ');$ Obj-> setVariable ('age', $ I );$ Obj-> parsecurityblock ();}?>

{Name} {Age} {Sex}
The following HTML code is generated:
Panfan0BOY 
Panfan1BOY 
Panfan2BOY

2.2.3 instantiate a template

As shown in the preceding section, different pages are generated by setting different templates and different instantiated data for the render class. Then, how can we associate a template with its corresponding render? This is a good question. To simplify the complicated problem, we did not consider using a universal render that can instantiate all templates and data, because this would make the render logic very responsible, but used a lot of render, each render can instantiate one or more similar templates. Each template has a corresponding render class id. these definitions are pre-defined. We use an xml file to define all templates used in the application. The xml file name is template. xml. its basic structure is as follows:


  Welcome
  Welcome
  True
  Welcome.html
  Common_render  


  Home
  Home
  Home.html
  False  



In this XML file, Defines all templates used in this project, The tag defines some key information about each template:

The fileName attribute defines the path where the template file is stored. name indicates the template name and id indicates the id of the template. UseRender indicates whether to use render for instantiation. if it is false, the php require will be used to generate the page directly. Otherwise, the corresponding render show method will be called to display the page. RenderId is the render ID.

Template. xml is loaded into the system by the init () of the Assitant class. you can use Assitant-> lookupTemplate (templateid) to obtain the templateInfo object of the template, and then use the getRenderId method of the templateInfo object, obtain the render ID, call the lookupRender (renderId) method of Assistant to obtain the render object instance, and then use render-> loadTemplateFile () to load the template file, set template-related data:

Render-> setRenderData (data)

Use render-> show ()

The html page can be instantiated accordingly.

2.2.4 Render

Render is the main class in the presentation layer. As mentioned in the preceding section, a render instance of the corresponding template will be returned in the lookupTemplate of the Assistant object. in xml, we can get the renderid based on the templateid. how can we get a render instance from the renderid? We use another xml file render. xml to obtain the corresponding render information:



SimpleQuery
SimpleQuery
SimpleQuery. php SimpleQueryRender


AdvancedQuery
AdvancedQuery
AdvancedQuery. php
AdvancedQueryRender


QueryList
AdvancedQueryList
AdvancedQuery. php
AdvancedQueryRender


In this XML file, Defines all the render used in this project, The tag defines some key information for each render:

Id: the unique identifier of the RENDER.
Name: defines the render name description, which is consistent with the ID by default.
ClassName: defines the PHP class name of this render, which is unique.
Filename: indicates the PHP file name that implements the RENDER class.

For ease of operation, each render information here is defined as a class: renderInfo

RenderInfo inherits the info class. Definition of info class:

Since the render information is consistent with the attributes provided by the info class, the class definition of renderInfo simply inherits info:
Class renderInfo extends info {
........
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.