MVC schema learning in PHP5 _ PHP Tutorial

Source: Internet
Author: User
MVC structure learning in PHP5. I. introduction: when developing WEB applications, one of the most popular practices is to use the "MVC" structure to develop WEB applications in this way, which is logical and simple, enable 1. introduction

Currently, when developing WEB applications, one of the most popular practices is to use the "MVC" structure to develop WEB applications in this way, which is logical and simple, it makes program design more convenient and convenient. What is "MVC? Simply put, it is a combination of "Model", "View", and "Controller", that is, all the three-layer abstract structures, of course, the "MVC" mentioned here is for WEB applications. "separating code from page design" is the dominant idea, this idea is fully embodied in the "Struts" of the Java Servlet/JavaServer Pages technology. if you are interested, you can refer.

From the introduction of PHP5, we can see that the object-oriented functions are becoming more and more perfect. using PHP to develop large commercial websites or distributed enterprise applications has become possible. if Zend Optimizer is used together, code Encapsulation has been implemented.

How can we develop WEB applications using the "MVC" design pattern in PHP? Remember one thing (separate code from page design) and use a simple example to demonstrate it. for example, if you want to query member information from the database to display on the webpage, you need to consider two points here: 1. connect to the database and retrieve the member information. display member information on the webpage. connect to the database and use a database class. Call it a "DB" class. This Class assumes the role of "Model) then we need to write a program that operates the "DB" class to retrieve data. The role of this program is "Controller )", it accepts the client's "POST" or "PUT" data, then calls the "DB" class to retrieve the data, and stores the data in the "Controller, finally, pass the data to the "View" and display it in a certain typographical format. from the analysis above, we can see that the template plays the role of "View) "Of course, only one template class cannot be said to be MVC. The real MVC is not so simple. for details, refer to" JSF ".

"3 T" is a template class. it mainly reads "Controller" data and performs some special processing. Finally, it displays the data through some simple template syntax, what features does it have?

Fast resolution. you can choose to use html or php Cache as needed. of course, you can also achieve fast and stable WEB applications without caching.

It is easy to use and easy to install. in terms of data reading, it is similar to the famous template class "SMARTY". In terms of data display, it is similar to "PHP syntax" and "JavaBeans"

Good scalability. you can add the desired feature at any time as needed because it is open-source and will support the plug-in feature in the near future.

Good scalability and support for the latest PHP5, as long as your PHP version is> = 4.0.6. of course, you need to have the permission to operate files on the server.

Powerful functions, supporting multi-level nesting of templates, multi-level loop of arrays, etc.

Of course, this template still needs to be improved in many ways and can be continuously improved only when tested and used in various environments. Currently, it is only tested in LINUX and WINDOWS environments.

II. Installation

1. after decompression, you can see the following directory structure:

./3tx. x/cmp/compiled files (make sure this folder can be read and written)
./3tx. x/tpl/template file (the template files are put here to make sure the folder is readable)
./3tx. x/che/folder where cached files are stored (make sure this folder can be read and written)
./3tx. x/ttt. php 3 T template class file
./3tx. x/program File (all programs you write are stored here)

2. your PHP version cannot be lower than PHP4.0.6. I suggest you upgrade your PHP version to version 4.3.0 or above, and the overall performance of the program will be greatly improved.

3. if the variable is undefined during runtime, add "error_reporting (7);" function before the program.

III. Syntax

Simple template syntax description:
Generally, the left braces "{" and right braces "}" are used as the start and end of the template syntax. of course, you can also use custom delimiters, such as "[" and "]", the following description is separated by braces.

(Note: the code in the middle of [tplCode] and [/tplCode] Below is the template syntax code)

1. use PHP code in the template file, such:
[TplCode]
{Php}
$ I = 3;
Echo $ I;
{/Php}
[/TplCode]
See "example6"

2. use the foreach loop in the template, for example:


First usage (loop array $ a, equivalent to foreach ($ a as $ k => $ v) in PHP )....)
[/TplCode]
{Foreach: $ a, $ k, $ v}
$ V = {$ v}

{/Foreach}
[/TplCode]

Second usage (you can set the number of cycles. If the array $ a has 15 elements, the following loop takes only the first five)
[TplCode]
{Foreach: $ a, $ k, $ v, 5}
$ V = {$ v}

{/Foreach}
[/TplCode]

Method 3 (you can set the number of loops. if array $ a has 15 elements, the following loop starts from 3rd elements and ends with 5th elements)
[TplCode]
{Foreach: $ a, $ k, $ v, 3, 5}
$ V = {$ v}

{/Foreach}
[/TplCode]
See "example1" and "example3". you can use multi-dimensional arrays in the "foreach" loop. for details, see "example10"

3. use the IF statement in the template, for example:

First usage
[TplCode]
{If: $ a = "hello "}
The value of variable $ a is "hello"
{/If}
[/TplCode]

Second usage
[TplCode]
{If: $ a = true}
Variable $ a is true
{Else}
Variable $ a is not true
{/If}
[/TplCode]

Third usage
[TplCode]
{If: $ a = 2}
The value of variable $ a is 2.
{Elseif: $ a = 3}
The value of variable $ a is 3.
{/If}
[/TplCode]
For more information, see "example2" and "example6"

4. include the template file in the template, for example:
{TplCode}
{Includetpl: head. tpl}
{/TplCode}
The template file "head. tpl" is included. the template file must be in the same directory.

5. the template contains the php file, for example:
{TplCode}
{Shortdephp: head. php}
{/TplCode}
The php file "head. php" and the file "head. php" are included in the current program directory.
For more information about the files, see "example8"

6. output time in the template, for example:
{TplCode}
{Date: Y-m-d H: I: s}
{/TplCode}
The subsequent "Y-m-d H: I: s" string is a standard PHP time identifier. For more information, see The PHP Manual.
For more information, see "example7"

7. use mathematical functions in the template

First, output the result directly.
{TplCode}
{Math: 3*2-5}
{/TplCode}

Second, assign a value to the specified variable.
{TplCode}
{Math: 3*2-5, $ result}
{/TplCode}

Method 3: assign a value to the specified variable. set the third parameter to "Y" and "N" to output immediately.
{TplCode}
{Math: 3*2-5, $ result, Y}
{/TplCode}
For more information, see "example4"

8. use the FOR loop in the template
The following code is used:
[TplCode]
{For: 5,1000, 1, $ I}
{$ I}

{/}
{/TplCode}
Parameter description:
5: indicates that the cycle starts from 5.
1000: indicates that the loop ends at 1000.
1: The increment of each loop is 1, which is equivalent to $ n ++.
$ I: returns the value of each loop.
(Constants such as "5", "1000", "1" can also be replaced by variables, such as: {for: $ num, $ max, $ step, $ I}, where the variables are assigned values using the "assign ()" method in the program)
Refer to the following code for more information ):
[TplCode]
{For: 500,30,-2, $ I}
The cycle starts from 500, minus 2 each time, and ends until 30. The value of the current loop is: {$ I}

{/}
{/TplCode}
For more information, see "example2", "example11"

9. use the Email tag in the template
First usage:
[TplCode]
{Email: redhat@hnwj.net}
[/TplCode]
Second usage:
[TplCode]
{Email: redhat@hnwj.net, Redhat email}
[/TplCode]
Third usage:
[TplCode]
{Email: redhat@hnwj.net, this is the "Redhat" mailbox <-dh-> This is a style <-dh-> class = m, m}
[/TplCode]
For more information, see "example5"

10. Define variables in the template
[TplCode]
{Assign: $ tplVar, which is the variable I defined <-dh-> can be output in the template or PHP code output}
[/TplCode]
For more information, see "example6 ".

11. other syntaxes and functions are still under development ......
If you have any good comments or ideas, go to http://2002.buyionline.net/2002/gbook.phpto pick it up. if you find that bugalso needs prompt message, thank you!



Note:
1. This template supports multi-layer nested templates or PHP files and multi-layer foreach or for loops.
2. practical skills
In actual use, if the attribute $ cmpCheck is set to true, the PHP program will be compiled every time it is run. Otherwise, the program will determine whether to re-compile the PHP file based on the length of time after compilation.
The default value of this attribute is true. it is set to false only when it is in use (which can accelerate the speed)
The setting method is as follows: $ tttObj-> setCmpCheck (true );
3. the biggest disadvantage of this program is that it cannot accurately capture the syntax error messages in the program.
4. the cache function is not currently supported. if you have any good ideas, please let me know :-)
5. because the php file is compiled in the mixed encoding mode, do not enter an error (of course, the template supports the same case and case, that is, you write a {math: 38*7} and {MatH: 38*7} have the same effect. for example, input "{foreach: $ data, k, $ v}" to compile the program, however, a syntax error occurs during running because a "$" symbol is missing before "k. I have already written the code for capturing errors in each line of syntax analysis, but it takes a long time to find that the code reaches hundreds of lines. if the code is less, however, a large amount of data may cause performance degradation. in addition, PHP itself has a very good error message, and later I thought I did not analyze each line of code.
6. I wonder if you have noticed that in the above identifiers, the parameters are not enclosed by quotation marks or double quotation marks (except for the condition judgment statement). Please note :-)

4. use

1. create a php file named first. php and save it in the current directory, that is, "./". The content is as follows:
Require_once "./ttt. php"; // introduce a class file
$ Ttt = new TTT (); // Initialize an instance of the 3 T template class
$ Ttt-> setTplDir ("./tpl/"); // Directory of the template file to be compiled
$ Ttt-> setCmpDir ("./cmp/"); // Directory for storing compiled files
$ Ttt-> assign ('title', 'skycolor'); // Set the variable
$ Ttt-> assign ('content', 'Blue, good weather, cloudification, clear'); // Set the variable
$ Ttt-> assign ('foot', 'Welcome '); // Set the variable
$ Ttt-> display ('First. tpl '); // output
?>

2. create a tpl File (named "first. tpl" and save it in the Directory "./tpl/"). The content is as follows:





{$ Title}


{$ Content}



{$ Foot}



3. browse http: // domain/path/to/3tvx in the browser. x/3 t/first. php shows the result. of course, you must configure the PHP runtime environment first.
4. For more examples, see the "example" series provided by the program...
V. class attributes (part)
$ TplDir: String, "./tpl /"
Template File Directory. the template to be loaded is loaded from this directory.

$ CmpDir: String, "./cmp /"
Directory for storing compiled PHP files

$ CheDir: String, "./che /"

$ TplFile: String ,""
Template file, the main template file to be parsed

$ StartLeft: String ,"{"
The left boundary symbol of the template variable. you can set it by using setLeft (String $ s ).

$ StartRight: String ,"}"
The right boundary symbol of the template variable. you can set it by using setRight (String $ s ).


VI. class methods (part)
TTT (String | null)
Class constructor. you can directly set the template to be parsed here, for example, $ obj-> TTT ("head. tpl ");

SetLeft (String)
Sets the left border of the template variable "$ startLeft". The default value of this variable is "{"

SetRight (String)
Sets the left border of the template variable "$ startRight". The default value of this variable is "{"

SetTplDir (String)
Sets the storage path of the template. the method with the same name is "setTemplatesFile ()"

SetCmpDir (String)
Sets the storage path after template compilation. the method with the same name is "setCompilesFile ()"

SetCheFile (String)
Sets the cache template file directory. the method with the same name is "setCachesFile ()"

SetCacheFilter (String | array)
When the template cache function is used, files set using this method will not be cached for processing.

SetWordsFilter (array)
Set characters or strings that are not suitable for display on the website, such as $ ttt-> setWordsFilter ('ABC', 'XYZ ');, replace all "abc" in the webpage with "xyz ";

SetWordsFile (String | array)
When you set characters or strings that are not suitable for display on the website, the characters or strings in the files set using this method will be directly displayed without being affected by the "setWordsFilter ()" method.

SetQuery (String)
This method is used only when the template cache function is used. it is mainly used to set a unique string of characters so that the cached files will not be repeated, if this parameter is not set, the template is automatically obtained, but the program becomes insecure. as long as you continuously GET different parameters from the program, different cache files will be generated all the time. after N hours, I think you have no space on the server's hard disk. of course, this is only because you have used the cache function and have not used this method to set a unique string, therefore, it is important to correctly set and process some GET or POST values in the program. You can use this method like this "$ ttt-> setQuery (" typeid = $ tid & msgid = $ sid ")", note that when a malicious user submits a different $ tid or $ sid, the above attack event will also occur, therefore, you must capture the invalid $ tid and $ sid in the program and stop executing the "$ ttt-> display ()" method.

Assign (String, String | array)
Set the variables to be used in the template. The first parameter is the variable to be used in the template, and the second parameter is the user-defined value, as follows:
$ Obj-> assign ('webname', 'Home name ');
$ Obj-> assign ('userid', array ));

Display (String | null)
Output the parsed template. the parameter is the name of the template file to be output (if the class is initialized or the method "setTplFile ()" has been set, this method does not require parameters)


Currently, when developing WEB applications, one of the most popular practices is to use the "MVC" structure to develop WEB applications in this way, which is logical and simple, make...

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.