Home Backend Development PHP Tutorial (Picture) Detailed introduction to PHP template engine Smarty

(Picture) Detailed introduction to PHP template engine Smarty

Jul 25, 2016 am 09:11 AM

This is an old article, but the knowledge it introduces about the smarty template engine is still of great benefit. I share it here for your reference. 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 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 roles in large and medium-sized projects. job. In the development of network applications, the following diagram can be used to represent the relationship between concepts. (Picture) Detailed introduction to PHP template engine Smarty 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 It has also increased tenfold from the original 20 to 30 K. Writing CGI programs creates an urgent requirement: separating 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 representation rely 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 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. This template is processed to display "Hello, world!" in the browser.

  1. $greetings
  2. $greetings
  3. < ;/html> ;
Copy code

The processing methods are omitted for the time being, and will be discussed specifically for comparison later.

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. 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 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 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 is a lot 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 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.



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles