Home > Backend Development > PHP Tutorial > Learning the MVC structure in PHP5_PHP tutorial

Learning the MVC structure in PHP5_PHP tutorial

WBOY
Release: 2016-07-21 16:11:15
Original
814 people have browsed it


1. Introduction

Nowadays, when developing WEB applications, one of the more popular methods is to use the "MVC" structure. Using this method to develop WEB applications is highly logical, simple and clear, and makes the program design easier. It’s more convenient and faster to get up. What is "MVC"? To put it simply, it is a combination of "Model", "View" and "Controller", that is, all "three-layer" abstract structures. Of course, the "MVC" mentioned here " is for applications on the WEB. "Separating code and page design" is its leading idea. This idea is most vividly expressed in "Struts" using Java Servlet/JavaServer Pages technology. Those who are interested can go to http ://jakarta.apache.org/strutsLook, this design pattern allows programmers to focus on the design, writing and debugging of code, and web designers can have more time to invest in design without paying attention to specific details. Function realization, this division of labor is fully suitable for large-scale projects or enterprise-level distributed application development.

From the launch of PHP5, we can see that the object-oriented functions are becoming more and more perfect. It has become possible to use PHP to develop large-scale commercial websites or distributed enterprise applications. If combined with Zend Optimizer, it has been realized. Code encapsulation.

How to use the "MVC" design pattern in PHP to develop WEB applications? Remember one thing (code and page design are separated), and use a simple example to demonstrate it. For example, if you want to query member information from the database and display it on the web page, you need to consider two points here: 1. Connect to the database and retrieve the members. Information, 2. Display the member information on the web page, and connect to the database. We use a database class, call it the "DB" class. This class plays the role of "Model" at this time, and then we need to write A program that operates the "DB" class to retrieve data. The role played by this program is the "Controller". It accepts "POST" or "PUT" data from the client, and then calls the "DB" class to retrieve the data. Data, store these data in the "Controller", and finally pass the data to the "View" and display it according to a certain layout format. From the above analysis, we can see that the template plays the role here Of course, just a template class cannot be said to be MVC. The real MVC is not that simple. For details, please refer to "JSF".

"3t" is a template class, which mainly reads the data of "Controller" and performs some special processing. Finally, it displays the data through some simple template syntax. What does it have? What about the characteristics?

The parsing speed is fast. You can choose to use html caching or php caching according to your needs. Of course, you can also use caching without caching. You can also achieve fast and stable WEB applications

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

It has good scalability, you can add whatever you want at any time as needed The necessary functions, because it is open source, will support plug-in functions in the near future

It has good scalability and supports the latest PHP5. As long as your PHP version >= 4.0.6, you can use it. Of course, you need to have permission to operate files on the server

It is powerful and supports multi-level nesting of templates, multi-level array loops, etc.

Of course, there are many areas for improvement in this template. It can be continuously improved after testing in various environments. Currently, it is only tested in LINUX and WINDOWS environments.

2. Installation

1. After decompression, you should see the following directory structure:

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

2. Your PHP version cannot be lower than PHP4.0.6. I recommend that your PHP version be upgraded to 4.3.0 Above, the overall performance of the program will be greatly improved

3. If a variable is undefined during runtime, please add the "error_reporting(7);" function in front of the program

3. Syntax

Template simple syntax description:
Generally, the left brace "{" and the right brace "}" are used as the beginning and end of the template syntax. Of course, you can also use custom delimiters, such as " [" and "]", the following description uses curly brackets as delimiters

(Note: The code between [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 foreach loop in the template, such as:


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

{/foreach}
[/tplCode]

The second usage (you can set how many times to loop, if the array $a has 15 elements, then the following The loop only takes the first 5)
[tplCode]
{foreach:$a,$k,$v,5}
$v = {$v}

{/foreach}
[/tplCode]

The third usage (you can set how many times to loop, if the array $a has 15 elements, the following loop will start from the 3rd element, End after getting the 5th element)
[tplCode]
{foreach:$a,$k,$v,3,5}
$v = {$v}

{/foreach}
[/tplCode]
Please refer to "example1" and "example3". Multi-dimensional arrays can be used in the "foreach" loop. For details, please see "example10"

3. In Use IF statements in templates, such as:

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]

The 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]
Please refer to "example2" and "example6" for specific usage

4. Include the template file in the template, such as:
{tplCode}
{includetpl:head.tpl}
{/tplCode}
The template file "head.tpl" is included here. The included template file must be in the same directory

5. Include PHP files in the template, such as:
{tplCode}
{includephp:head.php}
{/tplCode}
The PHP file "head.php" is included here, and the file "head.php" is in the current program directory
Please see "example8" for 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 stamp. For specific usage, please refer to the PHP manual
For specific usage, please refer to "example7"

7. Use mathematics in templates Function

The first usage, directly output the result
{tplCode}
{math:3*2-5}
{/tplCode}

The second usage , assign value to the specified variable
{tplCode}
{math:3*2-5,$result}
{/tplCode}

The third usage, assign value to the specified variable, Chapter 1 The three parameters set whether to output immediately, set to "Y" output, "N" not output
{tplCode}
{math:3*2-5,$result,Y}
{/tplCode}
Please refer to "example4" for specific usage

8. Use FOR loop in the template
As shown in the following code
[tplCode]
{for:5,1000,1,$ i}
{$i}

{/for}
{/tplCode}
Parameter description:
5: Indicates looping starting from 5
1000: Indicates looping End at 1000
1: Indicates that the increment of each cycle is 1, equivalent to $n++
$i: Indicates that the value of each cycle is obtained
("5", "1000", " Constants such as 1" can also be replaced by variables, such as: {for:$num,$max,$step,$i}, where the variables are assigned using the "assign()" method in the program)
Also refer to the following code (for understanding):
[tplCode]
{for:500,30,-2,$i}
The loop starts from 500, subtracting 2 each time, and does not end until 30. The current loop value is:{$i}

{/for}
{/tplCode}
Please refer to "example2", "example11" for specific usage

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 email address}
[ /tplCode]
Third usage:
[tplCode]
{email:redhat@hnwj.net, this is the email address of "Redhat"<-dh->This is styled< -dh->class=m,m}
[/tplCode]
Please refer to "example5" for specific usage

10. Define variables in the template
[tplCode]
{assign:$tplVar, this is the variable I defined <-dh-> can be output in the template or in PHP code}
[/tplCode]
Please refer to "example6" for specific usage.

11. Other syntax and functions are still under development...
If you have any good comments or ideas, please go to http://2002.buyionline.net/2002/gbook.php and mention them. If you find a bug, please leave a message in time to explain it, thank you!



Note:
1. This template supports multi-layer nested templates or PHP files, and supports multi-layer foreach or for loops
2. Actual usage 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-install the PHP file based on the existence time of the compiled PHP file. Compile
The default value of this attribute is true, and it is usually set to false when it is in use (which can speed up the speed)
The setting method is: $tttObj->setCmpCheck(true);
3. This program The biggest disadvantage is that it cannot accurately capture the syntax error information that appears in the program
4. It does not support the caching function yet. If you have good ideas, please tell me:-)
5. Since it uses a mixed compilation mode The template is compiled into a PHP file, so please don’t make a mistake (of course the template supports uppercase and lowercase writing, which means that if you write {math:38*7} and {MatH:38*7}, the effect is the same ), if you enter "{foreach:$data,k,$v}", the compilation will pass, but it will cause a syntax error when running, because there is a "$" symbol missing in front of "k". It has already been written In order to perform syntax analysis on each line to capture erroneous code, I found that it takes a long time when the code reaches hundreds of lines. It is okay if the code is relatively small, but if there are more codes, it will lead to a decrease in performance. And PHP itself has many Nice error message, but after thinking about it, I didn’t analyze each line of code.
6. I wonder if you have noticed that in the above logo, the parameters are without quotes or double quotes (conditional judgment) Except for statements), please pay attention:-)

4. Use

1. Create a PHP file (named first.php and saved in the current directory, i.e. "./"), The content is as follows:
require_once "./ttt/ttt.php";//Introducing class files
$ttt = new TTT();//Initializing instances of the 3T template class
$ttt->setTplDir("./tpl/");//The directory where template files that need to be compiled are stored
$ttt->setCmpDir("./cmp/");//The storage of compiled files Directory
$ttt->assign('title','Color of the sky');//Set variables
$ttt->assign('content','Blue, good weather, cloudless ,Qing');//Set variables
$ttt->assign('foot','Welcome welcome');//Set variables
$ttt->display('first.tpl'); //Output
?>

2. Create a tpl file (named "first.tpl" and saved in the directory "./tpl/"). The content is as follows:





{$title}


{ $content}



{$foot}



3. Browse http in the browser ://domain/path/to/3tvx.x/3t/first.php to see the results. Of course, you must configure the PHP running environment first.
4. For more examples, please see the program that comes with it. "example" series...
5. Class attributes (part)
$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 main template file to be parsed

$startLeft:String,"{"
The left boundary symbol of the template variable, you can pass the setLeft(String $s) method yourself Go to settings

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


6. Class methods (part)
TTT(String|null)
Class constructor, you can directly set the template that needs to be parsed here, such as: $obj->TTT("head.tpl");

setLeft(String)
Set the template variable "$startLeft ", the default value of this variable is "{"

setRight(String)
Set the left boundary of the template variable "$startRight", the default value of this variable is "{"

setTplDir (String)
Set the storage path of templates. The same name of this method is "setTemplatesFile()"

setCmpDir(String)
Set the storage path of compiled templates. The same name of this method is "setCompilesFile()"

setCheFile(String)
Set the cached template file directory. The method with the same name is "setCachesFile()"

setCacheFilter(String|array)
When the caching function of the template is used, the files set using this method will not be cached

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 web page with "xyz";

setWordsFile(String|array)
When set, it should not be used on the website When the characters or strings are displayed on, the characters or strings in the file set by this method will not be affected by the "setWordsFilter()" method and will be displayed directly

setQuery(String)
This method It is only used when using the caching function of the template. It is mainly used to set a unique string of characters so that the cached file will not be repeated. If it is not set, the template will be automatically obtained but it will make the program unsafe. As long as it continues GET different parameters to the program will always generate different cache files. After N time, I think your server's hard disk will run out of space. Of course, this is only possible if you use the cache function and do not use this method to set a unique string. Caused by this, it is very important to correctly set and process some GET or POST values ​​in the program. You can use this method "$ttt->setQuery("typeid=$tid&msgid=$sid")" like this, here. It should be noted that when a malicious user submits a different $tid or $sid, the above attack event will also be caused, so the illegal $tid and $sid must be captured in the program and the execution of the "$ttt->display()" method must be stopped. .

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 the parsed template, and the parameter is the template file name to be output (if it has been set during the initialization of the class or using the method "setTplFile()", use this method No parameters are required)


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313993.htmlTechArticle1. Introduction Nowadays, when developing WEB applications, one of the more popular methods is to use the "MVC" structure. Using this method to develop WEB applications is highly logical and simple, making...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template