Php. MVC Tutorial

Source: Internet
Author: User
Tags locale xml parser
First, preface:
Asp,jsp,php is a web development of the three major technologies, three technical advantages and disadvantages have been analyzed. The ASP is simple and easy to use and has Microsoft backing, JSP powerful because Java support, PHP is open source cross-platform. At home, the most widely used ASP, JSP development momentum, PHP is at a disadvantage. This may be related to the company's support and technical training.
As a result of the company's project needs, I this only contact PHP, after a period of time to experience the most profound, one is easy to learn, quick to use, built-in functions, suitable for rapid development, second, the lack of learning materials, popularization is not wide, often have to read English documents.
For small to medium-sized Web applications, PHP is very competitive, the linux+apache+mysql+php (LAMP) portfolio is almost competent for the majority of Web site solutions, for large applications, the system architecture requirements are higher, need to have mature framework support, The JSP struts is a good framework, the domestic introduction of its data is also very much, the application gradually wide up, The corresponding PHP also has php.mvc, but I searched all over the network also did not find a Chinese document, this let me move the user guide idea, also is a start, I hope PHP can flourish in the country.
Php. MVC is an open-source framework for PHP Web applications that implements model-view-controller (MVC) Design patterns. Industry standards for Web applications that encourage application design based on the MODEL2 architecture. This development pattern allows Web pages or other displays to be detached from internal application code, making it easier for designers and programmers to focus on their respective areas of specialization. This framework provides a separate entry point for the controller. This controller accepts HTTP requests and assigns them to the corresponding action processing according to the configuration file.
The model contains the business logic of the application, and the controller handles the request and turns to the corresponding display component?? A template file that combines HTML and PHP tags. The processing results are returned to the client browser, or through additional protocols such as SMTP.
Php. MVC is using PHP to implement the Jakarta Struts framework, which currently supports many of the features of struts, including declaring application configuration parameters through an XML parser. For example, the mapping between various business logic components and corresponding display components is specified in the XML configuration file.

Php. MVC's website address

Two, PHP. Installation configuration for the MVC series tutorial

Php. MVC must be installed on a Web server in PHP v 4.1.0 and later

Windows (Apache 2.0.51+php-4.3.9-win32)

1. Download the appropriate Apache version from

2. Download the appropriate PHP version from Http://

3. Download the appropriate PHP.MVC version from Http://

4. Create the directory c:\www as the Web server directory, C:\webapp as the Web root directory,
You can also define your own directory, the following changes can be made accordingly.

5. Install Apache to c:\www, open the browser, enter http://localhost in the address bar to test whether the installation is successful
Note: If you have additional Web servers installed on your system (such as IIS 5) and you are using 80 ports, stop the server first.

6. Unzip the PHP package to c:\www.

7. Copy the php.ini-dist from the C:\www\php-4.3.9-Win32 directory to the system directory such as C:\Winnt and rename it to PHP.ini,
Copy the Php4ts.dll to the system directory, such as C:\Winnt\System32, and open the http.conf file in the C:\www\Apache group\apache2\conf directory,
Join under scriptalias/cgi-bin/"C:/www/apache group/apache2/cgi-bin/"
AddType application/x-httpd-php. php
Action application/x-httpd-php "/php/php.exe"
and change DocumentRoot "C:\www\Apache group\apache2\htdocs" to DocumentRoot "C:/webapp"

8. Put PHP. MVC compression Package extracted to C:\webapp

9. Open the C:\webapp\phpmvc directory under the main.php file, 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 '; The
confirms that has writable permissions in the C:\webapp\phpmvc\WEB-INF directory.
Open the browser and enter Http://localhost/phpmvc/Main.php?do=stdLogon in the address bar to test whether the installation was successful.

10. To view the more detailed installation documentation, see Http://

Three, PHP. Introduction to the MVC Series Tutorial:

I. Introduction to
PHP. MVC is an open-source Web application framework that implements the model-view-controller (MVC) design pattern and encourages application design based on the MODEL2 architecture. This development model allows Web pages or other displays to be detached from internal application code, making it easier for web designers and programmers to focus on their respective areas of specialization.
This framework provides a separate entry point for the controller. This controller accepts HTTP requests and assigns them to the corresponding action processing according to 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?? Typically implemented with template files. The processing results are returned to the client browser, or through additional protocols such as SMTP.
PHP. MVC uses PHP to implement the Jakarta Struts framework, which currently supports many of the features of struts, including XML and object mapping through an XML parser, which sets the configuration parameters for the application. For example, the mapping between various business logic components and corresponding display components is specified in the XML configuration file. The logical diagram shown in

Figure 1 depicts the high-level structure of the frame. The
can see that the framework consists of three main components: the front controller, the host controller, and the action allocator.
Second, excellent/disadvantage

1. php. MVC is an open source project that gives you full access to your source code, giving developers a deeper understanding of their internal implementation mechanisms.
2. Use PHP. MVC promotes modular development, separates the roles of developers and designers, and improves the reusability and maintainability of code.
3. php. MVC Framework Learning can draw on some of Jakarta struts knowledge and experience, if you have the experience of developing struts, then you can quickly use PHP. MVC for development.
4. The MVC pattern is a design standard for Java development Web applications, using PHP. The MVC framework also helps web developers understand MVC design patterns.
1. php. The MVC feature is still changing and perfecting, and you need to keep an eye on the latest version.
2. Use PHP. MVC requires an additional learning process.
3. Apply PHP. MVC can get a clear program structure, but it also increases the complexity of the system.
4. Apply PHP. MVC can make programs more organized, but it also slows down program execution.

So you need to decide whether to apply PHP based on the size, periodicity, cost, and quality of the developer. MVC Framework.

Four, PHP. The process of MVC series Tutorials:
Php. The MVC framework is assembled by many classes, but we do not have to understand the detailed working procedures of all classes and can use this framework, and Figure 2 shows some of the core components we need to know about using the framework.

From Figure 2 we can see how a typical Web browser's HTTP request interacts with the core classes of our application framework, and then how to get the HTTP response back to the Web browser.

Now let's take an example to understand the framework's processing flow. For example, to view the company Sales report, first enter in the browser address field
The Http:// client is sent to PHP. MVC application One request. The controller of the application framework handles this request, parses the query string, and takes out the request path keyword. In this instance, the path is salesreport. Later we will see how to configure the required application behavior through an XML configuration file, bind form validation, business logic processing, and display components.
If we want to strictly control that only authenticated people can access this report, the user must first enter Basic authentication information, usually a user name and password. In order to restrict access to the report by only authenticated users, a class called Actionform is used, and we need to inherit the framework's actionform to define our own form validation classes, such as Salesactionform, as follows:
Class Salesactionform extends Actionform {...}.

In the Salesactionform class we check whether the user can be trusted to determine the next action. If the user does not pass the validation, we redirect to the initial page requiring re-entry, and if he passes the validation, the controller invokes the business processing class through the action class.
We customize by inheriting the framework action class, such as Salesaction, as follows:
Class Salesaction extends Action {...}.

In the XML configuration file we define the correspondence between the request and the action class so that the Controller finds the appropriate action class, which is called salesaction. In the Salesaction class we have access to business processing classes and data sources. In this example, we obtain the sales data from the database and make the report format. For example, we create some objects that you can use later in the Sales report template, as follows:

Sales report Items-per Zone (individual object instances):
$item 1 = new Item (' Northern Zone Sales ', $salesNorth);
$item 2 = new Item (' Southern Zone Sales ', $salesSouth);

When we have finished the sales report, we need to specify the display component through the controller. This is done through an object that is already configured in the XML configuration file called Forward, as follows:
return $mapping->findforwardconfig (' salesreportsuccess ');

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

The controller then directs the request to Actiondispatcher, which is directed to the specified display component, in this case SALESREPORT.TPL, in the template by accessing previously defined objects and variables to get the data prepared in salesaction.
The following shows how we use the Phptal template system to access report data and generate display views, objects $item1 We use class variables $item1->value

Finally, the processing results are sent over HTTP to the client browser, thus completing the process.

Five, PHP. The MVC Series Tutorial catalog file

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

Php. MVC Class Library

From what we can see PHP. The MVC Class Library is installed in the server's dev directory, which is used to place some common class libraries. For security reasons, the directory does not allow Web users access, so it is best not to build the directory in the Web root directory. If for some reason PHP is needed. The MVC Class Library is installed in the Web root directory, and you must use the. htaccess file to control its Access objects.
The Apache. htaccess file is displayed below

# 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 the this server.
Order Deny,allow
Deny from all
Allow from localhost

This will instruct the Apache server
Deny everyone access to the directory containing the. htaccess and its subdirectories, in this case the files and subdirectories contained in the/web-inf directory of the Php.mvc class library.
Allows access from the server host, which allows developers of Web servers to browse the test directories under the class library and perform unit tests.

Php. MVC files do not have to be modified to work properly, in order to be able to access the class library file, we need to set the Php.mvc class Coogan directory in the Web application's main.php file as follows:

$appServerRootDir = ' d:/dev/php/phpmvc-base '; No trailing slash

Php. MVC Web Application

From Figure 3 We can see that a Web application directory SalesReport is placed under the Web root directory www.
Under SalesReports, we can see several directories and main.php files, the art directory is used to store the application image, the style directory is used to store the stylesheet, the two directories can be accessed through the web, and can be renamed according to the actual needs. We are able to access these resources in the template file as follows:

Next is the Web-inf directory, which holds the application classes and resources. It cannot be accessed through the web, which is achieved through the. htaccess file. Developers can freely create directories and subdirectories in this directory, but they need to be declared in the modulepaths.php in 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.

In the Web-inf directory there are also. htaccess,modulepaths.php, Phpmvc-config.xml, PHPMVC-CONFIG_1_1.DTD, and prepend.php files. One of the. htaccess files has been discussed earlier.

The modulepaths.php file defines the path to the specified application class and resource, which we can define as follows:

$appDirs = Array ();
$appDirs [] = "; Starting with the Sub-application home directory
$appDirs [] = ' web-inf ';
$appDirs [] = ' web-inf/classes ';
$appDirs [] = ' WEB-INF/TPL ';

The Phpmvc-config.xml file is the central component of the PHP.MVC application, and you can define the behavior and properties of the application through XML, which is described in more detail later.
The Phpmvc-config_1_1.dtd file is a document type definition file for Phpmvc-config.xml, and the DTD file specifies the nodes that can be contained in the Phpmvc-config.xml file, which is the final reference to the behavior and properties of the application. Most XML editors can use DTD files to verify the validity of the Phpmvc-config.xml file.
The file contains some configuration data for the application, which is dynamically generated based on the latest information from the Phpmvc-config.xml file. If your application does not get the expected results, you can add the spacebar in Phpmvc-config.xml to modify it, and the configuration data will be regenerated when you rerun the application.

prepend.php files are commonly used to contain application files, before we have included the application class and template files, which we can use to contain other classes and resource files, as follows:

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

Main.php is the single entry point for the PHP.MVC application, which is placed in the application root directory. All requests need to be done through it.
From the above we can see that the path of the Php.mvc class library must be defined in the main.php file

$appServerRootDir = ' d:/dev/php/phpmvc-base '; No trailing slash

Next we will specify the application path

$moduleRootDir = ' c:/www/salesreports '; No trailing slash

We can also set the Actiondispatcher path for the application. Each PHP. MVC applications typically have to customize a
Actiondispatcher to handle the specified request, we need to define the Actiondispatcher variable as follows:

$actionDispatcher = ' Reportactiondispatcher ';

The $osType variable is used to specify the operating system type of the host on which the PHP.MVC is located, usually the framework is automatically detected and used to set the application path, but if your application runs with a path error, set the variable manually. As shown below:

$osType = ' UNIX ';

Under normal circumstances, other parameters contained in the main.php can be modified without modification.

Six, PHP. Object relationships for the MVC series tutorial

Above is the action class, which is typically used to handle a request to complete an initial assay pass through the Actionform class. We see again that the base class of the inherited action definition Abstractbaseaction,salesreportaction class inherits abstractbaseaction to handle the request, In the Salesreportaction class we can invoke the business logic class Reportbusinessclass to access the database and other resources.

Below is the Actiondispatcher class, which is responsible for preparing display resources such as page templates for action requests. In general, we need to inherit the framework Actiondispatcher class to define our own dispatcher, such as the reportactiondispatcher in the example.

In the following we will have a more detailed introduction

XML application Configuration system

The Phpmvc-config.xml file is the primary configuration component of the PHP.MVC application, and each PHP.MVC application has its own Phpmvc-config.xml file, typically located in the Web-inf directory. Once the file is modified, the controller invokes the XML parser to parse the file, transforming the XML node into a configuration object. These configuration objects are cached in the file and are usually placed in the same directory as the Phpmvc-config.xml. In a later request, the controller will call into the cached file to save the processing time.

In Figure 5 We see how the configuration file relates to the application component, and we define a path property for the action node as SalesReport, which is the access path for the action, such as: Mycompany/main.php?do=salesreport.

In the action node, the Name property is Salesreportform, which tells the controller that we want to handle form validation with a form-bean called Salesreportform. We can see that the Form-bean named Salesreportform is defined in the Form-bean above the Action-mappings node, where the Validate property is true to indicate that the controller calls Form-bean validate (...) Method.

In the action node and the Form-bean node to which it is contacted, there is a type attribute. We use this attribute to define the respective classes of Form-bean and action. For example, the action node defines the Actionform class of the action class as the Salesreportaction,form-bean node as salesreportform.

Next we also need to define the forward node group in the action node to specify the URI of the framework display component, where the Name property defines an identity for the forward node, and the Path property defines the resource or template associated with the action. The first forward node in the example is defined as salesreportsuccess, The resource path is SALESREPORT.TPL, the second is defined as salesreportfailure, the resource path is SALESREPORTINDEX.TPL, and in our class we can use these forward nodes to specify the location of the display resource. In this example, if the report is successfully generated, We process the request with the Salesreportsuccess object and the Salesreport.tpl it defines, and if the report generation fails, we use the Salesreportfailure object and the SALESREPORTINDEX.TPL to process it, typically returning to the initial page.

Phpmvc-config.xml files can be modified with a generic text editor, or with a dedicated XML editor. The dedicated XML editor can use PHPMVC-CONFIG_1_1.DTD to verify the validity of the configuration file, which defines the elements, attributes, and values that are used in the XML file. Information about this can be found in the relevant XML data.

The following is an example Phpmvc-config.xml file:

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

Figure 4 shows PHP from a developer's point of view. The main classes and resources in the MVC sample program, and the relationships between them.

in the upper-left corner is the Actionform class, and we inherit it to handle the validation of HTML forms and the functions associated with them. In the example, a base class abstractbaseform is defined by inheriting Actionform, which contains some common logic that can be referenced for more applications Actionform classes. For example, the Salesreportform class implements the Abstractbaseform class specifically.

We explained PHP earlier. The structure and process of MVC, next, we will focus on the following core components: the

... Seven, PHP. The MVC System Tutorial configuration file XML configuration file is a "switchboard" of the PHP.MVC application that binds components for HTTP requests. The controller consists of some framework classes that are responsible for locating the correct form and action classes and displaying resources for HTTP requests, as defined in the Phpmvc-config.xml file. The Actionform class is typically used to handle Web Forms validation. The action class can access the business processing class, allowing us to focus on the application business flow. Actiondispatcher class manipulation displays the processing of resources.

Sales Report ->value'll appear here
XML configurations and Bindings:phpmvc-config.xml

Eight, PHP. The Controller of the MVC series tutorial

A controller consists of classes that process user requests based on predefined configuration options. A typical user request is as follows:

Php. The MVC controller consists of two parts: the front controller and the controller. When the request arrives, the front-end controller is responsible for installing the application, and the controller processes the request based on the Phpmvc-config.xml configuration properties.

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

Define the application path: This will specify PHP. The MVC class library and the path to the Web application are as follows:
$appServerRootDir = ' c:/www/phpmvc-base ';
$moduleRootDir = ' C:/www/mycompany '; Define the application's Actiondispatcher: We usually need to extend the framework actiondispatcher to define our own dispatcher class:
$actionDispatcher = ' Myactiondispatcher '; Initialize application classpath: In order to load classes and resources, the front controller imports a predefined global path and an application path. We can set the path in/web-inf/modulepaths.php, as follows:
$appDirs = Array ();
$appDirs = ' WEB-INF/REPORT_TPL ';
$appDirs = ' web-inf/report_classes '; Contains the application class: the front controller will import the class files it needs, and we can use the/web-inf/prepend.php file to selectively import some special application class files. As follows:
Include_once './web-inf/mytools/mytools.php '; Configure the application: The front controller will set configuration information for the application, such as the actiondispatcher we defined earlier. Initialize controller: The front controller will now create an Application server instance (Actionserver). Import configuration information: The front controller will now import the application configuration information, and if Phpmvc-config.xml has been modified since the last request, the Phpmvc-config.xml file will be re-processed and the data will be cached to/web-inf/ The Initialize HTTP request: The front controller will now set the HTTP request and add the request properties. Invoking the application controller: the front controller has now completed the preparation and will hand over the processing power to the controller.

The controller receives a request from the front-end controller and performs a series of actions based on the configuration properties.

Handle the action path: The controller identifies the keyword based on the request path and selects an action map. For example, the request path is:
Http://, the action path is salesreport.

Processing site: Select a locale for the current user as needed to process the content format: format content as needed, default to text/html. Processing does not cache: Set not cache header information as needed, default:
"Pragma", "No-cache"
"Cache-control", "No-cache"
"Expires", 1 processing preprocessing tasks: You can override this method in a custom Actionserver subclass to perform some of the specified preprocessing tasks. Handling Action Mappings: The controller will identify the action map based on the request and generate the action mapping object (Actionconfig) based on the corresponding node of Phpmvc-config.xml, for example:. Processing role: Check all required certifications that can perform this action. Handling Actionform: The controller will find the associated Actionform,form-bean based on the action map, which is specified by the action's Name property, for example:
。 Handling populate: Sets the properties of the Actionform instance based on the request parameters. Verify Actionform: Determines whether to call Actionform's validate () method based on the Validate property value of the action, such as:. If validate () returns False (validation fails), the controller displays an error with the Display resource (template) specified by the input property in action, such as:
Validate = "true"
input = reportsindex.tpl>
If validate () returns True (validation passed), processing will continue. Handle forward: The controller checks whether the URI of the forward map is normal, and if so, continues processing. Processing include: The controller checks if the URI of the include map is normal, and if so, continues processing. Handle Action Creation: The controller creates or obtains an action instance to handle the request, which is defined by the Type property of the action, such as:
Type = "Salesreportaction"
... Handle action execution: The controller will now invoke the Execute () method of the action class, such as Salesreportaction->execute (...). Within this method, we will invoke the business processing logic class. Handle the action chain: The controller checks to see if there is another action to handle, and 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 for the forward element of the action node, such as:
Type = "Salesreportaction"

Name = "Salesreportsuccess"
Path = "Salesreport.tpl"
Nextactionpath = "SalesReport2"/>
The path property of the forward element is a must, and if this special action has no output, we can set path = "". Handle Action Forward: The controller forwards or redirects to the specified resource, and a Forward request is processed in the current processor. Requestprocessor just gives control to Actiondispatcher, which contains the specified URI template. Like what:

Name= "Forward_path
Path= "Forwardrequest"
Redirect= "false"/> The redirect request is actually sent to the client browser with a header response and then redirected to a new URL. The current processing terminates immediately when the redirect header information is sent.

Name= "Redirect_path
Path= "/myapp/main.php?do=newrequest"
Redirect= "true"/>

Name= "Redirect_path
Path= "Http://"
Redirect= "true"/>

If no other action needs to be handled, the controller processing is finished.

  • Related Article

    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.