the template
engine Smarty - PHP
from
: cjjer Made some changes
to use PHP to implement the logic layer and presentation layer of the MVC development model. There are a variety of template engines to choose from, but after the birth of the official engine SMARTY, the choice has changed. Its concept and implementation are quite avant-garde. This article mainly discusses the different characteristics of SMARTY compared to other template engines, briefly introduces the installation and use of the engine, and uses a small test case to compare the speed and ease of use of SMARTY and PHPLIBtemplate.
1. MVC requires templates.
MVC was first summarized as a design pattern during the development process of SmallTalk language. MVC represents model, view and control respectively. The purpose is to allow different development roles to perform their respective duties in large and medium-sized projects. In the development of network applications, the following diagram can be used to represent the relationship between concepts.
This figure shows a simple WEB application. The information the user sees on the browser is the content on the database server, but it has been processed by the application server before. Developers are responsible for establishing data structures, logic for processing data, and methods for representing data.
When CGI became popular in China in 1996, early WEB programmers were all self-taught from HTML. It was not difficult to print lines of HTML in PERL. However, as the network speed increased step by step, the page size also increased. From the original 20 to 30 K, it has skyrocketed tenfold. Writing CGI programs creates an urgent requirement: to separate PERL and HTML source code. Thus, social progress is reflected in the division of labor within the development team. Since artists and programmers are not very familiar with each other's work, they need to use an agreed language to communicate during cooperation.
This language is not our native language or English. The term is called template, and the logic and presentation depend on it. It is an expression method that combines the characteristics of HTML and scripting languages. In this way, the presentation layer can display the data processed by the logic layer in the format desired by the user. If you have MFC development experience under the Windows platform, you will definitely be familiar with the encapsulation of Document/DocumentTemplate/View. This is a very typical MVC example. For Web applications, I personally think that EJB/servlets/JSP in J2EE are the most powerful, and of course there are simple and beautiful Structs. Another well-known implementation is COM/DCOM+ASP. This combination is used by the most people in our country.
By comparing several MVC implementations in WEB applications, we can get a concept about templates: a set of scripts inserted into HTML, or script HTML, through which inserted content represents changing data. The following is an example of a template file. After processing, this template displays Hello, world! in the browser.
The processing method of$greetings
is omitted for now, and will be discussed later for comparison.
2. Why choose SMARTY?
For PHP, there are many template engines to choose from, such as the earliest PHPLIBtemplate and the rising star Fasttemplate. After several upgrades, they have become quite mature and stable. If you are very satisfied with the template engine you currently have, then...please read on. I believe that as a free software enthusiast or a developer pursuing efficiency and elegance, the following SMARTY introduction will be somewhat interesting.
In addition to the influence of personal preference, I have always tended to use official standard implementations, such as APACHE's XML engine Axis. The advantage is that you can get the best possible compatibility (for example, the compatibility of early MFC with Win3x was better than other application frameworks, and of course now all versions are very complete). Before SMARTY was released, I had been using the Integrated Template eXtension in PEAR. This engine is almost compatible with PHPLIBtemplate and Fasttemplate. From the syntax of the template to the processing of the template, the template is read into the memory and then the parse() function is called to replace the preset tags with data.
Let’s see how SMARTY does it. After receiving the request, first determine whether the url is requested for the first time. If so, compile the template file required for the url into a php script, and then redirect; if not, it means that the template of the url has been compiled. Check You can redirect immediately without recompiling. The recompile conditions can be set to a fixed time limit. The default is that the template file is modified.
How about it? Does it look familiar? Come to think of it──Isn’t this the principle of JSP! Indeed, this kind of compilation seems incredible when used on an interpreted scripting engine like PHP, but if you think about it carefully, isn't JAVA also interpreted and executed by the JVM? This means that nothing is impossible, only unimaginable.
Now that we have talked about JAVA, let me express my views on the future of PHP. The official PHP website announced that version PHP 5.0 will be released at the end of 2003. This version has many new features: such as exception handling, namespaces, more object-oriented, etc. It can be said that it is getting closer to JAVA, and SMARTY is also one of the new features, making PHP more suitable for the development of large and medium-sized projects. But it seems to be getting further and further away from the reason why I chose it in the first place--flexibility and ease of use. But from the perspective of the life cycle of a software, PHP is in the growth stage, and the advantages outweigh the disadvantages for developers to give it more functions in the hope that it can be competent for commercial applications. As a loyal user of PHP, you certainly don’t want PHP to always be accused of insufficient capabilities, right?
WHY CHOOSE SMARTY, JUST BECAUSE IT'S LIKE JSP? There are certainly better reasons. First of all, in addition to the relatively high cost of the first compilation, as long as the template file is not modified, the compiled cache script is available at any time, saving a lot of parse() time; secondly, SMARTY has a rich function library like PHP. From counting words to automatic indentation, text wrapping and regular expressions, you can use it directly; if you feel it is not enough, for example, you need the function of paging display of the data result set, SMARTY also has strong expansion capabilities, which can be expanded through plug-ins.
Facts speak louder than words. I designed a test program and compared SMARTY and PHPLIBtemplate based on the two factors of speed and development difficulty. The reason why I chose PHPLIBtemplate is that in Patrick's article "Choosing the Most Suitable Template in the PHP World", there is a comparison between PHPLIB template and Fasttemplate. Competition, PHPLIBtemplate won a great victory, which gave SMARTY a good opponent. Before testing, let’s talk about the issues that need to be paid attention to during the installation process.
3. Problems you may encounter
On SMARTY’s official website, there is a detailed user manual, and you can choose online versions in HTML and PDF formats. We will not cover the existing content in the manual here, but will just explain the problems you may encounter during first use.
The first question is very fatal: it says that the required file cannot be found? Not everyone writes applications according to SMARTY's default directory structure. This needs to be specified manually. Assuming the directory structure is as follows:
You need to specify the directory structure in 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, and then comes the second one: Why can't the beautiful template I just generated with Dreamweaver be used? It's not that there's anything wrong with the template file, it's because SMARTY's default tag delimiter 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 = "/}";
Now the installation is basically completed, no problem.
4. Contrast and Analogy
First, think about the design of the test. The main judging factor is of course speed. For speed testing, an arithmetic mean was used. Repeat the page generation N times on the test page, and then compare the total page generation time. Another important factor is ease of use (as for scalability, there is no need to compare the results), 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. The variable settings also adopt the most commonly used blocks, which are called blocks in the PHPLIB template and sections in SMARTY. Don’t underestimate the difference in names. The usability criteria are divided into two parts: whether the syntax of template files and script files is concise and easy to use.
Let’s dive into the testing. Let’s first look at the syntax of the two template files: the left side of the blue bar is the PHPLIB template, and the right side belongs to SMARTY. Personal preferences vary, so I won’t comment here. Focus on comparing the processing statements in the script, 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');
The following is SMARTY:
$smart->assign('row',$row);
$smart->display('bigfile.htm');
SMARTY only uses two variables, tags and row, while PHPLIB template has an additional template file handler and an inexplicable out. To be honest, I didn't know why this out existed when I first learned it. It still seems awkward now. Why does SMARTY have so few 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 that there is a function called _compile_tag() in 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, which saves the workload of script programming. The workload on the template label is not much different. It can be judged that SMARTY is higher in ease of use.
Now it’s our turn to focus on speed. After all, for a skilled web developer, it is only a matter of time to master the most difficult tool, not to mention the template engine, a technology with a gentle learning curve. Speed is the life of a web application, especially when the template engine is used on a site with a large number of concurrent visits, which is even more important. Before the test started, I thought PHPLIB template would win in this aspect because it has been upgraded many times and has basically no bugs. Moreover, SMARTY's engine is too big, unlike its opponent which only has two files.
Sure enough, the test results are as shown below, PHPLIB template has a 25% speed advantage:
But it won’t always be like this. I pressed refresh again, and this time I got a different result:
PHPLIB is basically unchanged, but SMARTY has increased the speed by 25%. Continue to refresh, and you will get results similar to the second time: SMARTY is nearly 10% faster than PHPLIB template. I think this is why the compiled version is faster than the interpreted version. The SMARTY engine itself is very large, and the template needs to be compiled into a php file, so the speed is certainly not as fast as the compact PHPLIB template. But this is only the case for the first time. When receiving the request for the second time, SMARTY found that the template had already been compiled, so the most time-consuming step was skipped, and the opponent had to perform search and replacement step by step. This is a classic example of "exchanging space for time" mentioned in the principles of compilation.
5. Conclusion
The conclusion is that if you have fallen in love with SMARTY, then what are you waiting for? Of course, this does not mean that it is omnipotent. Just like when I use the MVC model to write my personal website, not only does it not reduce the workload, but I always have to worry about the coupling between different levels.
What is SMARTY not suitable for? Take a classic example from the manual: the weather forecast website. One more thing comes to mind: the stock market. Using SMARTY on this kind of website will be inefficient due to frequent recompilation, so PHPLIB template is more suitable.
This article is not to compare the two engines, but to illustrate the advantages of SMARTY. The most meaningful thing about using it is that it is part of the new PHP system. As an independent force, in addition to the two major systems of .NET and JAVA ONE, there are other options for large and medium-sized web development. For the GNU project, its significance is no different than Liu and Deng's army leaping thousands of miles into the Dabie Mountains.
Author: Yu Boxiang