PHP Template Engine smarty_php Tutorial

Source: Internet
Author: User
Tags php template php website
The logical and presentation layers of the MVC development model in PHP are available in a variety of template engines, but when the official engine Smarty is born, the choice changes. Its concept and implementation are quite "avant-garde". 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 usability of Smarty and phplib template with a small test case.

First, MVC needs templates
MVC was the first design pattern that was summed up in the development of the Smalltalk language, and MVC represented "model", "View" and "control", respectively, in order to make different development roles perform in large and medium-sized projects. In the development of network application, it can be used to express the relationship between 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. Developers are responsible for building data structures, the logic of processing data, and methods of representing data.

When CGI began to pop in China in 96, early Web programmers began learning from HTML, and it was not difficult to print a line of HTML in Perl, but as the network stepped up, the page size soared 10 times times from the original 20 or 30 K. Writing CGI programs creates an urgent requirement: to separate Perl from the HTML source. Thus, social progress is embodied in the Division of labor within the development group. Because artists and programmers are not very familiar with the work of each other, in the process of cooperation need to use a contractual "language" to communicate.

This language is not our mother tongue or English, the term is called "template", logic and expression rely on it to contact. It is a form of 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 the Windows platform, then you will be familiar with the Document/document Template/view package, which is a typical example of MVC. For Web applications, the ejb/servlets/jsp is the most powerful and, of course, a concise and graceful structs. Another well-known implementation is com/dcom+asp, which is the most used in our country.

By comparing several MVC implementations in Web applications, you can get a concept about templates: A set of HTML-inserted scripts or inserted script HTML to represent the changed data through this inserted content. Here is an example of a template file that is processed and displayed in the browser "Hello, world!"

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




<title>$greetings</title>


$greetings




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



This is omitted for the moment, and is discussed in detail later.

Second, why Choose Smarty?
For PHP, there are a number of template engines to choose from, such as the first phplib template and the Rising Star fast template, after several upgrades, has been quite mature and stable. If you are satisfied with the template engine currently in hand, then ... Please also look down, I believe you as a free software enthusiast or the pursuit of efficiency and elegant developers, the following smarty how much will be a bit of meaning.

In addition to the impact of personal preferences, I have been inclined to use the official standards of implementation, such as Apache's XML engine axis. The advantage is that you get the best possible compatibility (such as early MFC's compatibility with WIN3X is better than other application frameworks, and of course the various versions are now perfect). I have been using the integrated Template eXtension in Pear before Smarty was released. This engine is almost compatible with the Phplib template, Fast template, from the syntax of the templates to the processing of templates expatiating: it reads the template into memory and then calls the parse () function, replacing the preset tag with data.

Let's see how smarty is doing. After receiving the request, first determine whether the URL is requested for the first time, if so, the template file required for the URL "compiled" into a PHP script, and then redirect, if not, that is, the URL template has been "compiled", check do not need to recompile can immediately redirect , the recompile condition can be set to a fixed time limit, and the default is that the template file is modified.

What, does it look familiar? Remember--this is not the principle of JSP! It is true that this "compilation" is unthinkable on an explanatory scripting engine such as PHP, but think about it that Java is not being interpreted by the JVM. This is called "No can not do, only unexpected."

Now that we've talked about Java, I'll make a little bit of a comment on PHP's future. 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 toward 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--smart and easy to use--is getting farther away. But in terms of the lifetime of a software, PHP is growing, and developers are giving it more functionality to be competent for business applications that outweigh the disadvantages. As a loyal user of PHP, certainly do not want PHP is always accused of "insufficient capacity" it?

Why choose Smarty, just because it looks like a JSP? There are, of course, better reasons. First, in addition to the high cost of the first compilation, as long as the template file is not modified, the compiled cache script is readily available, eliminating a large number of parse () time, followed by smarty like PHP has a rich library of functions, from the count of words to automatic indentation, Text wrapping and regular expressions can be used directly, if not enough, such as the need for data result set pagination display function, Smarty also has a strong ability to expand the form of plug-ins can be expanded.

Truth speaks louder than eloquence. I designed a test program that compares the speed and development difficulty of the smarty and phplib template, choosing Phplib template because there is a phplib in Patrick's article "Choosing the most appropriate template in the PHP world" Template to Fast template contest, the result Phplib template victory, this makes Smarty have a good opponent. Before testing, talk about the issues that 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 the online HTML and PDF versions. There is no longer a reference to what is already in the manual, just an explanation of the problems that may be encountered in the initial use.

The first question is very deadly: the hint that you can't find the file you need? Not everyone writes the app according to the Smarty default directory structure. This needs to be specified manually, assuming the directory structure is as follows:


You need to specify the directory structure in the 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 is solved, followed by the second one: how can I not use the beautiful template I just created with Dreamweaver? This is not a problem with the template file, but because the default tag delimiter for Smarty is {}, and unfortunately JavaScript definitely contains this tag. Fortunately, we can use any character as a delimiter, plus these two sentences:
Introduction:
--------------------------------------------------------------------------------


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


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



This installation is basically done, no problem.

Iv. Contrasting and analogy
Consider the design of the test first. The main factor of evaluation, of course, is speed. In order to carry out the speed test, the arithmetic mean is adopted. Repeat the page generation n times in the test page, and then compare the total page generation time. Another important factor is ease of use (as far as extensibility is not compared to the results already), so the template used cannot be too small. I use the page of my personal homepage, a HTML file generated with Firework+dreamweaver, about 7K in size. The variable settings also take the most commonly used chunks, called block in the Phplib template, and Smarty is called section. Don't underestimate the difference, the usability standard is divided into two pieces: whether the syntax of template files and script files is simple and easy to use.


Here's the drill down to the test. First look at the syntax of the two template files: The left side of the blue bar is the template for Phplib templates, and the right side belongs to Smarty. Personal preferences are not the same, so there is no comment here. Focus on the comparison of the script in the processing statements, 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 is more templates file handler, there is an inexplicable out. Honestly this out I did not know why to exist when I first learned, now looks, still awkward. Why is 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 see that there is a function called _compile_tag () in the Smarty_compiler.class.php, which is responsible for converting the section tag into a PHP statement. This is not an ordinary label, it has parameters and data, saving the workload of script programming, and the workload on the template label is not small, can be judged in the ease of smarty a domain.

It's our turn to focus on the speed, after all, for a skilled web developer, mastering the difficult tools is only a matter of time, not to mention the template engine, the learning curve of the gentle technology. The speed is the life of the Web application, especially when the template engine is used on sites with a large number of concurrent accesses. Before the test started, I thought the phplib template would win in this segment, because it went through many upgrades, had basically no bugs, and Smarty's engine was too big to be like its opponent with only two files.

Sure enough, the test results, such as the Phplib template, have a 25% speed advantage:


But not always, I pressed a refresh again, this time got a different result:


Phplib basically hasn't changed, but Smarty has increased the speed by 25%. Continue to refresh, the results are similar to the second result: Smarty is nearly 10% faster than the Phplib template. I think this is the compiler is faster than the interpretation of the principle of the type. Smarty The engine itself is very large, plus also to compile the template into PHP files, the speed of course, compared to the small phplib template. But this is only the first time. The second time the request was received, Smarty found that the template had been compiled, so the most time-consuming step was skipped, and the opponent had to perform the search and replace work in a methodical way. This is the very classic "space-for-time" example in the compilation principle.

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

What does Smarty not fit? A classic example of a handbook: The Weather Forecast website. I also think of one: the stock market. The use of smarty on such websites is less efficient due to frequent recompilation, or phplib template is more suitable.

This article is not 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 medium-to-large web development. For the GNU project, the significance of this is tantamount to Liu Deng's army Trinidad and the Dabie Mountains.

Reference documents

Smarty Official site: smarty.php.net
Wang Chen: "Choosing the most appropriate 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, pen name Hulet from the University of Economics and information. GNU addict, who likes to practise a variety of programming languages, studies various architectural frameworks.

Posts: 1275 replies: With a lot of PHP script will use Smarty as the core engine, and smarty exactly what is it? 2003-08-10 14:07

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



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

The more focused templates in the PHP world are handled by the Phplib template and the Fasttemplate two, and we've evaluated the ease of use and speed of the technology--want to know the results?

The cause of the matter: Have you ever used fasttemplate?
As for the template application in PHP Engineering, my colleagues and I have already been exposed to a number of projects--about its benefits, and I think there has been a lot of "senior sages" discussed both in the actual development phase and the rise to the design pattern. In terms of project implementation, in some medium-sized or even large-scale projects, the effective use of HTML (as well as other textual representations) and PHP code, not only in the development phase can improve the productivity of interface designers and application writers, but also to the project testing and maintenance of great convenience.

However-the purpose of this article is not to discuss the pros and cons of templates, or to teach you how to use templates in a PHP project, but rather to compare the most popular template processing methods in the two PHP worlds using an application perspective (in fact, just two template classes): Phplib Template and Fasttemplate.

In fact, I have been "quiet" in the use of Phplib template--is very stable and looks very good speed, so that I do not want to be disturbed to find a possible better alternative-although I also know that there are fasttemplate such things on the Earth (and also in Perl The world's most famous). Until one day, a colleague asked me: "Do not know how fasttemplate?" Why don't we try Fasttemplate? "

"All right, let's try!" "But as a sound method, it would be better to have a fuller understanding of it before any new models or methods are introduced into the project, and to find one or several reasons enough to persuade yourself and your colleagues to adopt it--for fasttemplate," he said.

Protagonist appearances: Understanding Phplib template and Fasttemplate
As I've already said, I've been using phplib for a while--I think you might be as good as I am in front of the screen, and I'm impressed with the excellent tool library. Again, when I started looking for a solution to the template, it was natural to search in the toolbox closest to me, so I found the Phplib class. After the initial browsing of the APIs it provided (and, of course, thanks to Phplib's exhaustive documentation), I began to use it-until now.

And fasttemplate seems to be more famous, in the Perl world of his fortune, and in the world of PHP, it seems that it is enough to convince people of its power alone.

On the use of the two ways, I would like to have a few more nonsense here, but after all, I am afraid to write two tutorials and no existing tutorials are popular-in the reference to this article there is a famous tutorial on phplib template and fasttemplate, if you Do not recognize the two templates or one of them, it is recommended that you first look at those two articles, you should get a lot of useful template application knowledge.

(After a mouse click and eyeball rotation and even writing the test code yourself), now that you have some understanding of both types of templates, you may have found a lot of similarities between them, and I'll summarize them here.

Setting of variables
Obviously, the form of {FOO} or {BAR} is the specified form in both templates, that is, the template file itself should have a consistent appearance in both templates (for example, the HTML file contains the variable that will be replaced with the {} identifier).
Initialization of a template class (builder of classes)
It is necessary to specify the directory location where the template file exists when building the template class.
Substitution of variables
The most common use of template processing is variable substitution, in addition to the method name (phplib template takes Set_var (), and Fasttemplate uses assign ()), the usage is almost identical-can be used (key, value) way , 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 call the parse () method (the method name should be the same) to parse the template file that needs to be output to a handle, then call the respective output method (Phplib template is P (), Fasttemplate is Fastprint ()) The contents of the handle and ends the processing.
The process of repeating parsing
For example, it is necessary to remove a few records from the database to be displayed while the template file has only a replaceable row of variables. Both have this function, only slightly different when used (phplib template takes parse (handler, value, True), and Fasttemplate takes parse (handler,. Value) Add a point to the front of the value), it should be said that the Phplib template method constructs a relatively graceful point.
The process of chunk parsing (or it can be called dynamic parsing)
Imagine that you need to remove the qualifying data from the database and display it in a Web page--but because the conditions are different, you don't know exactly how many pieces of data--if you're going to use a template again, chunks are the best option. It is a part of the template that is defined with a specific symbol that can be parsed repeatedly and added to the output Web page (rather than the previous parse being overwritten). The chunk may be as shown below (the Phplib template uses the block settings on the left and the fasttemplate on the right):



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


How is it that the feeling is almost unanimous? Here's an example of block parsing, and you'll find the same effect:


Our testing goals and results
The end of the Phplib template and fasttemplate Understanding, should be able to enter the topic of this article-in the application environment of course should choose easy to use at the same time the ideal component building system, then for such two similar technologies, it is necessary to evaluate. The evaluation should consist of two parts: the difficulty and speed of the use of the technology-the former is the part of the review, and the latter is the part of the test. For the former, we mainly comment on the API provided by two classes, and for the latter, we will let the test data to speak, of course, there is a need to write some simple test code.

Turn One: The ease of use of technology
This round is primarily about the use of APIs provided by Phplib template and Fasttemplate. It should be said that the former provides an API that is more consistent with some of PHP's common coding practices (especially when you use other classes of phplib in your project, which can have a good impact on the entire project), while some of the latter's method names always feel awkward (I hope you don't think it's just my narrow view, like Fastprint (), and 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 block, Fasttemplate is not supported until the most recent version. In other words, if you use a previous version, you have to store this piece of content in a separate place when dealing with things like the output recorded in the database, and then attach the file to the template parsing process--something that's really uncomfortable, especially for web designers.

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

OK, so much to say (maybe you'll think it's all fasttemplate), the winner of this round is obvious: Phplib Template, especially if you're using Phplib's other classes at the same time, this technique is more easy to use (you won't Unfamiliar with the API of the same development team).

Turn two: processing speed
Maybe that's what many people are most concerned about--in this round, we'll take two kinds of template processing: One is regular parsing, replacing, the other is parsing and replacing chunks--and both of these are the ones that are used most in the real system: the former is the General page processing, The latter is about the output processing of the database contents. At the same time, since the template files used by the two template classes are basically the same format, we can provide almost identical template files for two template parsing, which increases the credibility of the test.

A test plan will be developed before such a speed test, which simply means that there are two PHP test pages for each of the two processing methods, and a page that controls the test calls the two pages multiple times and records the time for the test data collection. (If you are interested you can also refer to the following detailed test scenarios, may be helpful to you in-depth understanding of this test)

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 hardware and software environment of the test--the hardware must be its own machine, Intel Celeron 733MHz, 256M ram,40g HDD, the OS in the software platform is Win2K pro,web server is apache+php and is running in a modular way.

Next is the system that plans this test--of course, first open a new tpl_test directory under the Web server's document root to place all the files for the test, and then build the Include directory under/tpl_test to hold two template class files (the core of our test, With. inc.php as the file extension) and a test class file (including functions such as timing and logging and reading logs and parsing, with. inc.php as file extension) and a data file (for chunk-parsed testing, which consists mainly of a two-dimensional array, Also with. inc.php as the file extension), establish the ihtml directory to store the template files used (need to be parsed template file, with. ihtml as the file extension), to establish the logs directory to store the test generated by the log (it is found that the test data is by the analysis of these logs obtained , with. Log as the file name extension). Of course, the processing of PHP files for both templates is placed in the/test directory. The key point of this test is that you also need to create a PHP file to make several calls to the file responsible for template processing mentioned above: for example, a file fast_test.php is a fasttemplate parsing template, and phplib_ Test.php is parsed using Phplib Template, the resulting PHP file is responsible for multiple HTTP requests for the above two pages to obtain the test data.

Select the template to be parsed and the PHP program to write-because the two template processing methods for the template file itself is almost identical to the format requirements (such as the substitution of variables are in the form of {VAR}, etc.), so as far as possible to ensure that the same test in the same template as possible to seek the maximum fairness of testing At the same time, in the previous article mentioned, for the simulation of real-world systems commonly used in two template applications: General page processing and the output of the database content processing, the test template file is also divided into two types: one is a regular with some of the template file to be replaced, and the other is the need to export the block should be output A template file that is repeatedly replaced with content. Also for these two template files, you need to write two different PHP files to parse.

Test Method--in the browser request to/test/result.php, need to take parameter 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, and only needs to request the page in the browser to get the test information


simple__test_phplib.php

PHP files for analyzing generic templates using Phplib template


simple__test_fast.php

PHP files for analyzing generic templates using Fasttemplate


complex__test_phplib.php

PHP file for parsing with block templates using Phplib template


complex__test_fast.php

PHP file for parsing with block templates using Fasttemplate







/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 that was used with the block template.







/ihtml

Contains the template file. ihtml



Simple_phplib.ihtml
Generic template files that are processed using Phplib templates



Simple_fast.ihtml
Generic template file with fasttemplate processing



Complex_phplib.ihtml
Block-based template files processed with phplib template



Complex_fast.ihtml
Block-based template file with fasttemplate processing







/logs

Contains log files.



Simple_phplib.log
Use Phplib template to process logs generated by generic templates



Simple_fast.log
Use Fasttemplate to process logs generated by generic templates



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



Complex_fast.log
Using Fasttemplate to process logs generated with a block template

After the design and writing of the test system and the two templates to the colleague responsible for the web design, we can access the system--the hard work of the early days so that the work of viewing the results now only needs to enter the http://localhost/tpl_test/in the browser's address bar. 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 you are on-for example, my own machine called Patrick, etc.). Here are some of the results I got in my own test: (interpretation of test result data)

Name
Explain
Note

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

Max_seq
Number of maximum processing time
The range is between 1-amount

Max_value
Value for maximum processing time
Peak data for reference

Min_seq
Number of minimum processing time
The range is between 1-amount

Min_value
Value for minimum processing time
Peak data for reference

Average
Average processing time
The most valuable data in the test


Of course, if you think the result of a test is not reliable, you can repeatedly press the browser's refresh button, you can observe the different test

The result (which should theoretically be comparable).

Test results and issuance of "XX Selection Award"
Well, in the speed test of the round two phplib template with an astonishing twice times the speed of victory over the Fasttemplate, while in the first round phplib template has a good API design and ease of use prevailed. The results are obvious-our selection awards have certainly been awarded 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 results, fasttemplate naturally won't be able to get into our project-although it seems that we've spent half a day getting a fruitless result (phplib template continues to work well in the project), but the testing process is valuable, In particular, the use of PHP testing methods, should be in a similar decision in the future to play a certain role in reference.


http://www.bkjia.com/PHPjc/314004.html www.bkjia.com true http://www.bkjia.com/PHPjc/314004.html techarticle the logical and presentation layers of the MVC development model in PHP are available in a variety of template engines, but when the official engine Smarty is born, the choice changes. Its concept and realization are quite ...

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