Study on MVC structure in PHP5

Source: Internet
Author: User
Tags functions connect net variables php file string version variable
PHP5 A. Introduction

Now in the development of Web applications, a more popular approach is to use the "MVC" structure, the use of such a way to develop Web applications, logical, Jianho clear, so that the design is more convenient and fast. What is "MVC"? In simple terms, it is "model", "the combination of view and controller (Controller), which is all the" three-layer "abstract structure, of course" MVC "here is for Web applications," Make code and page design separate " Is its leading thinking, this idea in the use of Java servlet/javaserver pages Technology "Struts" performance of the incisively and vividly, interested can go to http://jakarta.apache.org/struts to see, This design pattern allows the program designers to focus on code design, writing and debugging, web designers can have more time to put into the design without having to pay attention to the implementation of specific functions, this division of labor is fully adapted to large-scale projects or enterprise-level distributed application development.

From the introduction of PHP5 can see, the object-oriented function is more and more perfect, the use of PHP to develop large-scale commercial web sites or distributed enterprise applications has become possible, if the combination of Zend Optimizer, has implemented the code encapsulation.

How do you use the MVC design pattern in PHP to develop Web applications? Remember a bit (the Code and the page design are separate), with a simple example to illustrate, for example, to query from the database members of the information to display on the page, Here we need to consider two points: 1. Connect the database and remove the member data, 2. Display the member data on the Web page, connect the database we use a database class, call it "DB" class, this class is now playing the "model" role, then we need to write an operation "DB" Class to take out the data, the role of the program is "Controller (Controller)", which takes the client "POST" or "put" data, and then calls the "DB" class to take out the data and store the data in the controller (Controller). Finally, pass the data to "view" and display it in a certain typesetting format. From the above analysis can be seen, the template is here to play a "view" role, of course, only a template class can not be described as MVC, the real MVC is not so simple, you can refer to the specific "JSF".

"3t" is a template class, mainly read "controller (Controller)" Data and some special processing, and finally through some simple template syntax to show the data, it has some what kind of characteristics?

Fast parsing, you can choose to use HTML caching or PHP caching as needed, but you can also implement fast and stable Web applications without caching.

Easy to use, easy installation, in the reading of data similar to the famous template class "SMARTY", in the data display is similar to "PHP syntax" and similar "JavaBeans"

Scalability is good, you can always add to the function you want as needed, because it is open source, in the near future, will support the plug-in function

Scalability is good, support the latest PHP5, as long as your PHP version >=4.0.6 can be used, of course you need to have the right to operate files on the server

Powerful, Support Template multilevel nesting, array multilevel loop, etc.

Of course, this template still need to improve a lot of places to be tested in a variety of environmental testing to continue to improve, currently only in the Linux and Windows environment test pass.

Two. Installation

1. After decompression should be able to see the following directory structure:

./3tx.x/cmp/compiled files (make sure this folder is readable and writable)
./3tx.x/tpl/template files (all template files are here to make sure that this folder is readable)
./3tx.x/che/Cached Files folder (make sure this folder is readable and writable)
./3tx.x/ttt/ttt.php 3T Template class file
./3tx.x/Program Files (all of the programs you write are here)

2. Your PHP version can not be less than PHP4.0.6, I suggest that your PHP version upgrade to 4.3.0, the overall performance of the program will be greatly improved

3. If a variable is not defined at run time, please add "error_reporting (7)" before the program; Function

Three. Grammar

Template Simple Syntax Description:
Generally use the left brace "{" and the right Brace "}" as the beginning and end of the template syntax, and of course you can use custom delimiters, such as using [and], and the following instructions are delimited with curly braces

(note; The following code in the middle of [Tplcode] and [/tplcode] is the template syntax code)

1. Use the PHP code in the template file, such as:
[Tplcode]
{PHP}
$i = 3;
echo $i;
{/php}
[/tplcode]
Please refer to "Example6"

2. Use a foreach loop in the template, such as:


The first usage (loop array $a, equivalent to foreach in PHP ($a as $k => $v) ...)
[/tplcode]
{foreach: $a, $k, $v}
$v = {$v}<br>
{/foreach}
[/tplcode]

The second usage (can set the loop several times, if the array $a has 15 elements, then the following loop takes only the first 5)
[Tplcode]
{foreach: $a, $k, $v, 5}
$v = {$v}<br>
{/foreach}
[/tplcode]

The third use (you can set the loop several times, if the array $a has 15 elements, then the following loop starts with the 3rd element, takes the 5th element end)
[Tplcode]
{foreach: $a, $k, $v, 3,5}
$v = {$v}<br>
{/foreach}
[/tplcode]
Refer to "example1" and "example3" and use multidimensional arrays in a "foreach" Loop, see "Example10"

3. Use the If statement in the template, such as:

The first use of
[Tplcode]
{if: $a = = "Hello"}
The value of the variable $a is "Hello"
{/if}
[/tplcode]

The second way to use
[Tplcode]
{if: $a = = true}
Variable $a is true
{Else}
Variable $a is not true
{/if}
[/tplcode]

The third way to use
[Tplcode]
{if: $a = = 2}
The value of the variable $a is 2
{elseif: $a = = 3}
The value of the variable $a is 3
{/if}
[/tplcode]
For specific use please refer to "example2" and "Example6"

4. Include template files in the template, such as:
{Tplcode}
{INCLUDETPL:HEAD.TPL}
{/tplcode}
This contains the template file "Head.tpl", which contains template files that must be in the same directory

5. Include PHP files in the template, such as:
{Tplcode}
{includephp:head.php}
{/tplcode}
This contains the php file "head.php", the file "head.php" in the current program directory
Include file See "Example8"

6. In the template output time, such as:
{Tplcode}
{date:y-m-d H:i:s}
{/tplcode}
The following "Y-m-d h:i:s" string is a standard PHP time tag that can be used in reference to the PHP manual
For specific use please refer to "Example7"

7. Using mathematical functions in a template

The first use, the direct output of the result
{Tplcode}
{math:3*2-5}
{/tplcode}

The second usage, assigning to the specified variable
{Tplcode}
{math:3*2-5, $result}
{/tplcode}

The third use, assignment to the specified variable, the third parameter set whether to output immediately, set to "Y" output, "N" does not output
{Tplcode}
{math:3*2-5, $result, Y}
{/tplcode}
For specific use please refer to "example4"

8. Use a For loop in the template
Shown in the following code
[Tplcode]
{for:5,1000,1, $i}
{$i}<br>
{/for}
{/tplcode}
Parameter description:
5: Indicates starting from 5 cycle
1000: Loop to 1000 end
1: The increment of each cycle is 1, equivalent to $n++
$i: Represents the value of getting each loop
Constants such as the above "5", "1000", "1" are also available in substitution for variables such as: {for: $num, $max, $step, $i}, where the variables are assigned in the Assign () method in the program)
Also refer to the following code (understand):
[Tplcode]
{for:500,30,-2, $i}
Cycle from 500, each time minus 2, until 30 is over, the current loop value is: <b>{$i}</b><br>
{/for}
{/tplcode}
For specific use please refer to "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's mailbox}
[/tplcode]
Third usage:
[Tplcode]
{email:redhat@hnwj.net, this is "Redhat" Mailbox <-dh-> This is a <-dh->class=m,m with style}
[/tplcode]
For specific use please refer to "Example5"

10. Define variables in the template
[Tplcode]
{Assign: $tplVar, this is the variable I defined <-dh-> can be exported in the template also available in PHP code output}
[/tplcode]
Please refer to "Example6" for specific use.

11. Other grammars and functions are still under development ...
Have a good opinion or idea please go to http://2002.buyionline.net/2002/gbook.php to mention it, find bugs also please leave a message to explain, thank you!



Note:
1. This template supports multiple layers of nested templates or PHP files, supporting multi-tier foreach or for loops
2. Practical Use skills
If you set the property $cmpcheck to true during the actual use, you will compile the PHP program every time you run it, or you'll be able to determine whether you want to recompile it based on the length of time the PHP file is compiled.
The default value of this property is true, and is generally set to false in use (speed can be accelerated)
Set the method such as: $tttObj->setcmpcheck (TRUE);
3. The biggest drawback of this procedure is that it can not accurately capture the syntax error messages that appear in the program
4. Temporarily does not support caching function, if you have the good idea may as well tell me:-)
5. As a result of the use of mixed-mode compiler template for php files, so please do not lose the wrong (of course, the template is to support the same case writing, that is, you write a {math:38*7} and {math:38*7} effect is the same), such as input "{foreach: $data, K, $V} "compilation will pass, but running will result in a syntax error, because the" K "in front of it is less than a" $ "symbol. It was already written. Parsing each line of syntax to catch the wrong code, but found that the code to reach hundreds of lines of time takes longer, if the code is less still can, But if more words can lead to performance degradation. And PHP itself has a very good error message prompts, then think about it did not go to the analysis of each line of code.
6. I do not know whether you notice that in the above identification, the parameters are not quoted or double quotes (except the conditional judgment statement), wish to pay attention to OH:-)

Four. Use

1. Create php file (named first.php, saved in the current directory, that is, "./"), which reads as follows:
<?php
Require_once "./ttt/ttt.php";//Introducing class files
$TTT = new TTT ()//Initializes an instance of the 3T template class
$ttt->settpldir ("./tpl/");//need to compile template file storage directory
$ttt->setcmpdir ("./cmp/");//post-compile file storage directory
$ttt->assign (' title ', ' Color of the sky ');/Set Variable
$TTT->assign (' content ', ' Blue, nice weather, cloudless, clear '); Set variable
$ttt->assign (' foot ', ' Welcome to welcome ');/Set Variable
$ttt->display (' first.tpl ');//Output
?>

2. Establish the TPL file (named "First.tpl", which is saved under the directory "./tpl/"). The contents are as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title>{$title}</title>
<body>
{$content}<br>
<br>
{$foot}
</body>

3. Browse the http://domain/path/to/3tvx.x/3t/first.php in the browser to see the results, of course, you have to the PHP operating environment configured well.
4. For more examples, please see the "Example" series from the program.
Five. Class attributes (partial)
$tplDir: String, "./tpl/"
The directory of the template file, the template that needs to be loaded is loaded from here

$cmpDir: String, "./cmp/"
Compiled PHP file storage directory

$cheDir: String, "./che/"

$tplFile: String, ""
Template file, the template master file to be resolved

$startLeft: String, "{"
The left boundary symbol of the template variable, which you can set yourself by using the Setleft (String $s) method

$startRight: String, "}"
The right boundary symbol for the template variable, which you can set yourself by using the Setright (String $s) method
 

Six. class method (partial)
TTT (String|null)
Class Builder, where you can set the template to be resolved directly, such as: $obj->ttt ("Head.tpl");

Setleft (String)
Sets the left boundary of the template variable "$startLeft", which defaults to "{"

Setright (String)
Sets the left boundary of the template variable "$startRight", which defaults to "{"

Settpldir (String)
Sets the path where the template is stored, with the same method as "Settemplatesfile ()"

Setcmpdir (String)
Sets the store path after the template is compiled, with the same method as "Setcompilesfile ()"

Setchefile (String)
Sets the cached template file directory, which has the same method as "Setcachesfile ()"

Setcachefilter (String|array)
Files that are set using this method will not be cached when the cached functionality of the template is used

Setwordsfilter (Array)
Set characters or strings that are not suitable for display on the site, such as: $ttt->setwordsfilter (' abc ', ' XYZ '), and replace all "ABC" in the Web page with "XYZ";

Setwordsfile (String|array)
When you set a character or string that is not appropriate for display on a Web site, the characters or strings in the file that you set this method will be displayed directly without being affected by the Setwordsfilter () method

Setquery (String)
This method is used only when the caching feature of the template is used. Is mainly used to set a unique string of characters so that the cached files will not be duplicated, if not set the template will be automatically obtained but will make the program unsafe, as long as the constant to the program get different parameter changes will always generate different cache files, n time, I think your server's hard drive has no space, of course, these are only when you use the caching function and do not use this method to set a unique string, so it is important to set and process some get or post values correctly in your program. You can use this method like this "$ttt->setquery (" typeid= $tid &msgid= $sid "), and note that this can also cause attacks when a malicious user submits a different $tid or $sid. Therefore, you must catch illegal $tid and $sid in your 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 ', ' homepage name ');
$obj->assign (' UserID ', Array (23,37,12,18));

Display (String|null)
Output parsed template, parameter is the template file name to output (if the class is initialized or the method "Settplfile ()" has been set, you can use this method with no parameters)




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.