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

Learning the MVC structure in PHP5_PHP tutorial

Jul 21, 2016 pm 04:11 PM
mvc php5 web one introduce practice study develop Compare flow now use structure


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

TrendX Research Institute: Merlin Chain project analysis and ecological inventory TrendX Research Institute: Merlin Chain project analysis and ecological inventory Mar 24, 2024 am 09:01 AM

According to statistics on March 2, the total TVL of Bitcoin’s second-layer network MerlinChain has reached US$3 billion. Among them, Bitcoin ecological assets accounted for 90.83%, including BTC worth US$1.596 billion and BRC-20 assets worth US$404 million. Last month, MerlinChain’s total TVL reached US$1.97 billion within 14 days of launching staking activities, surpassing Blast, which was launched in November last year and is also the most recent and equally eye-catching. On February 26, the total value of NFTs in the MerlinChain ecosystem exceeded US$420 million, becoming the public chain project with the highest NFT market value besides Ethereum. Project Introduction MerlinChain is an OKX support

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

See all articles