(PHP) template engine Smarty Introduction

Source: Internet
Author: User
Keywords (PHP) template engine Smarty Introduction
Tags php website

Template

Engine Smarty Introduction--php

From

: Cjjer made a partial change

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 phplibtemplate with a small test case.

First, MVC needs templates

MVC is the first design pattern summed up in the development of Smalltalk language, and MVC represents models, views, and controls, which are designed to allow different development roles to 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 communicate in an agreed language.

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/documenttemplate/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!

$greetings

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

Second, why Choose Smarty?

For PHP, there are many template engines to choose from, such as the first phplibtemplate and the rising star Fasttemplate, 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 Phplibtemplate, fasttemplate, from the syntax of the template to the processing of the template expatiating: it reads the template into memory and then calls the parse () function to replace the preset tag with the 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, compile the template file required by the URL into a php script, and then redirect, if not, that is, the URL template has been compiled, check do not need to recompile can be redirect immediately, 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's true that this kind of compilation is unthinkable on an explanatory scripting engine like PHP, but think about it that Java is not being interpreted by the JVM. This is called not to 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 always be accused of the ability to be inadequate?

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 compared the two factors of speed and development difficulty to Smarty and Phplibtemplate, and chose Phplibtemplate because there was a phplib in Patrick's article "Choosing the most appropriate template in the PHP world." Template to the Fasttemplate race, the result Phplibtemplate victory, which 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:

$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:

$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:

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

Here are the Smarty:

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

Author: Yuboxiang

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