PHP Template engine smarty_php Basics

Source: Internet
Author: User
Tags bz2 data structures exception handling php class php code php script php template php website

The logical layer and presentation layer of the MVC development pattern in PHP has a variety of template engines to choose from, but when the official engine Smarty is born, the choice changes. Its idea and realization are quite "avantgarde". This paper mainly discusses the different characteristics of smarty to other template engines, briefly introduces the installation and use of the engine, and compares the speed and ease of smarty and phplib template with a small test case.

One, MVC needs template
MVC was the first design pattern to be summed up in the development of Smalltalk language, and MVC represented "model", "View" and "control" respectively, so that different development roles could be involved in large and medium-sized projects. In the development of Web applications, the following diagram can be used to represent the relationships among the concepts.


The diagram shows a simple Web application in which the user sees the information on the database server, but before it is processed by the application server. What developers are responsible for is building data structures, processing the logic of data, and methods of representing data.

When the 96 CGI became popular in China, early web programmers began to learn from HTML, and it was not difficult to print a row of HTML in Perl, but as the network sped up, the page size jumped 10 times times from the original 20 or 30 K. Writing CGI programs creates an urgent requirement: Separate Perl and HTML source code. Thus, social progress is embodied in the Division of labor within the development group. Because art and programmers are not very familiar with each other's work, in the process of cooperation need to use a "language" to communicate.

This language is not our mother tongue or English, the term is called "template", logic and representation depend on it. It is an expression that combines HTML and scripting language features. In this way, the presentation layer can display data that has been processed by the logical layer in the format that the user wants. If you have the development experience of MFC under Windows platform, you will be familiar with the encapsulation of document/document Template/view, this is a typical MVC example. For Web applications, individuals think that the ejb/servlets/jsp in Java EE is the most powerful, and of course there are simple and graceful structs. Another well-known realization is com/dcom+asp, which is the most used in our country.

By comparing several MVC implementations in a Web application, you can get a concept of a template: A set of HTML-inserted scripts or scripting HTML that represents the changed data through the inserted content. The following is an example of a template file, which is processed to display "Hello, world!" in the browser.

Introduction:
--------------------------------------------------------------------------------


<title> $greetings </title>
<body>
$greetings
<body>


--------------------------------------------------------------------------------



Here for the moment to omit the treatment, in the following special comparative discussion.

Second, why Choose Smarty?
For PHP, there are a number of template engines to choose from, such as the first phplib template and the Up-and-comer fast template, after several upgrades, has been quite mature and stable. If you are satisfied with the current template engine, then ... Also look down and believe that you as a free software enthusiast or for the pursuit of efficiency and elegance of the developers, the following Smarty introduced how much will be somewhat interesting.

In addition to the impact of personal preferences, I have tended to use official standards for implementations such as Apache's XML engine axis. The advantage is that you get as good a compatibility as possible (for example, early MFC's compatibility with WIN3X is better than other application frameworks, but now all versions are perfect). I have been using the integrated Template eXtension in Pear before Smarty released. This engine is almost compatible with phplib template, Fast template, from the syntax of the template to the processing of the template expatiating: All the templates are read into memory and then called the Parse () function, replacing the preset tags with the data.

Let's see how smarty is doing. After receiving the request, first decide whether to request the URL for the first time, if it is, the template file required for the URL "compiled" into a PHP script, and then redirect; if not, it means that the template for the URL has been "compiled", checking that you do not need to recompile to immediately redirect , the recompile condition can be set to its own fixed time limit, and the template file is modified by default.

What, does it look a little familiar? Come to think of it--this is not the principle of JSP! It is true that this "compilation" is unthinkable in an interpretative scripting engine such as PHP, but is Java not also interpreted by the JVM? This is called "nothing can not be done, only unexpected."

Now that we've talked about Java, let's comment on the future of PHP. The official PHP website announced the release of the PHP5.0 version by the end of 2003. This version has many new features: exception handling, namespaces, more object-oriented, and more. It can be said that more and more to the Java, Smarty is also one of the new features, making PHP more suitable for large and medium-sized project development. But it seems that the reason I chose it--the deft use of it--is getting far. But in terms of the life cycle of a software, PHP is in the growth period, the developer gives it more functions, in order to be able to do business applications is more advantages than disadvantages. As a loyal user of PHP, you certainly don't want PHP to always be blamed for "lack of capacity"?

Why choose Smarty just because it looks like a JSP? There are, of course, more good reasons. First of all, in addition to the cost of the first compilation is relatively high, as long as the template file is not modified, compiled cache script is available at any time, save a lot of parse (), and then smarty like PHP has a rich library of functions, from counting words to automatic indentation, Text wrapping and regular expressions can be used directly, if not enough, such as the need for data results set paging display function, Smarty also has a strong ability to expand, through the form of plug-ins can be expanded.

Facts speak louder than words. I designed a test program that compares Smarty and phplib template with speed and development difficulty, and phplib template because there is a phplib in Patrick's article, "Choosing the right template in the PHP world." Template to fast template competition, the result phplib template swept, this makes smarty have a good opponent. Before testing, talk about the issues you need to be aware of during the installation process.

Iii. problems that may be encountered
On the official website of Smarty, there is a detailed user manual that allows you to select online HTML and PDF versions. There is no longer a reference to what is already in the manual, but an explanation of the problems that may be encountered in the first use.

The first question is fatal: Does the hint say you can't find the file you want? Not everyone writes the application according to the Smarty default directory structure. This needs to be manually specified, assuming the directory structure is as follows:


You need to specify the directory structure in index.php:
Introduction:
--------------------------------------------------------------------------------

$smart->template_dir = "smarty/templates/";
$smart->compile_dir = "smarty/templates_c/";
$smart->config_dir = "smarty/configs/";
$smart->cache_dir = "smarty/cache/";


--------------------------------------------------------------------------------



The first problem was solved, followed by the second: how can I use the beautiful template I just created with Dreamweaver? It is not a problem with the template file, but because the default tag delimiter for Smarty is {}, and unfortunately JavaScript certainly contains this tag. Fortunately we can use any character as a separator, plus these two sentences:
Introduction:
--------------------------------------------------------------------------------


$smart->left_delimiter = "{/";
$smart->right_delimiter = "/}";


--------------------------------------------------------------------------------



This installation is basically done, no problem.

Iv. contrast and analogy
First conceive the design of the test. The main factor of comparison is speed. In order to carry out the speed test, the arithmetic mean is adopted. In the test page, repeat the page generation n times, and then compare the total page generation time. Another important factor is ease of use (as far as extensibility does not have a result to compare), so the template used cannot be too small. I use the page of my personal homepage, an HTML file generated with Firework+dreamweaver, about 7K in size. One of the variable settings also take the most commonly used blocks, in the phplib template called block, and Smarty is called section. Don't underestimate the difference of the name, the ease of use standard is divided into two: template file and script file syntax is concise and easy to use.


Let's drill down to the test. First look at the syntax of the two template files: the blue bar to the left is the Phplib template template, the right belongs to Smarty. Personal preference is not the same, so there is no comment here. Focus on the processing statements in the script, first look at the Phplib template:
Introduction:
--------------------------------------------------------------------------------


$tpl->set_file (' phplib ', ' bigfile.htm ');
$tpl->set_block (' phplib ', ' Row ', ' rows ');
for ($j = 0; $j < $j + +) {
$tpl->set_var (' tag ', "$j");
$tpl->parse (' Rows ', ' Row ', true);
}
$tpl->parse (' Out ', ' phplib ');
$tpl->p (' out ');


--------------------------------------------------------------------------------


Here are the Smarty:

Introduction:
--------------------------------------------------------------------------------

$smart->assign (' Row ', $row);
$smart->display (' bigfile.htm ');

--------------------------------------------------------------------------------



Smarty only used tags and row two variables, and phplib template more templates file handler, there is a baffling out. To tell the truth of this out I did not know why to exist when I learned, now look, or awkward. Why smarty less so much processing statements? The answer is that the work is done by the engine. If you like to delve into the source program, you can find a function called _compile_tag () in the Smarty_compiler.class.php, which is responsible for converting the section label into a PHP statement. This is not a common label, it has parameters and data, save the workload of scripting, and the workload on the template label is not large, you can determine the ease of use on the Smarty one domain.

It's our turn to focus on the speed, after all, for a skilled web developer, it is only a matter of time to master the tools of the difficult, not to mention the template engine this learning curve of the smooth technology. Speed is the life of a Web application, especially if the template engine is used on a site with a large number of concurrent accesses. Before the test began, I felt that phplib template would win this part because it had undergone many upgrades and had almost no bugs, and Smarty's engine was too big to have two files like its opponents.

Sure enough, the test results are as follows, Phplib template has a 25% speed advantage:


But not all the time, I hit the refresh again, this time I got a different result:


The phplib basically did not change, but the smarty increased by 25%. Continuing to refresh, the results are similar to the second: Smarty is nearly 10% faster than Phplib template. I think this is the principle that the compiler is faster than the explanatory type. Smarty engine itself is very large, coupled with the template to compile into PHP files, of course, the speed is not as small as the phplib template. But this is only the first time. The second time the request was received, Smarty found that the template had been compiled, and the most time-consuming step was skipped, and the opponent had to find and replace the job in a step-by-steps manner. This is the compiler principle of the classic "Space Change Time" example.

V. Conclusion
The conclusion is that if you have fallen in love with smarty, what are you waiting for? Certainly not that it's omnipotent, just as I use the MVC pattern to write my personal site, instead of reducing the workload, but always for the coupling between different levels.

What does Smarty do for you? A classic example of a handbook: weather forecasting websites. I also think of one: the stock market. The use of Smarty on this site will be due to the frequent recompilation and low efficiency, or phplib template more suitable.

This article is not meant to compare the two engines, but to illustrate the advantages of smarty. The most significant thing about using it is that it is part of the new PHP system, as an independent force, except. NET and Java one, there are other options for large and medium web development. For the GNU project, its significance is tantamount to Liu Deng's army leaps into the Dabie mountains.

Reference documents

Smarty Official site: smarty.php.net
Wang: Choosing the most suitable template in the PHP world
Download the test program in this article: test.tar.bz2
http://phpe.net/uploads/attach/article_1058233528.bz2
About the author
Yuboxiang, the pseudonym Ulles from the University of Economics and engineering information. GNU addicts, like to practice a variety of programming languages, study various system framework.

Post Number: 1275 reply: With a lot of PHP script will use Smarty as the core engine, and Smarty in the end what is it? 2003-08-10 14:07

Choose the most appropriate template in the PHP world--Compare phplib template and Fasttemplate



The template application in PHP engineering is a good way to handle the presentation layer recommended in medium and large projects. But specific to the implementation of the template, the use of what existing template technology needs to be compared.

There are two kinds of phplib template and Fasttemplate in the more focused template processing in the PHP world, we evaluate the usability and speed of technology-want to know the result?

The cause of the matter: Have you ever used fasttemplate?
As for the template application in PHP Engineering, my colleagues and I have already touched on a lot of projects-for the benefit of it, I think there have been a lot of "predecessors" discussed in both the actual development stage and the design pattern. As far as project implementation is concerned, in some medium-sized or even large projects, effectively the HTML (and other forms of the presentation layer) and PHP code, not only in the development phase can improve the efficiency of the interface designers and application writers, but also to the testing and maintenance of the project to bring great convenience.

But--the purpose of this article is not to discuss the pros and cons of templates, nor to teach instructional tutorials on how to use templates in PHP projects, but to compare the most popular template processing methods in the two PHP worlds with an application perspective (in fact, it's just two template classes): Phplib Template and Fasttemplate.

In fact, I have been "quiet" in the use of Phplib template--is stable and looks so good that I do not want to go to the uneasy search for a possible better alternative-although I also know that there are such things as fasttemplate on this earth (and also in Perl Famous in the world). Until one day, a colleague asked me: "Do not know how fasttemplate?" Why don't we try Fasttemplate? "

"Well, let's try it!" "But as a safe way, it's best to be able to understand it more fully before any new models or methods are introduced into the project, and find one or several reasons enough to convince yourself and your colleagues to adopt it--for fasttemplate."

Protagonist appearances: Understanding Phplib template and Fasttemplate
As I have said before, I have been using phplib for some time-I think you may be just like me in front of the screen and very impressed with this excellent tool class library. Again, when I started looking for a template solution, it was natural to search the toolbox closest to me, so I found the template class in Phplib. After first browsing through its API (and, of course, thanking Phplib for detailed documentation), I began the process of using it-until now.

And Fasttemplate seems to be a bit more famous, naturally in the Perl world of its own making, and it seems to be in the PHP world alone enough to convince people of its power.

On the use of both the method, I would like to have a few more nonsense here; but after all, I'm afraid I'm probably writing two tutorials and no existing tutorials are popular--in the resources of this article there's a famous tutorial on phplib template and fasttemplate, if you Recognize that there is no understanding of these two templates or one of them, I suggest you go to see the two articles, you should get a lot of useful template application knowledge.

(Some mouse clicks and eye movements even after writing the test code in person) now that you have some understanding of both templates, you may have found a lot of similarities between them, and I will summarize these places below.

Settings for variables
It is obvious that the form of {FOO} or {BAR} is in the specified form in both templates; that is, the template file itself should look consistent in both template processing (for example, all of the HTML files contain a variable that will be replaced with the {} identified in the middle).
Initialization of template classes (builder of classes)
You need to specify the directory location where the template file exists when you build the template class.
Substitution of variables
The most commonly used in template processing is variable substitution, both ways except for the method name (phplib template uses Set_var (), and Fasttemplate uses assign ()), which is almost consistent with the use of (key, value) , you can also pass an array (array (key=>value)) directly.
Processing of template files
is a way to specify a handle (handler) for each template file, and the handle can also replace the variable in another template file as the value of the variable.
Parsing, output process
It is necessary to invoke the parse () method (the method name is the same) to parse the template file that needs to be output and assign it to a handle, and then invoke the method of the respective output (phplib template is P (), Fasttemplate is Fastprint ()) loses The contents of the handle and end the processing.
The process of repeating parsing
For example, a few records from the database need to show that the template file only can be replaced by a row of variables, it is very necessary to this function. Both have this functionality, but are slightly different when used (phplib template uses parse (handler, value, True) and fasttemplate with parse (handler,. Value) Add a point to the front of the value), it should be said that the Phplib template method is relatively graceful.
The process of block parsing (or it can be called dynamic parsing)
Imagine that you need to take the qualifying data out of the database and display it in a Web page--but because the conditions are different, you don't know exactly how many data you're going to have--and if you have to adopt a template then the block is the best choice. It is the part of the template that is defined with a specific symbol that can be parsed and added to the output page (rather than the previous parse being overwritten later). The blocks may be as shown below (The block setting on the left is the Phplib template, and the fasttemplate on the right):



Well, if you're still a little confused about the pale text, let's take a look at the two detailed template processing routines! (If you are interested in discovering the following test code, you will find that two examples are actually from there.)


How does it feel to be almost the same? Here is an example of block parsing, and you'll find the same effect:


Our testing objectives and results
End of the Phplib template and fasttemplate Understanding, should be able to go to the point of this article--in the application environment, of course, you should choose easy to use the same speed of the ideal parts building system, then for such two similar technologies, it is necessary to evaluate. The evaluation should be made up of two parts: the degree to which technology is used and the speed at which the former is part of the review, while the latter is part of the test. For the former, we comment primarily on the APIs provided by the two classes; for the latter, we will let the data of the test speak, and of course there is a need to write some simple test code.

Round one: Ease of use of technology
This round is focused on the use of APIs provided by Phplib template and Fasttemplate. It should be said that the API provided by the former is more consistent with some of the common coding conventions in PHP (especially when you use other classes of phplib in your project, such a norm would have a good effect on the whole project), while some of the latter's methods were somewhat awkward (I hope you don't think it's just my narrow view, like Fastprint () and so on), the parameters of the method are not very "authentic", which you can also see from the code just now.

Another point to note is that for the parsing of the template blocks, Fasttemplate is not supported until the most recent version. That is, if you're using a previous version, you have to store the content separately somewhere, and then attach the file to the template analysis process--it's really unpleasant, especially for web designers, to work with the output of records in the database.

Of course there is one more thing to look at--that's support for PHP versions. Phplib was produced in the PHP3 era, which was similar to fasttemplate, but according to our application, Phplib is quite good in the current PHP4 environment and Fasttemplate's web page shows some information indicating that there may be some bugs for PHP4.

Well, that's a lot to talk about (maybe you'll think it's all fasttemplate), the winner of this round is obvious: Phplib Template, especially when you're using Phplib's other classes, this technique is more user-friendly (you won't be able to Unfamiliar with the API of a development team).

Round two: processing speed
Maybe that's what a lot of people are most concerned about--in this round, we will use two types of template processing: one is the normal analysis, substitution, the other is the block parsing, replacement-and this is also the two ways in the actual system to apply the most: the former is the General page processing, The latter is about the output processing of the database content. At the same time, because the template file format of the two template classes is basically the same, we can provide almost consistent template file for two template parsing, which increases the reliability of the test.

This speed test will be developed before a test plan, simply to two different processing methods to write two PHP test pages, while there is a control of the test page multiple calls to the two pages and record the time to collect test data. (If you are interested you can also refer to the following detailed test plan, you may be more in-depth understanding of this test will help)

Summary-After the entire test system is complete, we should be able to get a list of the following files in the/test directory:

(a bit of a complex test scenario)

The first is to determine the test hardware and software environment-the hardware must be its own machine, the Intel Celeron 733MHz, 256M ram,40g HDD; the OS in the software platform is apache+php for Win2K Pro,web Server and operates as a module.

The second is the system that plans this test--of course, start with a tpl_test new directory in the Web server's document root directory to place all of this test files, and then create an include directory under/tpl_test to store two template class files (the core of our testing, With the. inc.php as the file name extension, and a test class file (which includes functions such as timing and logging, reading logs and parsing, and so on) and a data file (which prepares for the test of the chunk parsing, includes a two-dimensional array of inc.php). Same with. inc.php for file extension), set up ihtml directory to use template files (need to be resolved template files, to. ihtml for file extension), build logs directory store test generated log (after that, in fact, the test data is from the analysis of these logs , with. Log as the file name extension). Of course, the two template processing php file is placed in the/test directory. The key point of this test is that you also need to create a PHP file, the above mentioned in charge of the template processing of the file to make several calls: for example, a file fast_test.php is a fasttemplate parsing template, and phplib_ Test.php is a phplib Template resolution, then the results of the PHP file is responsible for multiple HTTP to request the above two pages to obtain test data.

Select the template to be resolved and the PHP program written--because both template processing is almost consistent with the format requirements of the template file itself (for example, to replace variables in the form of {VAR}, and so on), so you can try to ensure that the template used in the same test is the same as possible for the At the same time as mentioned in the preceding article, two kinds of template applications commonly used in the simulation system: the General page processing and the output processing of the database content, and the template files used in the test are divided into two kinds: one is the common template file with some variables to be replaced, and the other is the one with the block needed according to the output Template files that are repeatedly replaced by content. Also for these two template files, you need to write two different PHP files for parsing.

Test Method--in the browser to/test/result.php request, with parameters Type=[simple|complex], in the returned results can be seen in the two templates in simple or complex mode test results.

Level 1
Level 2
Level 3
Remark

/test


The root directory of the test system







result.php

A PHP file that tests and produces results, testing with the need to request the page in the browser to obtain the test information


simple__test_phplib.php

PHP files that use Phplib template to parse a generic template


simple__test_fast.php

PHP files that use Fasttemplate to analyze a generic template


complex__test_phplib.php

Use Phplib template to parse a php file with a block template


complex__test_fast.php

Using Fasttemplate to parse a php file with a block template







/include

Contains PHP class files. inc.php



phplibTemplate.inc.php
Phplib template class file



FastTemplate.inc.php
Fasttemplate class file



TplTest.inc.php
Test classes that need to be used in the test, including methods such as timing, read/analyze logs, and so on.



data.inc.php
Test the data file used with the block template.







/ihtml

Contains template files. ihtml



Simple_phplib.ihtml
Generic template files with Phplib template processing



Simple_fast.ihtml
Generic template file with fasttemplate processing



Complex_phplib.ihtml
Block-phplib template files with template processing



Complex_fast.ihtml
A block template file with fasttemplate processing







/logs

Contains log files.



Simple_phplib.log
Using Phplib template to process a log generated by a generic template



Simple_fast.log
Using Fasttemplate to process a log generated by a generic template



Complex_phplib.log
Using Phplib template to process logs generated with block templates



Complex_fast.log
Using Fasttemplate to process logs generated with block templates

After the design and writing of the test system, and the two templates for the Web design colleagues, we can access the system--------------------------------------------- Result.php?type=[simple|complex] (if you are doing this test on a different non-local server, the domain name should be the domain name of the server on which it is located-for example, my own machine is called Patrick, etc.). Here's what I've achieved in one test: (test result data explanation)

Name
Explain
Note

Amount
Total number of tests (total number of consecutive requests for this page)
This parameter can be modified in the result.php file

Max_seq
Serial number of the maximum processing time
Range between the 1-amount

Max_value
The value of the maximum processing time
Peak data for reference

Min_seq
Number of minimum processing time
Range between the 1-amount

Min_value
Value of minimum processing time
Peak data for reference

Average
Average processing time
The most valuable data in a test


Of course, if you think that the results of a test are not reliable, you can repeatedly press the browser refresh button, you can observe the different test

The result (should be roughly the same in theory).

Test results and issue "XX Selection Award"
Well, in the second leg of the speed-weighted test, phplib template beat Fasttemplate at an astonishing twice times, while in the first round phplib template had the upper hand with good API design and ease of use. The result is obvious-our choice award is certainly given to Phplib Template, and this test also gives us a deeper understanding of Phplib's class library design.

Subjective evaluation
Now that we have the result, fasttemplate will naturally not be able to enter our project-although it seems that we spent half a day in the results of a fruitless outcome (phplib template continues to work well on the project), but the process of testing is valuable, In particular, the use of PHP testing methods, should be in the future of similar decisions to play a certain reference role.


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.