PHP-Web application development: use templates

Source: Internet
Author: User
Tags php template
Every developer who has performed large-scale PHP-Web application design has the following experiences: spend a lot of time writing Hypertext statements, formatting pages, and doing an artist; or it takes a lot of time for the integrated program code to work with HTML static pages. Indeed, it is not easy to separate data processing from data display when developing Web applications using scripting language.

Every developer who has performed large-scale PHP-Web application design has the following experiences: spend a lot of time writing Hypertext statements, formatting pages, and doing an artist; or it takes a lot of time for the integrated program code to work with HTML static pages. Indeed, it is not easy to separate data processing from data display when developing Web applications using scripting language. However, when multiple people work together, if data and display cannot be separated, the development efficiency will be greatly affected and the professional division of labor will be realized. To solve this problem, PHP also provides its own solutions. This article mainly introduces the Template class in PHPLIB.

1. template processing design
The template processing class mainly needs to complete the following tasks:
· Read the HTML code used for display from the template file.
· Combine template files with actually generated data to generate output results.
· Multiple templates can be processed simultaneously.
· Allows template nesting.
· Allows processing of a separate part of the template.

To sum up the preceding tasks, the template class is designed to read the displayed HTML code from multiple template files, replace the dynamic data in the display code with the data calculated by the PHP program, and then output the data in a certain order. The replacement part can be set freely.

The HTML code used to read the Display adopts the file reading method.
Template files and data are replaced with regular expressions.
Processing multiple templates is implemented using array storage.
The main idea of implementing template nesting is to treat the template and the output (any intermediate analysis results) equally, and they can be replaced.
Individual parts are processed by setting tags in the template file, and then using tags in regular expression replacement to control partial replacement.

2. implementation of the template processing class
See Template. inc in PHPLib for a total of 345 lines of code with detailed comments. The following lists some major functions for your reference:
1) function set_file ($ handle, $ filename = "") line 77, read the file
2) function set_var ($ varname, $ value = \ "\") line 119, set ING data-replace variable
3) function set_block ($ parent, $ handle, $ name = \ "\") line 96, set annotation
4) function subst ($ handle) line 136, execute data replacement
5) function parse ($ target, $ handle, $ append = false) line 165, execution template file and data combination
6) function p ($ varname) line 268, output the processing result
Note: The 95th rows in the Template. inc file of the php-lib7.2c I downloaded are missing a slash (/), and the use is normal after the addition.

3. use of the template processing class
3.1 Basic example
For the sake of simplicity, it is assumed that the template file, the PHP file using the template, and the template processing class files are all placed in the same directory. In PHPLIB, the habit is to use the ihtml suffix as the template file suffix.
The following is the template file to be used:




Test with template


This is a test file using the template!
The current time is {currenttime }!


Note: The template file is similar to the common HTML file. The only difference is that "{}" is used to enclose variables of dynamic content that can be replaced by the template processing class.

Next, use the template processing class to process the preceding template:
// Introduce the Template class
Include (\ "template. inc \");

// Obtain the data to be replaced
$ TimeNow = date (\ "Y-m-d H: I: s \", time ());

// Instantiate a Template class
$ Template = new Template ();

// Load the test. ihtml Template
$ Template-> set_file (\ "handle1 \", \ "test. ihtml \");

// Replace the currenttime in the template with the value of $ timeNow
$ Template-> set_var (\ "currenttime \", $ timeNow );

// Perform the actual template operation
$ Template-> parse (\ "output \", \ "handle1 \");

// Output the final result
$ Template-> p (\ "output \");
?>


Note: If you only want to use the Template class in PHPLIB, you only need to include the Template. inc class in the file header.
When creating a Template object, you can specify the Template file path, for example, new Template ("/htdocs/apps/templates/"). The default path is the current path.

3.2 template nesting and block setting
The following example is from the reference manual with PHPLIB, which is comprehensive. here we need to explain that the purpose of setting blocks is not related to nesting, but this example includes both. Please read carefully. The Block setting is to avoid this situation: the content that can be originally completed in a template file (static page), because part of the loop is required, and extract part of the cyclic content into a template file separately. Think about it. if block settings are not required, does this example require three template files?
Template File 1, page. ihtml


{PAGETITLE}









{PAGETITLE}
{OUT} Content


Template File 2, box. ihtml










{TITLE}
{NUM} {BIGNUM}

Template processing file, test. php
// Introduce the Template class
Include (\ "template. inc \");

# Instantiate a Template class named $ t
$ T = new Template ();

# Create an array containing template files
$ T-> set_file (array (
\ "Page \" => \ "page. ihtml \",
\ "Box \" => \ "box. ihtml \"));

# Load a row in the template file box with the reference name rows
$ T-> set_block (\ "box \", \ "row \", \ "rows \");

# Set replacement
$ T-> set_var (array (\ "TITLE \" => \ "Testpage \",
\ "PAGETITLE \" => \ "hugo \"));

# Generate data NUM and BIGNUM
For ($ I = 1; $ I <= 3; $ I ++ ){
$ N = $ I;
$ Nn = $ I * 10;
# Set replacement
$ T-> set_var (array (\ "NUM \" => $ n, \ "BIGNUM \" => $ nn ));
# Analyze and add the analysis result to the end of rows
$ T-> parse (\ "rows \", \ "row \", true );
}

# Generate a box and then generate a page
$ T-> parse (\ "OUT \", array (\ "box \", \ "page \"));

# Output the final result
$ T-> p (\ "OUT \");
?>


Note: The variable naming and the final output handle in the page. ihtml template file use "OUT ".
The circular value part uses the database class to combine data generation with database applications.
The execution result is as follows:


Execution result chart of template nesting and block setting

4. Summary
This article briefly introduces the design, implementation and usage of the Template class in PHPLIB. Of course, there are many other PHP template schemes, such as FastTemplates evolved from Perl. At present, the Internet team is using another solution. the main implementation method is to store template files into the database, and to use eval to combine data with template files, template file management and template processing are relatively simple, but the file storage mode is missing. Some of my current attempts are to combine the two and try to improve them on the basis of the PHPLIB Template class. There are two initial target tasks: 1. expand the database support when reading template files, in this way, you can increase flexibility and use database management tools when necessary. 2. simplify the combination of template files and data, in most cases, you do not need to set the variables in the template file in the processing program (data variable ing.
We also hope that readers and PHP programmers will join us and give more valuable comments. good luck!

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.