Template engine smarty

xiaoxiao2021-03-06  122

Template engine smarty

The logical layer and representation of the MVC development model with PHP have a variety of template engines to choose from, but after the official engine Smarty is born, the choice has changed. Its ideas and implementations are quite "avant-garde". This article mainly discusses the different characteristics of Smarty to other template engines, briefly introduces the engine installation and use, and compares the speed and ease of use of Smarty and phpLib Template with a small test case.

First, the MVC requires template MVC to be earliered in a design pattern summarized during the development of SmallTalk languages. The MVC represents "model", "view", "control", and the purpose is to let different development roles in large and medium-sized projects. All the Division of the Division. In the development of a network application, you can use the following figure to represent the relationship between the concepts. The figure shows a simple web application that sees the information on the browser is the content on the database server, but before this, the application server processing is processed. The developer is responsible for establishing data structures, processing data logic, and methods representing data. When the CGI started popular in China, the early Web programmers started self-study materials from HTML, and the HTML of the Print in Perl was not a difficult thing, but with the network's step speed, the page size is also From the original two, thirty k rose ten times. Write a CGI program has an urgent requirement: Separate Perl and HTML source. Thus, social progress is reflected in the division of labor within the development team. Because the art and programmers are not very familiar with each other, they need to communicate with a conventional "language" during cooperation. This language is not our mother tongue or English, the term is called "template", logic and representation relying on it. It is an expression of HTML and scripting language features. In this way, the representation layer can display data processed through the logical layer according to the desired format desired. If you have experience in the development of MFC under the Windows platform, you will be familiar with the package of Document / Document Template / View, which is a typical MVC example. For web applications, individuals think that EJB / Servlets / JSP in J2EE is the most powerful, of course, simple and beautiful Structs. Another very famous implementation is COM / DCOM ASP, this combination is used in our country. With several MVC implementation in a web application, you can get a concept about the template: a set of scripts inserted into HTML or an insertion of the script HTML, which represents the changed data. An example of a template file is given below, which is displayed in the browser after processes "Hello, World!"

$ greetings </ title></p> <p></ hEAD></p> <p><body></p> <p>$ greetings</p> <p><body></p> <p></ html></p> <p>The handling method is omitted here, and it is specifically contrast in later. Second, why do SMARTY? For PHP, there are many template engines to choose from, such as the earliest phpLib Template and the next Xiu Fast Template, have been quite mature and stable after several upgrades. If you are very satisfied with the template engine in the current hands, then, please see it down, I believe you as a free software enthusiast or pursuit of efficiency and elegant developers, how much it will be a bit. In addition to personal preferences, I have been tending to use official standards, such as Apache's XML engine AXIS. The advantage is that you can get as good compatibility (such as early MFC compatibility with Win3X is better than other application frameworks, of course, now all versions are very perfect). I have been using the Integrated Template Extension in the PEAR before SMARTY release. This engine and phpLib Template, Fast Template are almost compatible, from templates syntax to the same display of the template: all read the template into the memory and then call the parse () function, replace the preset tag . Let's take a look at 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 to this URL into a PHP script, then redirect; if not, that is, the Template of the URL has been "compiled" After passing, check that you don't need to recompile, you can immediately immediately, recompile the condition you can set it yourself as a fixed time limit. The default is that the template file is modified. How, does it seem to be a bit more familiar? I think of it - this is not the principle of JSP! Indeed, this "compilation" is used to be incredible on the interpretation script engine such as PHP, but think about it, Java is not explained by JVM? This is called "I don't do it, only I can't think." Since Java is talked, I will publish a point in the future of PHP. PHP official website announced that the PHP version 5.0 will be released at the end of 2003. This version has a lot of new features: such as abnormal processing, namespace, more object-oriented, and more. It can be said that it is more and more 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 that I have chosen the reason for the original choice - the farther is getting farther and farther. However, in the survival cycle of a software, PHP is in the growth period, and developers give it more functions, and the business application is superior than the disadvantage. As a loyal user of PHP, I don't want PHP always accused "Ability"? Why choose Smarty, just because it is like JSP? Of course there is a more reasonable reason. First of all, in addition to the first compilation cost, as long as the template file is not modified, the compiled cache script is ready to use, save a lot of PARSE () time; second Smarty has a rich library like PHP, From the counting of the statistics to automatic indentation, text surrounds, and regular expressions can be used directly; if it is not enough, such as the function of the data result set page display, Smarty has strong extension capability, can be expanded in the form of a plugin. The fact is better than elite.</p> <p>I have designed a test program, which compares smarty and phpLib Template through speed and development difficulties. The reason for choosing phplib template is a phplib template in patrick's article "Select the most appropriate template in the PHP world." For the Fast Template competition, the pHPLIB Template won the whole victory, which makes smarty a good opponent. Before the test, please talk about the problems you need to pay attention to during the installation process. Third, the problem that may be encountered is on the official website of Smarty, there is a detailed user manual, which can choose the version of online HTML and PDF format. This is no longer involved in the content on the manual, just explains the issues that may be encountered in the initial use. The first question is very important: Tip can't find the required file? Not everyone is written in accordance with the Smarty default directory structure. Here is required to be manually specified, assuming that the directory structure is as follows: $ smart-> template_dir = "smarty / templates /";</p> <p>$ smart-> compile_dir = "smarty / templates_c /";</p> <p>$ smart-> config_dir = "smarty / configs /";</p> <p>$ smart-> cache_dir = "smarty / cache /";</p> <p>The first question is solved, the next is the second: How can I just use the beautiful template generated by Dreamweaver? It is not a problem with the template file, but because the default marker separator is {}, the JavaScript is definitely containing this tag. Ok, we can use any character as a separator, plus this two sentences:</p> <p>$ Smart-> Left_Delimiter = "{/";</p> <p>$ smart-> right_delimiter = "/}";</p> <p>This is basically completed, no problem. Fourth, the backing and class is more conceived. The main evaluation factors are of course speed. In order to perform speed testing, an arithmetic average is taken. Repeat the page in the test page to generate N times, then compare the total page generation time. Another important factor is ease of use (as for the scalability, it has been a result), so the template used is not too small. I use the page of my personal page, a HTML file generated with Firework Dreamweaver, about 7k. The variable settings also take the most common block, called Block in the phplib template, and smarty said section. Don't underestimate this name, ease of use of standards, two pieces: the syntax of the template file and the script file is simple and easy. Let's go deep into the test. First look at the grammar of two template files: the left side of the blue strip is a template for phplib Template, and the right side belongs to Smarty. Personal preferences are different, so they don't comment here. Focus on the processing statement in the script, first look at the phpLib Template:</p> <p>$ TPL-> set_file ('phplib', 'bigfile.htm');</p> <p>$ TPL-> Set_block ('phplib', 'row', 'rows ");</p> <p>For ($ j = 0; $ j <10; $ j ) {</p> <p>$ TPL-> Set_var ('Tag', "$ J");</p> <p>$ TPL-> PARSE ('Rows', 'Row', True);</p> <p>$ TPL-> PARSE ('out', 'phpo ");</p> <p>$ TPL-> P ('Out');</p> <p>Here is Smarty:</p> <p>$ Smart-> Assign ('Row', $ ROW);</p> <p>$ Smart-> Display ('Bigfile.htm');</p> <p>Smarty only used Tags and ROW variables, and phplib Template has more template files, and there is an inexplicable OUT. Said that this OUT I didn't know why I want to exist when I first studied, I still don't have awkward. Why is smarty to deal with statements? The answer is that the work is completed by the engine. If you like to drill the source program, you can find a function called _compile_tag () in smarty_compiler.class.php, which is responsible for converting the Section this tag into a PHP statement. This is not an ordinary label, which has parameters and data, saving the workload of scripting programming, and the working volume on the template label is not large, and it can be determined that Smarty is high in SMARTY. The following is the speed of our most concerned. After all, for a skilled web developer, it is a matter of time problems, let alone template engine such learning curve gentle technology. The speed is the life of the web application, especially the template engine is used in a large site of concurrent visit, this is more important. Before the test start, I think PhPlib Template will win on this link, because it has experienced many upgrades, there is basically no bug, and smarty's engine is too big, unlike its opponent only two files. Sure enough, the test results are shown below. PhPlib Template has 25% of the speed advantage: but will not always, I pressed it once, this time I got a different result: phplib basically did not change, but smarty increased by 25%. speed. Continue to refresh, the result is similar to the second result: Smarty is nearly 10% faster than phplib Template. I think this is the principle of compilation and interpretation. The Smarty engine itself is very large, plus the template into a PHP file, which is certainly less than a small PHPLIB TEMPLATE. But this is just the first time. When receiving the request, Smarty found that the template has been compiled, so the time consuming step is skipped, and the opponent will perform the search and replacement work in accordance with the class. This is a very classic "spatial change time" example in the compilation principle. 5. Conclusion The conclusion is if you already fall in love with smarty, what are you waiting for? Of course, it is not to say that it is all, just like I use MVC mode to write my personal website, but there is no reduction in workload, but it is always necessary to be a coupling between different levels. What is smarty not suitable? Classic examples in a manual: Weather Forecast website. I also thought of: the stock market market. Using Smarty on this website, it is more efficient due to frequent reconstruction, or PHPLIB Template is more suitable. This article is not to compare both engines, but to illustrate the advantage of Smarty. It is the most meaningful place to use it is a part of the PHP system. As an independent force, in addition to the two major systems of .NET and Java One, there are other choices in large and medium-sized web development. This is a GNU project, and its significance is tantamount to Liu Deng, thousands of miles, jump into the big hill.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-126633.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="126633" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'Z3qUIVQyy_2BmVFwp2j6d3qZnxADNitEbueYPejfGEii7AurWKKCWyus9RAyDirZ1x5m8AItsfdV143mVwJQbchw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>