Getting started with PHP by Cainiao _ PHP Tutorial

Source: Internet
Author: User
Tags constant definition getting started with php
Getting started with PHP Smarty for Cainiao. PHP designers who are new to the template engine will find it difficult to hear about Smarty. In fact, I don't dare to touch it. However, when analyzing the XOOPS program architecture, PHP designers who are new to the template engine will find it difficult to hear about Smarty. In fact, I don't dare to touch it. However, when analyzing the XOOPS program architecture, it began to find that Smarty is actually not difficult. As long as you practice the basic functions of Smarty, it is enough in general applications. Of course, the Foundation can be well laid, so there is no need to worry about the next advanced application.

The main purpose of this article is not to thoroughly explore the use of Smarty, which has been fully written in official instructions. I will only write down some of my usage experiences here, so that I can get some inspiration from my friends who want to know about Smarty but cannot get into it. Because the content of this article is not very in-depth, friends who will use Smarty may feel simple.

At present, this article has been revised for the third time, and I want to add more materials. However, due to the relationship between time, I have not thoroughly studied many advanced Smarty skills, so I dare not take it out, however, I believe this article should be able to satisfy most beginners who want to learn Smarty. Of course, if there are any mistakes in this article, please let us know that I will correct them in the next revision.

Smarty introduction

What is a template engine?

I don't know when to start. some people started to feel unsatisfied with the embedded Server Script in HTML. However, both Microsoft's ASP and open source PHP are webpage servo-side languages embedded with Server scripts. So some people think that it would be better to separate the application logic (or commercial application logic) from the web presentation logic (Layout?

In fact, this problem has existed for a long time. when interactive web pages become popular, both ASP and PHP users are both program developers and visual designers. However, these users are usually either program or artist, and if they want to take both of them into account, they have to die a lot of brain cells...

So the template engine came into being! The purpose of the template engine is to achieve the logic separation function mentioned above. It enables program developers to focus on data control or function fulfillment, while visual designers can focus on web page layout to make webpages look more professional! Therefore, the template engine is suitable for the company's website development team, so that everyone can exert their expertise!

For the template engine that I have been familiar with, it is roughly divided into two forms based on the data presentation method: the template engine that needs to be matched with the program processing and the template engine that is completely determined by the template itself.

In the template engine that needs to be matched with the program processing, the program developer must be responsible for the variable presentation logic, that is, he must process the variable content before outputting it to the template, in order to do assign work. In other words, program developers should write more programs to determine the style of variables. The template engine, which is completely determined by the template itself, allows the variables to be directly added to the template, so that the visual designer can decide how to present the variables when designing the template. Therefore, it may have another set of template program syntax (such as Smarty), to facilitate control of the presentation of variables. However, visual designers also need to learn how to use the template language.

The operating principle of the template engine is as follows:

Generally, the template engine (such as PHPLib) obtains the template to be parsed when creating the template object, and then sets the variable into it, and parses the template through the parse () method, finally, output the webpage.

For the Smarty user, the program does not need to do any parse action, and these Smarty will automatically help us. In addition, if the template has not changed, Smarty will automatically skip the compilation action and directly execute the compiled webpage to save compilation time.

Some concepts of using Smarty

In the general template engine, we often see the concept of a region. The so-called block may grow like this:

Region content


Most of these blocks use if or for and while in PHP programs to control their display status. although the template looks much more concise, you only need to change the display mode of different templates, the PHP program is bound to be changed again!

In Smarty, all variables are dominated, and all presentation logic is controlled by the template. Because Smarty has its own template language, the template syntax of Smarty (if, foreach, section) and variable content are used to present whether the block is to be displayed or repeated. In this way, it seems that the template has become a little complicated, but the advantage is that as long as the planning is proper, PHP programs do not have to change the line.

From the above description, we can know that to use Smarty, we need to master the principle of clearly separating the application logic from the webpage presentation logic. That is to say, PHP programs do not have too many HTML codes. In the program, you only need to make sure that the variables are in the template, so that the template determines how to present these variables (or even not ).

Smarty basics

Install Smarty

First, we first determine the place where the program is placed.

In Windows, the location "d: appservwebdemo" may be similar 」.

In Linux, it may be like this: "/home/jaceju/public_html /」.

Download the latest Smarty kit: http://smarty.php.net from The Smarty official website.

After unlocking Smarty 2.6.0, you will see many files, including a libs folder. In libs, there should be 3 class. php labels + 1 debug. tpl + 1 plugin folder + 1 core folder. Then copy the libs file to the main folder of your program and rename it to class. That's it? That's right! This method is relatively simple and suitable for users without their own hosts.

Why are some complicated installation methods described in the Smarty official manual? Basically, the installation is based on the official method. it can be installed only once on the host, and then provided to all designers under the host for direct reference when developing different programs, rather than installing too many Smarty copies. The method provided by the author is suitable for developers who want to bring the program over and migrate it, so that there is no need to worry about whether the host has installed Smarty.

Program folder settings

Take the installation of Appserv in Windows as an example. The main folder of the program is "d: appservwebdemo 」. After installing Smarty, we will create a folder like this under the main folder:

Under Linux, remember to change the templates_c permission to 777. In Windows, the read-only mode is canceled.

The first small program written with Smarty

First, set the path of the Smarty file. name the following file as main. php and place it in the main folder:

Main. php:

Include "class/Smarty. class. php ";
Define (@#__ SITE_ROOT #, @ # d:/appserv/web/demo #); // no diagonal lines at last
$ Tpl = new Smarty ();
$ Tpl-> template_dir = _ SITE_ROOT. "/templates /";
$ Tpl-> compile_dir = _ SITE_ROOT. "/templates_c /";
$ Tpl-> config_dir = _ SITE_ROOT. "/configs /";
$ Tpl-> cache_dir = _ SITE_ROOT. "/cache /";
$ Tpl-> left_delimiter ==#< {@#;
$ Tpl-> right_delimiter ==#}> @#;
?>




The purpose set in the above method is that if the program is to be transplanted to other places, you only need to change _ SITE_ROOT. (Refer to XOOPS here)

After the template path of Smarty is set, the program will follow this path to capture the relative positions of all templates (in the example, @ # d: /appserv/web/demo/templates /@#). Then we use the Smarty method of display () to display our template.

Next, we will place a test.htm in the templates folder: (it doesn't matter what the extension name is, but it is easy for visual designers to develop. I still use. htm as the main tool .)

Templates/test.htm:



<{$ Title}>


<{$ Content}>






Now we want to display the template above and change the webpage title ($ title) and content ($ content). please name the following file content as test. php and put it in the main folder:

Test. php:

Require "main. php ";
$ Tpl-> assign ("title", "webpage title for testing ");
$ Tpl-> assign ("content", "tested webpage content ");
// The above two rows can also be replaced by this line
// $ Tpl-> assign (array ("title" => "webpage title for testing", "content" => "webpage content for testing "));
$ Tpl-> display(@#test.htm @#);
?>




Open your browser and enter http: // localhost/demo/test. php (depending on your environment). you will see the following picture:



Next under templates_c, we will see a strange folder (% 179), and clicking on it is also a strange folder (% 1798044067), where there is a file:

Templates_c/% 179/% 1798044067/test.htm. php:





<? Php echo $ this-> _ tpl_vars [@ # title @ #];?>


_ Tpl_vars [@ # content @ #];?>






That's right. this is the files compiled by Smarty. It converts the variables in the template into PHP syntax for execution. The next time we read the same content, Smarty will directly capture this file for execution.

Finally, let's sort out the entire process of writing the Smarty program:

Step 1. load the Smarty template engine.

Step 2. create a Smarty object.

Step 3. set the parameters of the Smarty object.

Step 4. process the variables in the program, and then use the assign method of Smarty to place the variables into the template.

Step 5. use the display method of Smarty to show the webpage.

How to arrange your program architecture

In addition to the folders required by Smarty (class, configs, templates, and templates_c), we can see two folders: train Des and modules. In fact, this is built by the author imitating the XOOPS architecture, because XOOPS is one of the programs I have come into contact with, and a few of the station programs that use the Smarty template engine. Although the program architecture like this is not as powerful as the XOOPS 1%, there is at least XOOPS to support it.

The connectors folder is mainly used to place some functions and SQL scripts, so that they can be introduced in main. php, as shown below:

Main. php:


Include "class/Smarty. class. php ";
Define (@#__ SITE_ROOT #, @ # d:/appserv/web/demo #); // no diagonal lines at last
// Base on the location of main. php
Require_once "des/functions. php ";
Require_once "des/include. php ";
$ Tpl = new Smarty ();
$ Tpl-> template_dir = _ SITE_ROOT. "/templates /";
$ Tpl-> compile_dir = _ SITE_ROOT. "/templates_c /";
$ Tpl-> config_dir = _ SITE_ROOT. "/configs /";
$ Tpl-> cache_dir = _ SITE_ROOT. "/cache /";
$ Tpl-> left_delimiter ==#< {@#;
$ Tpl-> right_delimiter ==#}> @#;
?>




The modules folder is used to place program modules, so that programs won't be lost, and the overall architecture is clear at a glance.

As we mentioned above, main. php is the main core of the entire program. it starts here, whether it is constant definition, external program loading, and shared variable creation. Therefore, all subsequent modules need to include this file. Therefore, during the program process planning, you must have a good idea of the things that should be put in main. php; of course, it is better to use the include or require instructions to clearly separate each link.



In step 5 of the Smarty program mentioned in the previous section, main. php will help us to complete the first three steps first, and the subsequent module programs only need to perform the next two steps.

Start with variable

How to use variables

From the examples in the previous chapter, we can clearly see that we use the two signs <{and}> to package variables. The default identifier is {and}, but for the relationship between the text rush code and javascript, the author still imitates XOOPS and replaces the identifier. The naming method of variables is the same as that of PHP variables. There is also a $ font (which is different from the general template engine ). The identifier is a bit like in PHP.




(In fact they will be replaced with this), so the following template variables are feasible:

1. <{$ var}>

2. <{$ var}>

3. <{$ var

}>
In Smarty, the preset variables are global, that is, you only need to specify them once. If you specify more than two times, the variable content will be based on the last one specified. Even if we load external subtemplates in the main template, the same variables in the subtemplate will also be replaced, so that we no longer need to parse the subtemplate.

In the PHP program, we use the assign of Smarty to place variables in the template. The usage of assign has been written much in the official manual, as shown in the example in the previous section. However, when we repeat the block, we must do something about the variable before we can sign the variable assign into the template, which will be mentioned in the next chapter.

Modify your variables

As we mentioned above, the style of the Smarty variable is determined by the template. Therefore, Smarty provides many types of variables that can be modified. The method is as follows:

<{Variable | MODIFIER}>

<{Variable | modifier: "parameter (optional, depending on the function)"}>
Example:

<{$ Var | nl2br}>

<{$ Var | string_format: "% 02d"}>
Well, why do we need the template to determine the style of variables? Let's take a look at the HTML below. this is part of a shopping cart checkout screen.



Total amount: 21,000 yuan
Generally, the template engine template may be written as follows:



Total amount: {format_total} RMB
In their PHP program, write as follows:


$ Total = 21000;
$ Tpl-> assign ("total", $ total );
$ Tpl-> assign ("format_total", number_format ($ total ));
?>




The Smarty template can be written as follows: (the number_format modifier can be downloaded from the Smarty official website)



Total amount: <{$ total | number_format: ""}> RMB
In the PHP program of Smarty, write as follows:


$ Total = 21000;
$ Tpl-> assign ("total", $ total );
?>




Therefore, in Smarty, we only need to specify the variable once and leave the remaining variable to the template. Do you understand this? This is the benefit of making the template decide the display style of variables on its own!

Control template content

Duplicate blocks

In the Smarty sample, there are two ways to repeat a block: foreach and section. In the program, we need an assign array, which can contain an array. As in the following example:

First, let's look at how the PHP program is written:

Test2.php:


Require "main. php ";
$ Array1 = array (1 => "apple", 2 => "pineapple", 3 => "banana", 4 => "happy ");
$ Tpl-> assign ("array1", $ array1 );
$ Array2 = array (
Array ("index1" => "data1-1", "index2" => "data1-2", "index3" => "data1-3 "),
Array ("index1" => "data2-1", "index2" => "data2-2", "index3" => "data2-3 "),
Array ("index1" => "data3-1", "index2" => "data3-2", "index3" => "data3-3 "),
Array ("index1" => "data4-1", "index2" => "data4-2", "index3" => "data4-3 "),
Array ("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3 "));
$ Tpl-> assign ("array2", $ array2 );
$ Tpl-> display ("test2.htm ");
?>




The template is written as follows:

Templates/test2.htm:




Test duplicate blocks


  
Use foreach to present array1
<{Foreach item = item1 from = $ array1}>
<{$ Item1}>
<{/Foreach}>
Use section to present array1
<{Section name = sec1 loop = $ array1}>
<{$ Array1 [sec1]}>
<{/Section}>
Use foreach to present array2
<{Foreach item = index2 from = $ array2}>
<{Foreach key = key2 item = item2 from = $ index2}>
<{$ Key2 }>:< {$ item2}>
<{/Foreach}>
<{/Foreach}>
Use section to present array1
<{Section name = sec2 loop = $ array2}>
Index1: <{$ array2 [sec2]. index1}>
Index2: <{$ array2 [sec2]. index2}>
Index3: <{$ array2 [sec2]. index3}>
<{/Section}>







After the preceding example is executed, we find that the execution results of both foreach and section are the same. So what is the difference between the two?

The first difference is obvious, that is, foreach needs to present the two-layer array variables of our assign in the form of nest processing, while section uses the "main array [Loop name]. sub-array index "to present the entire array. From this we can see that the foreach of Smarty in the template is the same as the foreach in PHP, while the section is the description developed by Smarty to process the array variables listed above. Of course, this is not just the function of section. in addition to the nested data presentation mentioned in the next section, several application examples of section are also provided in the official manual.

However, it should be noted that the array index thrown to the section must be a positive integer starting from 0, that is, 0, 1, 2, 3 ,.... If your array index is not a positive integer starting from 0, you must use foreach to present your data. You can refer to this article in the official forum to discuss section and foreach usage.

Presentation of Nest data

The most annoying thing about the template engine is the presentation of nest-like data. many famous template engines specifically emphasize this, but it is a pediatrics for Smarty.

For the most common nest data, let's talk about the topic area in the attention program. Assume that the result to be presented is as follows:

Announcement area

Website service announcement

Literature area

Introduction to good books

Qiwen

Computer area

Hardware Peripheral

Software discussion

In the program, we take static data as an example:

Test3.php:


Require "main. php ";
$ Forum = array (
Array ("category_id" => 1, "category_name" => "announcement area ",
"Topic" => array (
Array ("topic_id" => 1, "topic_name" => "website announcement ")
)
),
Array ("category_id" => 2, "category_name" => "文 ",
"Topic" => array (
Array ("topic_id" => 2, "topic_name" => "Good book introduction "),
Array ("topic_id" => 3, "topic_name" => "surprise ")
)
),
Array ("category_id" => 3, "category_name" => "computer area ",
"Topic" => array (
Array ("topic_id" => 4, "topic_name" => "hardware peripherals "),
Array ("topic_id" => 5, "topic_name" => "software discussion ")
)
)
);
$ Tpl-> assign ("forum", $ forum );
$ Tpl-> display ("test3.htm ");
?>




The template is written as follows:

Templates/test3.htm:



Nested loop test














<{Section name = sec1 loop = $ forum}> <{Section name = sec2 loop = $ forum [sec1]. topic}> <{/Section}><{/Section}>
<{$ Forum [sec1]. category_name}>
<{$ Forum [sec1]. topic [sec2]. topic_name}>







The execution result is the same as the example given by the author.

Therefore, in the program, we only need to find a way to plug a layer of repeated values into the array, and then use the <{first layer Group [Loop 1]. the second layer Group [Loop 2]. layer 3 array [Loop 3]... array index}> to display the values in each nested loop in this way. What method is used? In the next section, we will discuss how to use the database.

Convert data in the database

We mentioned how to display nested loops. In fact, our data may be captured from the database during application, therefore, we have to find a way to convert the database data into the above multi-array form. Here, the author uses a database category to capture information in the database, you can use your favorite method.

We only modify the PHP program, and the template is the one above (this is the benefit of the template engine ~), Here, the $ db object is assumed to have been established in main. php, and the obtained information is the above example.

Test3.php:


Require "main. php ";
// Create the first layer group first
$ Category = array ();
$ Db-> setSQL ($ SQL1, @ # CATEGORY @#);
If (! $ Db-> query (@ # CATEGORY @ #) die ($ db-> error ());
// Capture the first layer of circular data
While ($ item_category = $ db-> fetchAssoc (@ # CATEGORY @#))
{
// Create a second-tier group
$ Topic = array ();
$ Db-> setSQL (sprintf ($ SQL2, $ item_category [@ # category_id @ #]), @ # TOPIC @#);
If (! $ Db-> query (@ # TOPIC @ #) die ($ db-> error ());
// Capture the second-level circular data
While ($ item_topic = $ db-> fetchAssoc (@ # TOPIC @#))
{
// Push the captured data into the second layer Group
Array_push ($ topic, $ item_topic );
}
// Specify the second layer Group as a member of the data captured by the first layer Group
$ Item_category [@ # topic @ #] = $ topic;
// Push the first layer of data into the first layer Group
Array_push ($ category, $ item_category );
}
$ Tpl-> assign ("forum", $ category );
$ Tpl-> display ("test3.htm ");
?>




After the database captures a piece of data, we get an array containing the data. Using the while statement and the array_push function, we can insert data in the database into the array. If you only use a single-layer loop, remove the second-layer loop (the red part.

Determines whether the content is displayed.

To determine whether to display the content, we can use the if syntax for selection. For example, if the user has logged in, our template can be written as follows:

<{If $ is_login = true}>
Show user operation menus
<{Else}>
Display the input account and password form
<{/If}>

Note that there must be at least one space character on both sides of the "=" sign. Otherwise, the Smarty cannot be parsed.

For the general application of if syntax, refer to the official instructions, so I will not introduce it here. However, I found an interesting application: it is often seen that a table is generated in the program: (numbers represent the sequence of data sets)

1 2

3 4

5 6

7 8

This is what I call "horizontal repeat table 」. Its features are different from the traditional vertical repetition. the duplicate tables we see in the previous sections are from top to bottom, with only one piece of data in one column. The horizontal repeat table can generate n pieces of data in one column horizontally, and then replace the next column until the entire loop ends. To achieve this function, you only need to combine section and if in the simplest way.

Let's take a look at the following example:

Test4.php:


Require "main. php ";
$ My_array = array (
Array ("value" => "0 "),
Array ("value" => "1 "),
Array ("value" => "2 "),
Array ("value" => "3 "),
Array ("value" => "4 "),
Array ("value" => "5 "),
Array ("value" => "6 "),
Array ("value" => "7 "),
Array ("value" => "8 "),
Array ("value" => "9 "));
$ Tpl-> assign ("my_array", $ my_array );
$ Tpl-> display(@#test4.htm @#);
?>




The template is written as follows:

Templates/test4.htm:



Horizontal repeat table test












<{Section name = sec1 loop = $ my_array}> <{If $ smarty. section. sec1.rownum is p by 2}> <{/If}><{/Section}>
<{$ My_array [sec1]. value}>







The focus is on the smarty variable $ Smarty. section. sec1.rownum. in the section loop, this variable will get the index value starting from 1. Therefore, when rownum can be split from 2, it will outputChange Table columns (note! YesIn front). Therefore, number 2 is the number of data records we want to present in a column. You can change other different rendering methods.

Load external content

We can load the PHP program code or another sub-template in the template, using the pair de_php and include two Smarty template syntaxes. The author of pair de_php is rarely used. you can query the official manual for usage, this is not described here.

When using include, we can pre-load the subtemplate or dynamically load the subtemplate. Pre-loading is usually used with a common file header and copyright notice, while dynamic loading can be used in a unified framework page, and further achieve a Winamp-like Skin. Of course we can also mix these two types, depending on the situation.

Let's take a look at the following example:

Test5.php:


Require "main. php ";
$ Tpl-> assign ("title", "Include test ");
$ Tpl-> assign ("content", "This is the variable in template 2 ");
$ Tpl-> assign ("dyn_page", "test5_3.htm ");
$ Tpl-> display(@#test5_1.htm @#);
?>




Template 1 is written as follows:

Templates/test5_1.htm:




<{$ Title}>


<{Include file = "test5_2.htm"}>

<{Include file = $ dyn_page}>
<{Include file = "test5_4.htm" custom_var = "custom variable content"}>






Template 2 is written as follows:

Templates/test5_2.htm:

<{$ Content}>
Template 3 is written as follows:

Templates/test5_3.htm:

This is the content of Template 3.
Template 4 is written as follows:

Templates/test5_4.htm:

<{$ Custom_var}>
Note the following points: 1. the template position is based on the previously defined template_dir; 2. the variables in all the include child templates will also be interpreted .; 3. you can use "variable name = variable content" in "include" to specify the variables contained in the introduced template, as in Template 4 above.

Bytes. In fact, I don't dare to touch it. But when I analyzed the XOOPS program architecture ,...

Related Article

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.