PHP. MVC tutorial

Source: Internet
Author: User
Tags xml parser
I. Preface:
ASP, JSP, and PHP are three major web development technologies. Some people have analyzed the advantages and disadvantages of these three technologies. This is nothing more than ASP, which is easy to use and Microsoft is a reliable tool. jsp is powerful because it supports Java and PHP is open-source and cross-platform. In China, Asp has the widest application scope, JSP has the strongest development momentum, and PHP is at a disadvantage. This may be related to the company's support and technical training.
Due to the needs of the company's projects, I have come into contact with PHP. After a while, I have two profound experiences. One is easy to learn, quick to use, and many built-in functions, which are suitable for rapid development; second, there is a shortage of learning materials, which is widely used. Many times I have to read English documents.
For small and medium-sized web applications, PHP is very competitive. The combination of Linux + Apache + MySQL + PhP (LAMP) is almost competent for the solutions of most websites. For large applications, for systems with higher architecture requirements, mature framework support is required. jsp struts is a good framework. There are a lot of materials about it in China, and its application is becoming more and more popular, the corresponding PHP also has PHP. MVC, But I searched the internet and did not find a Chinese document. This gave me the idea of translating user guides, and I hope PHP will flourish in China.
PHP. MVC is a PHP Web application. Program An open-source framework that implements the Model-View-controller (MVC) design model-industrial standards for Web applications, and encourages Application Design Based on the model2 architecture. This development mode allows web pages or other display content from internal applications Code To make it easier for designers and programmers to concentrate on their respective areas of expertise. This framework provides a single entry point controller. The Controller accepts HTTP requests and assigns them to corresponding actions based on the configuration file.
The model contains the business logic of the application. The Controller is responsible for processing requests and turning to the corresponding display component-a template file that combines HTML and PHP tags. The processing result is returned to the client browser, or through another protocol such as SMTP.
PHP. MVC uses PHP to implement the Jakarta Struts framework. Currently, it supports many struts features, including declaring application configuration parameters through the XML parser. For example, you can specify the ing between various business logic components and corresponding display components in the XML configuration file.

Web address for PHP. MVC

Ii. installation and configuration of PHP. MVC series tutorials

PHP. MVC must be installed on PHP v 4.1.0 and later Web servers.

Windows (APACHE 2.0.51 + php-4.3.9-Win32)

1. Download the apache version from

2. Download the corresponding PHP version from

3. Download the corresponding PHP. MVC version from

4. Create the directory c: \ www as the Web Server Directory and c: \ webapp as the Web root directory,
You can also define your own directory and modify it as follows.

5. install Apache on c: \ www. Open the browser and enter http: // localhost in the address bar to test whether the installation is successful.
Note: If you have installed other Web servers (such as IIS 5) on your system that occupy port 80, stop the server first.

6. decompress the PHP compressed package to c: \ www.

7. Copy the php. ini-Dist under the c: \ www \ php-4.3.9-Win32 directory to the system directory such as C: \ WINNT and rename it PHP. ini,
Copy php4ts. DLL to the system directory, for example, C: \ winnt \ system32. Open the HTTP. conf file in the C: \ www \ apache group \ apache2 \ conf directory,
Under ScriptAlias/cgi-bin/"C:/www/Apache Group/apache2/cgi-bin/", add
ScriptAlias/PHP/"C: // www/php-4.3.9-Win32 /"
Addtype application/X-httpd-PHP. php
Action application/X-httpd-PHP "/PHP/php.exe"
Change DocumentRoot "C: \ www \ apache group \ apache2 \ htdocs" to DocumentRoot "C:/webapp"

8. decompress the php. MVC package to c: \ webapp.

9. Open the main. php file in the C: \ webapp \ phpmvc directory and modify the following content:
// Set PHP. MVC library root directory
$ Appserverrootdir = 'C: \ webapp \ phpmvc '; // no trailing slash
// Set the Application Path
$ Modulerootdir = 'C: \ webapp \ phpmvc '; // no trailing slash

// Set the OS type [Optional] [UNIX | Windows | Mac] If we have
// Trouble detecting the Server OS type. eg: path errors.
$ Ostype = 'windows ';
Check that the WEB-INF under the c: \ webapp \ phpmvc \ directory has write permission.
Open your browser and enter http: // localhost/phpmvc/Main. php in the address bar? Do = stdlogon to test whether the installation is successful.

10. For more detailed installation documentation, please refer to the Doc = All.

Iii. Introduction to the framework of PHP. MVC series Tutorials:

1. Introduction
PHP. MVC is an open Source Code Web application framework that implements the Model-View-controller (MVC) design mode, application Design Based on the model2 architecture is encouraged. This development mode allows web pages or other display content to be separated from internal application code, making it easier for web designers and programmers to concentrate on their respective areas of expertise.
This framework provides a single entry point controller. The Controller accepts HTTP requests and assigns them to corresponding actions based on the configuration file. The model contains the business logic of the application. When the request processing is complete, the Controller calls the corresponding display component, which is usually implemented using a template file. The processing result is returned to the client browser, or through another protocol such as SMTP.
PHP. MVC uses PHP to implement the Jakarta Struts framework. Currently, it supports many struts features, including ing between XML and objects through the XML parser, so as to set application configuration parameters. For example, you can specify the ing between various business logic components and corresponding display components in the XML configuration file.

The logic diagram shown in Figure 1 describes the high-level structure of the Framework.
The framework consists of three main components: front-end controller, master controller, and Action distributor.
Ii. advantages/disadvantages

1. php. MVC is an open-source project that allows you to fully access the source code, allowing developers to gain a deeper understanding of its internal implementation mechanism.
2. Using PHP. MVC can promote modular development, promote separation of roles between developers and designers, and improve code reusability and maintainability.
3. Learning the php. MVC framework can draw on some knowledge and experience of Jakarta Struts. If you have the struts development experience, you can quickly use PHP. MVC for development.
4. the MVC mode is a design standard for Java to develop Web applications. Using the php. MVC framework also helps web developers understand the MVC design mode.
1. php. MVC features are still being updated and improved. You need to keep yourself updated with the latest version.
2. php. MVC requires additional learning processes.
3. The application of PHP. MVC can get a clear program structure, but it also increases the complexity of the system.
4. The application of PHP. MVC can make the program more organized, but also reduce the program execution speed.

Therefore, you need to decide whether to apply the php. MVC framework based on the project size, cycle, cost, developer quality, and many other conditions.

4. Process of PHP. MVC series Tutorials:
The PHP. MVC framework is composed of many classes, but we can use this framework without having to know the detailed working process of all classes. Figure 2 shows some core components We Need To Know when using this framework.

Figure 2 shows how the HTTP request of a typical web browser interacts with the core class of our application framework, and then returns an HTTP Response to the Web browser.

Now, let's take an instance to understand the framework's processing process. For example, to view the company sales report, enter
Http:// The DO = salesreport client sends a request to the php. MVC application. The Controller of the application framework processes this request, analyzes the query string, and retrieves the Request Path keyword. In this instance, the path is salesreport. Later we will see how to configure necessary application behavior, bind form verification, business logic processing, and display components through the xml configuration file.
If you want to strictly control that only authenticated users can access this report, you must first enter the basic authentication information, usually the user name and password. To limit that only authenticated users can access the report, an actionform class is used here. We need to inherit the actionform of the framework to define our form verification class, such as salesactionform, as follows:
Class salesactionform extends actionform {...}.

In the salesactionform class, we need to check whether the user can trust it to determine the next action. If the user does not pass the verification, we will redirect to the initial Page to request re-input; if the user passes the verification, the Controller will call the business processing class through the action class.
We inherit the framework action class for customization, such as salesaction, as shown below:
Class salesaction extends action {...}.

In the xml configuration file, we need to define the correspondence between the request and the action class. In this way, the controller finds the corresponding action class, where salesaction is called. In the salesaction class, we can access the business processing class and data source. In this example, we obtain the sales data from the database and make the report format. For example, we create some objects which can be used later in the sales report template, as shown below:

// Sales report items-per zone (individual object instances ):
$ Item1 = new item ('Northern zone sales', $ salesnorth );
$ Item2 = new item ('Southern zone sales', $ salessouth );
When the sales report is completed, the display component must be specified by the Controller. This is done through an object configured in the XML configuration file called forward, as shown below:
Return $ mapping-> findforwardconfig ('salesreportsuccess ');

The forward object contains the path of the sales report template, such as salesreport. TPL, which is also defined in the configuration file.

The Controller then redirects the request to actiondispatcher and directs it to the specified display component. In this example, salesreport is used. TPL: in the template, you can access the previously defined objects and variables to obtain the data prepared in the salesaction.
The following shows how to use the phptal template system to access report data and generate a display view. Object $ Item1 we use the class variable $ Item1-> Value
<! -- // Sales report items-per zone (individual object instances): -->

<Table class = 'salestable'>
<TD class = 'salesitemdesc' tal: content = "Item1/salesnorth">
Sales Report-> value will appear here </TD>

Finally, the processing result is sent to the client browser through HTTP, thus completing the entire processing process.

V. Directory files of PHP. MVC series tutorials

Now let's analyze the structure of a typical PHP. MVC web application.

Figure 3 shows how to deploy a PHP. MVC application and its core class library

PHP. MVC class library

We can see that the php. MVC class library is installed in the dev directory of the server, which is used to place some common class libraries. For the sake of security, this directory is not accessible to Web users, so it is best not to create this directory in the Web root directory. If you need to install the php. MVC class library in the web root directory for some reason, you must use the. htaccess file to control its access objects.
The following shows the Apache. htaccess file.

# Options the. htaccess files in directories can override.
# Edit Apache/CONF/httpd. conf to AllowOverride in. htaccess
# AllowOverride authconfig

# Stop the directory list from being shown

# Controls who can get stuff from this server.
Order deny, allow
Deny from all
Allow from localhost

This indicates the Apache server
Deny all access to the Directory containing this. htaccess and its subdirectories, in this example is the php. MVC class library/WEB-INF directory contains files and subdirectories.
Access is allowed from the server host, which allows web server developers to browse the test directory under the class library and execute unit tests.

PHP. the MVC file can be used normally without any modifications. To access the class library file, we need. set PHP. the MVC library root directory is as follows:

$ Appserverrootdir = 'd:/dev/PHP/phpmvc-base'; // no trailing slash

PHP. MVC Web Application

From figure 3, we can see that the salesreport directory of a Web application is placed under the web root directory www.
In the first-level directory under salesreports, we can see several directories and Main. the PHP file and the art directory are used to store application images, and the style directory is used to store style sheets. These two directories can be accessed through the web and renamed as needed, we can access these resources in the template file as follows:

<LINK rel = 'stylesheet 'Type = 'text/CSS 'href = "./style/mystyles.css">

Next is the WEB-INF Directory, which stores application classes and resources. It cannot be accessed through the web, which is implemented through the. htaccess file. Developers can freely create directories and subdirectories under this directory, but need to declare in modulepaths. php under the WEB-INF directory. In the WEB-INF directory, the class directory is used to store application classes and resource files, and the TPL directory is used to store display resources, such as web templates.

There are also. htaccess, modulepaths. php, WEB-INF, phpmvc-config.xml, phpmvc-config_1_1.dtd and prepend. php files under the directory. The. htaccess file has been discussed earlier.

The modulepaths. php file is used to define the path of the specified application class and resource, which can be defined as follows:

$ Appdirs = array ();
$ Appdirs [] = ''; // starting with the sub-application home directory
$ Appdirs [] = 'web-INF ';
$ Appdirs [] = 'web-INF/class ';
$ Appdirs [] = 'web-INF/TPL ';

The phpmvc-config.xml file is a central component of the php. MVC application. You can use XML to define the behavior and attributes of the application, which will be described in more detail later.
The phpmvc-config_1_1.dtd file is the document type definition file for the phpmvc-config.xml, which specifies the nodes that can be included in the phpmvc-config.xml file and is the final reference to application behavior and properties. Most XML editors can use DTD files to validate phpmvc-config.xml files.
The file contains some configuration data for the application that is dynamically generated based on the latest information in the phpmvc-config.xml file. If your application does not get the expected results, you can add a Space key in the phpmvc-config.xml to modify it and the configuration data will be regenerated when you re-run the application.

Prepend. php files are often used to include application files. We have already included application classes and template files. We can use them to include other classes and resource files, as shown below:

Include_once 'locale. php ';
Include_once 'propertymessageresources. php ';

Main. php is the single entry point of the php. MVC application, which is placed in the application root directory. All requests must be completed through it.
From the above we can see that the main. php file must define the path of the php. MVC class library.

$ Appserverrootdir = 'd:/dev/PHP/phpmvc-base'; // no trailing slash

Next, we will specify the Application Path

$ Modulerootdir = 'C:/www/salesreports '; // no trailing slash

You can also set the actiondispatcher path of the application. Every PHP. MVC application usually needs to customize
Actiondispatcher to process the specified request. We need to define the actiondispatcher variable, as shown below:

$ Actiondispatcher = 'reportactiondispatcher ';

$ Ostype variable is used to specify PHP. the operating system type of the host where MVC is located. Generally, the framework can automatically detect and set the Application Path. However, if a path error occurs during your application running, set this variable manually. As follows:

$ Ostype = 'unix ';

Normally, other parameters contained in Main. php can be left unchanged.

Vi. Object relationship of PHP. MVC series tutorials

Figure 4 shows the main classes and resources in the PHP. MVC sample program and their relationships from the developer's perspective.

The actionform class is in the upper left corner. We inherit it to process HTML form verification and related functions. In this example, a base class abstractbaseform is defined by inheriting actionform. It contains some general logic and can be referenced by more application actionform classes, for example, the salesreportform class implements the abstractbaseform class.

At the top is the action class, which is usually used to process requests that have completed initialization verification through the actionform class. We can see the base class abstractbaseaction inherited from the action definition. The salesreportaction class inherits abstractbaseaction to process requests. In the salesreportaction class, we can call the business logic class reportbusinessclass to access databases and other resources.

Below is the actiondispatcher class, which prepares to display resources such as webpage templates for Action requests. Generally, we need to inherit the actiondispatcher class of the framework to define our own dispatcher, for example, reportactiondispatcher In the example.

We will give a more detailed introduction later.

VII. configuration file of PHP. MVC system tutorial

We have explained the structure and process of PHP. MVC. Next, we will focus on the following core components:

    • The xml configuration file is the "distribution board" of the php. MVC application and binds components for HTTP requests.
    • The Controller is composed of some framework classes, which are responsible for finding the correct form and action classes for HTTP requests and displaying resources.
    • Defined in phpmvc-config.xml files.
    • The actionform class is usually used to process web form verification.
    • The action class can access the business processing class, allowing us to focus on the application business flow.
    • The actiondispatcher class controls the processing of display resources.

XML application configuration system

The phpmvc-config.xml file is the main Configuration component of the php. MVC application, and each PHP. MVC application has its own phpmvc-config.xml file, usually located under the WEB-INF directory. Once this file is modified, the Controller will call the XML parser to parse the file and convert the XML node into configuration objects that are cached in the file, it is usually placed in the same directory as the phpmvc-config.xml. In subsequent requests, the Controller calls the cached file to save the processing time.

Figure 5 shows how the configuration file is associated with the application component. We have defined a path attribute for the Action node as salesreport, which is the access path of the action, for example: Do = salesreport.

In the Action node, the name attribute is salesreportform, which tells the Controller to use a form-bean named salesreportform to process form verification, we can see that form-bean named salesreportform is defined in form-bean on the action-mappings node, the validate attribute is true, indicating that the Controller will call the validate (...) of form-bean (...) method.

Both the Action node and the form-bean node associated with it have the type attribute. We use this attribute to define the classes corresponding to form-bean and action. For example, the Action node defines the action class as salesreportaction, And the actionform class of the form-bean node is salesreportform.

Next, we also need to define the forward node group in the Action node to specify the uri of the framework display component. The name attribute defines an identifier for the forward node, the path attribute defines the resources or templates associated with this action. In the example, the first forward node is defined as salesreportsuccess, and the resource path is salesreport. TPL, the second definition is salesreportfailure, and the resource path is salesreportindex. TPL: in our class, we can use these forward nodes to specify the resource location to display. In this example, if the report is successfully generated, we use the salesreportsuccess object and the salesreport it defines. TPL to process the request. If the report generation fails, we use the salesreportfailure object and salesreportindex. TPL is usually returned to the initial Page.

Phpmvc-config.xml files can be modified with a general text editor, or with a dedicated XML editor. The dedicated XML editor can use a phpmvc-config_1_1.dtd to validate the configuration file, which defines the elements, attributes, and values that are used in the XML file. For more information, see XML.

The following is the sample phpmvc-config.xml file:

XML configurations and bindings: phpmvc-config.xml
<? XML version = "1.0" encoding = "ISO-8859-1"?> <! Doctype phpmvc-config public "-// phpmvc // DTD phpmvc configuration 1.0 // en "". /phpmvc-config_1_1.dtd "> <phpmvc-config> <form-beans> <form-bean name =" salesreportform "type =" salesreportform "/> </form-beans> <action-mappings> <action Path = "salesreport" type = "salesreportaction" name = "salesreportform" Scope = "request" Validate = "true"> <forward name = "salesreportsuccess" Path = "salesreport ". TPL "/> <forward name =" salesreportfailure "Path =" salesreportindex. TPL "/> </Action-mappings> </phpmvc-config>

8. Controller for PHP. MVC series tutorials

A controller consists of several classes that process user requests based on predefined configuration options. A typical user request is as follows:
Http:// Do = salesreport.

The PHP. MVC controller consists of the front-end controller and controller. When the request arrives, the front-end controller installs the application, and the controller processes the request based on the configuration properties of the phpmvc-config.xml.

User requests are received by the main. php file. Here, some initialization parameters are set. The front-end controller performs the following tasks:

    • define the Application Path: This specifies the PHP. the MVC class library and Web Application Path are as follows:
      $ appserverrootdir = 'C:/www/phpmvc-base';
      $ modulerootdir = 'C: /www/mycompany ';
    • define the actiondispatcher of an Application: we usually need to extend the actiondispatcher framework to define our own dispatcher class:
      $ actiondispatcher = 'myactiondispatcher ';
    • initialize the application class path: To load classes and resources, the front-end controller imports the predefined Global Path and Application Path. We can in/WEB-INF/modulepaths. set the path in PHP as follows:
      $ appdirs = array ();
      $ appdirs = 'web-INF/report_tpl ';
      $ appdirs = 'web-INF/report_classes';
    • include application class: the front-end controller will import the class file it requires, and we can also use/WEB-INF/prepend. PHP file to selectively import some special application class files.
      include_once './WEB-INF/mytools. php';
    • Configure the application: the front-end controller sets the configuration information for the application, such as the actiondispatcher we previously defined.
    • initialize the Controller: the front-end controller now creates an application server instance (actionserver ).
    • Import configuration information: the front-end controller will now Import Application configuration information, if the phpmvc-config.xml is modified from the last request, the phpmvc-config.xml file will be reprocessed and the data will be cached in/WEB-INF/
    • initialize the HTTP request: the front-end controller now sets the HTTP request and adds the request attribute.
    • call the application Controller: the front-end controller is now ready, and the processing permission is handed over to the Controller.

The Controller receives requests from the front-end controller and performs a series of operations according to the configuration attributes.

Process Action path: the Controller identifies the keyword Based on the Request Path and selects an action ing. For example, the Request Path is:
Http:// Do = salesreport, and the action path is salesreport.

  • Processing Site: select a locale for the current user as needed
  • Processing content format: Set the content format as needed. The default format is text/html.
  • Non-Cache processing: Set the non-Cache header information as needed. The default value is:
    "Pragma", "No-Cache"
    "Cache-control", "No-Cache"
    "Expires", 1
  • Process preprocessing tasks: You can overwrite this method in the Custom actionserver subclass to execute some specified preprocessing tasks.
  • Process Action ing: the Controller identifies action ing based on requests and generates action config ing objects (actionconfig) based on the corresponding node of the phpmvc-config.xml, such as: <action Path = "salesreport".../>.
  • Processing role: Check all required certifications that can execute this action.
  • Process actionform: the Controller will find the associated actionform based on the action ing. Form-bean is specified by the action name attribute, for example:
    <Action... name = "salesreportform".../>.
  • Process populate: Set the attributes of the actionform instance based on the request parameters.
  • Verify actionform: determines whether to call the validate () method of actionform based on the value of the validate attribute of action, for example, <action validate = "true".../>. If validate () returns false (Verification Failed), the Controller will use the display Resource (Template) specified by the INPUT attribute in action to display an error, for example:
    <Action Path = "salesreport"
    Validate = "true"
    Input = reportsindex. TPL>
    If validate () returns true (Verification passed), the processing will continue. Process forward: the Controller checks whether the URI mapped to forward is normal. If yes, continue processing.
  • Processing include: the Controller checks whether the uri of the include ing is normal. If yes, continue processing.
  • Process Action creation: the Controller will create or obtain an action instance to process this request. This is defined by the Type attribute of action, for example:
    <Action Path = "salesreport"
    Type = "salesreportaction"
  • Process Action execution: the Controller will now call the execute () method of the action class, for example, salesreportaction-> execute (...). In this method, we will call the business processing logic class.
  • Processing action chain: the Controller will check whether another action needs to be processed. In the application configuration file, we can define a series of actions through actionchain. In order to define actionchain, you need to add a nextactionpath attribute to the forward element of the Action node, for example:
    <Action Path = "salesreport"
    Type = "salesreportaction"
    Name = "salesreportsuccess"
    Path = "salesreport. TPL"
    Nextactionpath = "salesreport2"/>
  • The path attribute of the forward element is required. If this special action has no output, we can set Path = "".
  • Processing action forward: the Controller forwards or redirects to the specified resource, and a forward request is processed in the current processor. Requestprocessor only gives control to actiondispatcher, which contains the specified URI template. For example:
    Name = "forward_path
    Path = "forwardrequest"
    Redirect = "false"/>
  • The redirection request is actually sent to the client browser with a header response and then redirected to a new URL. The current processing will be terminated immediately when the redirection header information is sent.
    <! -- This server -->
    Name = "redirect_path
    Path = "/MyApp/Main. php? Do = newrequest"
    Redirect = "true"/> <! -- This server, or a remote server -->
    Name = "redirect_path
    Path = " Do = newrequest"
    Redirect = "true"/>

If no other action needs to be processed, the Controller completes processing.

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: 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.