_php Tutorial on MVC structure Learning in PHP5

Source: Internet
Author: User
Tags mathematical functions
I. 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, logic strong, Jianho clear, making programming easier and faster. What is "MVC"? Simply put, it is the "model", "View" and "controller" of the Union, that is, all the "three-layer" abstract structure, of course, the "MVC" here is for the Web application, "Make code and page design separate" Is its dominant thought, this idea in the use of Java servlet/javaserver pages Technology "Struts" in the incisively and vividly, interested can go to http://jakarta.apache.org/struts to see, This design pattern enables the program designer to focus on the design, writing, and debugging of the Code, and the Web designer can devote more time to the design without regard to the specific functional implementation, which is fully adaptable to large-scale projects or enterprise-class distributed application development.

From the launch of PHP5 can be seen, which the object-oriented function is becoming more and more perfect, using PHP to develop large-scale commercial web sites or distributed enterprise applications has become possible, if combined with Zend Optimizer, has achieved the encapsulation of the code.

How do I use the "MVC" design pattern in PHP to develop Web applications? Remember a bit (Code and page design separate), with a simple example to illustrate, such as to query the database from the member's data to display on the page, Here are two points to consider: 1. Connect to the database and take out the membership information, 2. Connect the database to the Web page, link the databases we use a database class, call it the "DB" class, this class now plays the role of "model", then we need to write an operation "DB" Class of the program to take out the data, the role of the program is "Controller", which accepts the client "POST" or "PUT" data, and then call the "DB" class to take out the data, the data are stored in the "controller", Finally, the data to the "view" and in accordance with a certain format display, from the above analysis can be seen, the template here is playing "view" role, of course, just a template class can not be said to be MVC, the real MVC is not so simple, specifically can refer to "JSF".

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

Resolution is fast, you can choose to use the HTML cache or PHP cache, of course, you can not cache, but also to achieve fast and stable web applications

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

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

Good scalability, support the latest PHP5, as long as your PHP version >=4.0.6 can be used, of course you need to have permissions on the server operation files

Powerful, multi-level nesting of support templates, array multi-level loops, etc.

Of course, this template needs to be perfected a lot of places, to be used 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, you should see the following directory structure:

./3tx.x/cmp/compiled files (make sure this folder is readable and writable)
./3tx.x/tpl/template files (where template files are placed, make sure this folder is readable)
./3tx.x/che/the folder where the cache files are stored (make sure this folder is readable and writable)
./3tx.x/ttt/ttt.php 3T Template class file
./3tx.x/Program Files (the programs you wrote are here)

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

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

Three. Syntax

Template Simple Syntax Description:
The left curly brace "{" and the right curly brace "}" are generally used as the beginning and end of the template syntax, but you can also use custom delimiters, such as "[" and "]", which are described in curly braces as delimiters.

(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 as:
[Tplcode]
{PHP}
$i = 3;
echo $i;
{/php}
[/tplcode]
Please refer to "Example6"

2. Use the Foreach loop in the template, such as:


The first usage (circular array $ A, equivalent to foreach in PHP ($a as $k + = $v) ...)
[/tplcode]
{foreach: $a, $k, $v}
$v = {$v}

{/foreach}
[/tplcode]

The second usage (you can set the loop several times, if the array $ A has 15 elements, then the following loop will take only the first 5)
[Tplcode]
{foreach: $a, $k, $v, 5}
$v = {$v}

{/foreach}
[/tplcode]

A third usage (you can set the loop several times, if the array $ A has 15 elements, then the following loop starts with the 3rd element and takes the 5th element to the end)
[Tplcode]
{foreach: $a, $k, $v, 3,5}
$v = {$v}

{/foreach}
[/tplcode]
Refer to "example1" and "Example3" for multi-dimensional arrays in "foreach" loops, see "Example10" for details.

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

The first way to use
[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}
Variable $ A has a value of 2
{elseif: $a = = 3}
Variable $ A has a value of 3
{/if}
[/tplcode]
Please refer to "example2" and "example6" for specific use.

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" under the current program directory
Please see "Example8" for the included files.

6. Output the time in the template, such as:
{Tplcode}
{date:y-m-d H:i:s}
{/tplcode}
The following "Y-m-d h:i:s" string is the standard PHP time identifier, which can be referenced in PHP manuals
For specific use please refer to "Example7"

7. Using mathematical Functions in templates

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

Second use, assign to the specified variable
{Tplcode}
{math:3*2-5, $result}
{/tplcode}

The third use, assign 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. Using a For loop in a template
As shown in the following code
[Tplcode]
{for:5,1000,1, $i}
{$i}

{/for}
{/tplcode}
Parameter description:
5: Indicates starting from 5 cycles
1000: Show loop to 1000 end
1: Indicates an increment of 1 per loop, equivalent to $n++
$i: Indicates the value of each loop
(The constants such as "5", "1000", "1" above can also be substituted for variables, such as: {for: $num, $max, $step, $i}, where the variables are assigned by the "Assign ()" method in the program)
Also refer to the following code (understand):
[Tplcode]
{for:500,30,-2, $i}
The loop starts at 500, minus 2 at a time until 30 ends, and the value of the current loop is: {$i}

{/for}
{/tplcode}
For specific use please refer to "example2", "Example11"

9. Use the email tag in the template
The first usage:
[Tplcode]
{Email:redhat@hnwj.net}
[/tplcode]
Second usage:
[Tplcode]
{Email:redhat@hnwj.net,redhat's mailbox}
[/tplcode]
Third use:
[Tplcode]
{email:redhat@hnwj.net, this is the "Redhat" Mailbox <-dh-> This is a styled <-dh->class=m,m}
[/tplcode]
For specific use please refer to "Example5"

10. Defining Variables in Templates
[Tplcode]
{Assign: $tplVar, this is the variable i define <-dh-> can be output in the template as well as PHP code output}
[/tplcode]
Please refer to "Example6" for specific use.

11. Other grammar 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, found the bug also please leave a message to explain, thank you!



Note:
1. This template supports multiple layers of nested templates or PHP files, supporting multiple layers of foreach or for loops
2. Practical Use skills
In the actual use of the process if the property $cmpcheck set to True the PHP program will be compiled each run, or the program according to the length of time of the compiled PHP file to determine whether to recompile
The default value of this property is true, which is set to false (which speeds up) in use.
Setup method such as: $tttObj->setcmpcheck (TRUE);
3. The biggest drawback of this program is that it is not accurate to capture the syntax error messages that appear in the program
4. Cache feature is not supported, if you have a good idea, you might as well tell me:-)
5. Since the use of the mixed-mode compilation template for PHP files, so please do not lose the wrong (of course, the template is supported in the case of a consistent wording, that is, you write a {math:38*7} and {math:38*7} effect is the same), such as input "{foreach: $data, K, $V} "compile will pass, but will cause a syntax error when running, because there is a" $ "symbol in front of" K ". I already wrote the code for parsing the error on each line, but found that the code reached hundreds of lines of time longer, if the code is relatively small can be, However, if more of the words will lead to a decrease in performance. And PHP itself has a very good error message hint, and then think about it did not go to the analysis of each line of code.
6. I do not know whether we notice that in the above identification, the parameters are not quoted or double quotation marks (except conditional judgment statements), I hope to note oh:-)

Four. Use

1. Create a PHP file (named first.php, saved in the current directory, i.e. "./"), as follows:
Require_once "./ttt/ttt.php";//Introduce class file
$TTT = new TTT ();//Initializes an instance of the 3T template class
$ttt->settpldir ("./tpl/");//directory where template files need to be compiled
$ttt->setcmpdir ("./cmp/");//directory where the compiled files are stored
$ttt->assign (' title ', ' Color of the sky ');//Set Variable
$TTT->assign (' content ', ' Blue, nice weather, cloudless, Sunny ');//Set Variable
$ttt->assign (' foot ', ' welcome ');//Set Variable
$ttt->display (' first.tpl ');//Output
?>

2. Create the TPL file (named "First.tpl" and save in the directory "./tpl/"). The contents are as follows:





<title>{$title}</title>


{$content}



{$foot}



3. Browse http://domain/path/to/3tvx.x/3t/first.php in the browser to see the results, of course, you have to set up the PHP operating environment.
4. For more examples, see the "example" series that comes with the program ...
Five. Class attributes (partial)
$tplDir: String, "./tpl/"
Template file directory, 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 parse

$startLeft: String, "{"
The left boundary symbol of the template variable can be set by the Setleft (String $s) method.

$startRight: String, "}"
The right boundary symbol of the template variable, which can be set by the Setright (String $s) method


Six. class method (partial)
TTT (String|null)
Class constructor, where you can set the template to parse 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 storage path for the template, with the method with the same name as "Settemplatesfile ()"

Setcmpdir (String)
Sets the stored path after the template is compiled, and this method has the same name as "Setcompilesfile ()"

Setchefile (String)
Set the cached template file directory with the method with the same name as "Setcachesfile ()"

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

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

Setwordsfile (String|array)
When a character or string that is not intended to be displayed on a Web site is set, the characters or strings in the file set with this method will be displayed directly without being affected by the "Setwordsfilter ()" Method

Setquery (String)
This method is only used when using the template's caching function, mainly to set a unique string of characters so that the cache file will not be duplicated, if not set the template will be automatically obtained but will make the program unsafe, as long as the program get different parameters will always generate a different cache file, n time, I think your server's hard drive will be out of space, of course, these are only when you use the caching feature and do not use this method to set a unique string caused by the correct setting and processing in the program some get or post values is very important. You can use this method like this to "$ttt->setquery (" typeid= $tid &msgid= $sid ")", and it is important to note that when a malicious user submits a different $tid or $sid, it also causes the above attack event, Therefore, you must capture the illegal $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, the second parameter is a user-defined value, as follows:
$obj->assign (' WebName ', ' homepage name ');
$obj->assign (' UserID ', Array (23,37,12,18));

Display (String|null)
Outputs the parsed template with parameters for the template file name to be output (if the class is initialized or the method "Settplfile ()" is used, the method can be used without parameters)


http://www.bkjia.com/PHPjc/313993.html www.bkjia.com true http://www.bkjia.com/PHPjc/313993.html techarticle I. 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, logic strong, Jianho clear, so ...

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