There are a variety of template engines to choose from for the logic layer and presentation layer of the MVC development model using PHP, 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 PHPLIB templates.
1. MVC needs templates
MVC was a design pattern first summarized during the development process of SmallTalk language. MVC represents "model", "view" and "control" respectively. The purpose is Let different development roles perform their own 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 picture 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, but with the advancement of the Internet, The speed has increased step by step, and the page size has also increased tenfold from the original 20 to 30 K. Writing CGI programs creates an urgent requirement: separating PERL and HTML source code. Therefore, 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 representation 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/Document Template/View. This is a very typical MVC example. For Web applications, I personally think 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 inserted, represented by this inserted content Changing data. The following is an example of a template file. This template is processed to display "Hello, world!" in the browser
Introduction:
-------------- -------------------------------------------------- ----------------
$greetings $greetings
------ -------------------------------------------------- -----------------------
The processing method will be omitted here for the time being, 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 PHPLIB template and the rising star Fast template. 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.
Except for 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 PHPLIB template and Fast template. 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" After passing the check, you can redirect immediately after checking that recompilation is not required. The recompile condition can be set to a fixed time limit by yourself. The default is that the template file is modified.
How about it? Does it look familiar? Come to think of it──this is the principle of JSP! Indeed, it is incredible to use this kind of "compilation" on an interpreted script engine like PHP, but if you think about it carefully, isn't JAVA also interpreted and executed by the JVM? This is called "nothing is impossible, only imaginable".
Since we 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 farther and farther 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. Developers giving it more functions in the hope that it can be competent for commercial applications have more advantages than disadvantages. 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 is very similar to 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 PHPLIB template based on the two factors of speed and development difficulty. The reason why I chose PHPLIB template is that there is a PHPLIB template in Patrick's article "Choosing the Most Suitable Template in the PHP World" In the competition for Fast template, PHPLIB template 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. Possible problems
On SMARTY’s official website, there is a detailed user manual, and you can choose online versions in HTML and PDF formats. Here we will no longer cover the existing content in the manual, but just explain the problems you may encounter during first use.
The first question is very critical: it says the required file cannot be found? Not everyone writes applications according to the SMARTY default directory structure. This needs to be specified manually. Assuming that 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 is solved, and the next one is Second: Why can’t I use the beautiful template I just generated with Dreamweaver? It's not that there's anything wrong with the template file, but because SMARTY's default tag delimiter is {}. Unfortunately, Javascript definitely contains this tag. Fortunately, we can use any character as a separator, plus these two sentences:
Introduction:
----------------------- -------------------------------------------------- -------
$smart->left_delimiter = "{/";
$smart->right_delimiter = "/}";
------------------------------------------------ --------------------------------
The installation is now basically complete. , no problem.
4. Contrast and Analogy
Consider the design of the test first. 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 setting also adopts the most commonly used block, which is called block in PHPLIB template and section in SMARTY. Don’t underestimate the difference in names. The usability standard is divided into two parts: whether the syntax of template files and script files is concise and easy to use.
Let’s dive into the test. 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:
Introduction:
-------------------------- -------------------------------------------------- ---
$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:
Introduction:
---------------------------------- -----------------------------------------------
$smart->assign('row',$row);
$smart->display('bigfile.htm');
---------- -------------------------------------------------- --------------------
SMARTY only uses two variables, tags and row, while PHPLIB template has more templates There is also an inexplicable out in the file handler. To be honest, I didn't know why this out existed when I first learned it. Now it seems awkward. 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 any difficult tool, not to mention the template engine, a technology with a gentle learning curve. And 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, this is even more important. Before the test started, I felt that 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 large, 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 got something different this time. The 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 the reason why the compiled type is faster than the interpreted type. 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 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.
References
SMARTY official website: 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
Yu Boxiang, whose pen name is Yu Lai, comes from the School of Information, University of International Business and Economics. GNU enthusiasts like to practice various programming languages and study various system frameworks.
Number of posts: 1275 Reply: Many PHP scripts will use Smarty as the core engine, and what exactly is Smarty? 2003-08-10 14:07
Choose in the PHP world The most suitable template - Compare PHPLIB Template and FastTemplate
Template application in PHP projects is a good way to deal with the presentation layer recommended in medium-sized or even large-scale projects. However, when it comes to the implementation of templates, it is necessary to compare which existing template technologies should be used.
The two most popular template processing in the PHP world are PHPLIB Template and FastTemplate. We evaluated the ease of use and speed of the technology - want to know the results?
The origin of the matter: Have you ever used FastTemplate?
As for the template application in PHP projects, my colleagues and I have actually been exposed to it in many projects - regarding its benefits, I think both in the actual development stage and from the perspective of design patterns. Many "predecessors and sages" have discussed this. As far as project implementation is concerned, in some medium-sized or even large-scale projects, effectively separating HTML (and other text-based presentation layers) and PHP code can not only improve the performance of interface designers and application writers respectively during the development phase Work efficiency will also bring great convenience to the testing and maintenance of the project.
However--the purpose of this article is not to discuss the advantages and disadvantages of templates, nor is it to serve as an instructive tutorial on how to use templates in PHP projects, but to compare the two most popular ones in the PHP world from an application perspective. Template processing methods (actually just two template classes): PHPLIB Template and FastTemplate.
In fact, I have been using PHPLIB Template "quietly" - it is very stable and seems to be fast, so I don't want to worry about looking for a potentially better alternative - although I I also know that there is such a thing as FastTemplate on this earth (and it is also famous in the world of Perl). Until one day, a colleague asked me: "I wonder what FastTemplate is like? Why don't we try FastTemplate?"
"Okay, let's try it!" But as a safe method, Before any new pattern or method is introduced into the project, it is best to understand it more comprehensively and find one or several reasons that are sufficient to convince yourself and your colleagues to adopt it - FastTemplate is no exception.
The protagonist appears: Understanding PHPLIB Template and FastTemplate
As mentioned before, I have been using PHPLIB for some time - I think you in front of the screen may be like me and also have a deep understanding of this excellent tool class. Ku must be very impressed! Similarly, when I started looking for template solutions, I naturally searched in the toolbox closest to me, so I found the Template class in PHPLIB. After a quick glance at the API it provided (of course, thanks to PHPLIB's detailed documentation), I started using it - until now.
FastTemplate seems to be more famous. This is naturally the case in the Perl world where it made its fortune, and it seems to be the same in the PHP world. From this point alone, it is enough to make people believe in its capabilities.
Regarding how to use the two, I originally wanted to say a few more words here; but after all, I feel that writing two tutorials specifically will not be as popular as the existing tutorials - in the reference of this article There are famous tutorials on PHPLIB Template and FastTemplate in the information. If you think you are not familiar with these two templates or one of them, I suggest you read those two articles first. You should get a lot of useful information. Template application knowledge.
(After some mouse clicking and eye rolling and even writing the test code yourself,) Now that you have some understanding of both templates, you may have discovered a lot of similarities between them. Below I These places will be summarized.
Variable settings
Obviously, the form of {FOO} or {BAR} is the specified form in both templates; that is to say, in the two template processing methods, the template file itself The appearance should be consistent (for example, both HTML files contain variables marked with {} that will be replaced).
Initialization of the template class (class builder)
You need to specify the directory location where the template file exists when building the template class.
Variable substitution
The most commonly used method in template processing is variable substitution. Except for the different method names (PHPLIB Template uses set_var(), and FastTemplate uses assign()), the usage is almost the same - -You can use (key, value), or you can directly pass an array (array(key=>value)).
Template file processing
adopts the method of specifying a handler for each template file. At the same time, the handle can also be used as the value of a variable to replace a variable in another template file.
Parsing and output processes
Both require calling the parse() method (the method names are actually the same) to parse the template file that needs to be output and assign it to a handle, and then call the respective output methods (in PHPLIB Template It is p(), FastPrint() in FastTemplate) outputs the content of the handle and ends the processing.
Repeat the parsing process
For example, when several records are retrieved from the database and need to be displayed, but the template file only has a replaceable line of variables, this function is very much needed. Both have such functions, but they are slightly different in use (PHPLIB Template uses parse(handler, value, true), while FastTemplate uses parse(handler, .value) with an extra dot in front of the value). It should be said that PHPLIB Template's method is relatively elegantly constructed.
The process of block parsing (or can be called dynamic parsing)
Imagine that you need to retrieve qualified data from the database and display it on the web page - but because the conditions will be different, you cannot be clear You know how many pieces of data there will be - if you want to use a template at this time, then block is the best choice. It is a part defined with specific symbols in the template. This part can be parsed repeatedly and added to the output web page (rather than the previous parsing being overwritten by the next one). The block may look like the one shown below (the left is the block setting used by PHPLIB Template, and the right is used by FastTemplate):
Well, if you are confused about the above The text introduction is still a bit confusing, so let’s take a look at two detailed template processing routines! (If you are interested in exploring the following test code, you will find that the following two examples actually come from there)
How about, does it feel almost the same? The following is an example of block parsing, you will also find the same effect:
Our test goals and results
After finishing the understanding of PHPLIB Template and FastTemplate, you should be able to enter the main topic of this article --Of course, in the application environment, you should choose components that are easy to use and have ideal speed to build the system, so it is very necessary to evaluate these two similar technologies. The evaluation should be composed of two parts: the difficulty of using the technology and the speed - the former is the review part, and the latter is the test part. For the former, we mainly comment on the APIs provided by the two classes; for the latter, we will let the test data speak for itself. Of course, we will inevitably need to write some simple test code.
Round 1: Ease of use of technology
This round mainly explores the use of APIs provided by PHPLIB Template and FastTemplate. It should be said that the API provided by the former is more in line with some common coding practices of PHP (especially when other classes of PHPLIB are used in your project, such standardization will have a good impact on the entire project); while some methods of the latter The name always feels a bit awkward (I hope you don't think this is just my narrow view, such as FastPrint(), etc.), and the parameters of the method are not very "authentic", which you can also see from the code just now.
Another point that needs to be pointed out is that FastTemplate did not support the parsing of template blocks until the latest version. In other words, if you used the previous version, when processing things such as the output of records in the database, you had to store this piece of content separately somewhere, and then attach this file during template analysis and processing - really a problem This is a frustrating thing, especially for web designers.
Of course there is one more thing that needs to be investigated - that is the support for the PHP version. PHPLIB was produced in the era of PHP3, which is similar to FastTemplate; but according to our application, PHPLIB runs quite well in the current PHP4 environment, and FastTemplate's web page displays some information indicating that it may still have some bugs for PHP4. .
Okay, after talking so much (maybe you will think it is all bad words about FastTemplate), the winner of this round is obvious: PHPLIB Template, especially when you are using other classes of PHPLIB at the same time, like this The technical ease of use is more obvious (you will not be unfamiliar with these APIs from the same development team).
Round 2: Processing speed
Perhaps this is the part that many people are most concerned about - in this round, we will use two methods of template processing: one is conventional analysis and replacement, The other is to parse and replace blocks - at the same time, these two methods are also the most commonly used in actual systems: the former is general page processing, and the latter is output processing of database content. At the same time, since the template file formats used by the two template classes are basically the same, we can provide almost identical template files for the two templates to parse, which increases the credibility of the test.
Before conducting such a speed test, a test plan will be drawn up. To put it simply, two PHP test pages are written for the two processing methods. At the same time, there is a page that controls the test and calls these two pages multiple times. Record the time for collecting test data. (If you are interested, you can also refer to the following detailed test plan, which may help you understand this test in depth)
Summary--After the entire test system is completed, we should be able to get the /test directory The file list is as follows:
(a somewhat complicated test plan)
First, determine the hardware and software environment for the test - the hardware must be your own machine, Intel Celeron 733MHz, 256M RAM , 40G HDD; the OS in the software platform is Win2K Pro, the web server is Apache+PHP, and runs in a module mode.
The second step is to plan the system for this test - of course, first open a new directory tpl_test in the document root directory of the web server to place all the files for this test; then create an include directory under /tpl_test to Store two template class files (the core of our testing, with .inc.php as the file extension) and a test class file (including functions such as timing and logging, reading logs and analysis, with .inc.php as the file) extension) and a data file (to prepare for the block parsing test, mainly contains a two-dimensional array, also with .inc.php as the file extension), create an ihtml directory to store the template files used (which need to be parsed Template file, with .ihtml as the file extension), create a logs directory to store the logs generated by the test (later it will be discovered that the test data is actually obtained from the analysis of these logs, with .log as the file extension). Of course, the processing PHP files for the two templates are placed in the /test directory. The most critical point of this test is that you need to create a PHP file and call the above-mentioned file responsible for template processing several times: for example, a file fast_test.php uses FastTemplate to parse the template, and phplib_test.php uses PHPLIB Template is parsed, then the resulting PHP file is responsible for requesting the above two pages multiple times through HTTP to obtain test data.
Select the template to be parsed and write the PHP program - because the two template processing methods have almost the same format requirements for the template file itself (for example, the variables to be replaced are in the form of {VAR}, etc.), so you can Try to ensure that the templates selected by the two in the same test are as the same as possible to achieve the greatest fairness of the test; at the same time, as mentioned above, to simulate two template applications commonly used in real systems: general page processing and output processing of database content. , the template files used for testing are also divided into two types: one is an ordinary template file with some variables to be replaced, and the other is a template file with blocks that need to be repeatedly replaced according to the content that should be output. Similarly, for these two template files, two different PHP files need to be written for parsing.
Test method--Make a request to /test/result.php in the browser. You need to bring the parameter type=[simple|complex]. In the returned results, you can see that the two templates are simple or Test results in complex mode.
Level 1
Level 2
Level 3
Remark
/test
The root directory of the test system
result.php
A PHP file that performs testing and generates results. When testing, you only need to request the page in the browser to obtain it. Test information
simple__test_phplib.php
Use PHPLIB Template to analyze the PHP file of the general template
simple__test_fast.php
Use FastTemplate analyzes the PHP file for general templates
complex__test_phplib.php
Uses PHPLIB Template to analyze the PHP file with block templates
complex__test_fast .php
Use FastTemplate to analyze PHP files with block templates
/include
Contains PHP class file .inc.php
phplibTemplate.inc.php
PHPLIB Template class file
FastTemplate.inc. php
FastTemplate class file
TplTest.inc.php
The test class that needs to be used in the test, including methods such as timing, reading/analyzing logs, etc.
data.inc.php
The data file used when testing templates with blocks.
/ihtml
Contains template file.ihtml
simple_phplib .ihtml
General template files processed by PHPLIB Template
simple_fast.ihtml
General template files processed by FastTemplate
complex_phplib.ihtml
A template file with blocks processed using PHPLIB Template
complex_fast.ihtml
A template file with blocks processed using FastTemplate
/logs
Contains the log file.log
simple_phplib.log
Use PHPLIB Template to process logs generated by general templates
simple_fast.log
Use FastTemplate to process logs generated by general templates
complex_phplib.log
Use PHPLIB Template to process logs generated with block templates
complex_fast.log
Use FastTemplate to process logs generated with block templates
Passed After designing and writing the test system, and asking for two templates from colleagues in charge of web design, we can access the system - the hard work in the early stage means that now we only need to type in the address bar of the browser to view the results. Enter http://localhost/tpl_test/ result.php?type=[simple|complex] (If you are conducting this test on another non-local server, the domain name should be the domain name of the server - such as my own machine called patrick etc.).The following are the results I obtained in a certain test: (Explanation of test result data)
Name
Explanation
Remarks
amount
Total number of tests (continuous requests Total number of pages)
This parameter can be modified in the result.php file
max_seq
The sequence number of the maximum processing time
The range is between 1-amount
max_value
The value of the maximum processing time
Peak data for reference
min_seq
The sequence number of the minimum processing time
The range is between 1-amount
min_value
Min. Value of processing time
Peak data for reference
average
Average processing time
The most valuable data in the test
Of course, if you feel that a test The results are not reliable. You can repeatedly press the refresh button of the browser to observe the
results of different tests (theoretically they should be almost the same).
Test results and the award of "XX Choice Award"
Well, in the second round of the speed test, PHPLIB Template defeated FastTemplate at an astonishing 2 times speed; at the same time, in the first round, PHPLIB Template has the upper hand with good API design and ease of use. The results are obvious - our choice award is of course awarded to PHPLIB Template. At the same time, this test also gave us a deeper understanding of the design of the PHPLIB class library.
Subjective Evaluation
Now that we have the results, FastTemplate naturally cannot enter our project - although it seems from the results that we spent half a day to get an unchanged result ( PHPLIB Template continues to be used well in the project), but the testing process is very valuable, especially the method of testing using PHP, which should play a certain reference role in similar decisions in the future.
http://www.bkjia.com/PHPjc/314004.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314004.htmlTechArticleUsing 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 the official engine After the birth of SMARTY, the choices have changed. Its concept and implementation are quite...