search
HomeBackend DevelopmentPHP TutorialInstructions for using Smarty based on PHP Web development MVC framework_PHP tutorial

Instructions for using Smarty based on PHP Web development MVC framework_PHP tutorial

Jul 21, 2016 pm 03:11 PM
mvcphpsmartywebonedownloadInstructions for usebased onInstalldevelopframeDemoofConcise tutorial

1. Smarty concise tutorial
1. Installation demonstration
Download the latest version of Smarty-3.1.12, and then unzip the downloaded file. Next, we will demonstrate the demo example that comes with Smarty.
(1) Download address: http://www.smarty.net/download
(2) Create a new directory in the root directory of your WEB server. Here I create the yqting/ directory under /var/www , and then copy the demo/ and libs/ directories in the decompressed directory to the /var/www/yqting/ directory.
(3) Pay special attention to the cache/ and template_c/ directories under the demo/ directory. Be sure to set them with read and write permissions.
 chmod 777 cache/
 chmod 777 template_c/
(4) Start apache. Enter http://localhost/yqting/demo/index.php in the browser, and a simple Smarty demo is implemented.
2. Smarty directory structure
(1) Start the analysis with the /var/www/yqting directory:
yqting/
 ├── demo
 │ ├── cache Cache file storage directory
  │ ├── configs Configuration file directory
  │ ├── index.php

  │ └── templates_c Compiled file storage directory
  └── libs
  ├── debug.tpl debug template
  ├── plugins Some useful plug-ins for customization
├ ─ ─ SmartyBC.class.php Support Smarty 2 compatible
  ├── Smarty.class.php Smarty class definition file
   └── sysplugins Smarty core function plug-in, no need to modify
(2) Add your own definition Plug-in
In the above directory structure, the core part is actually the libs/ directory, and this part is not allowed to be modified.
To add your own plug-ins, one way is to place your own defined plug-ins in the libs/plugins/ directory, and the other way is to create your own plugins/ directory, and also create cache/ and configs/ , templates/ and templates_c/ directories, and ensure the read and write permissions of the cache/ and templates_c/ directories.
It is not difficult to find that in fact, in the above example, the demo/ directory is a complete directory containing self-defined plug-ins. We can refer to the demo/ directory to implement our own program.

3. Implement a simple example
(1) Create the directory weibo/ under /var/www/yqting/, and then create cache/, configs/, templates under the weibo/ directory / and templates_c/ directories, modify the permissions of cache/ and templates_c/ directories to read and write.
(2) Create a new template file: index.tpl, and place this file in the /var/www/yqting/weibo/templates directory. The code is as follows:
 
 


 
 Smarty
 

username:{$Name}

Each .tpl file for display will correspond to a .php file that handles business logic. This .php file is introduced below.
(3) Create a new index.php and place this file under /var/www/yqting/weibo/. The code is as follows:
 assign("Name",$username); $smarty->display('index.tpl') ; ?> The path used by require must be correct. You can refer to the directory structure above to take a look!
(4) In Smarty3, template_dir, compile_dir, config_dir and cache_dir have been specified in the constructor of the Smarty class and do not need to be specified again.   
(5) Enter http://localhost/yqting/weibo/index.php in the browser, and you can see the output information username:Smarty.

2. Explain the smarty program
We can see that the program part of smarty is actually a set of codes that conform to the PHP language specification. Let’s explain it in turn:
(1) /**/Statement:
The included part is the program header comment. The main content should be a brief introduction to the function of the program, copyright, author and writing time. This is not necessary in smarty, but from the perspective of the style of the program, this is a good style. ​
(2) include_once statement:
It will include the smarty file installed on the website into the current file. Note that the included path must be written correctly.   
(3)$smarty = new Smarty():
  This sentence creates a new Smarty object $smarty, which is a simple instantiation of an object.
(4) $smarty->templates="":
This sentence specifies the path when the $smarty object uses the tpl template. It is a directory. Without this sentence, Smarty's default template path is the current The templates directory of the directory. When actually writing a program, we need to specify this sentence. This is also a good programming style.   
(5)$smarty->templates_c="":
 This sentence specifies the directory where the $smarty object is compiled. In the template design chapter, we already know that Smarty is a compiled template language, and this directory is the directory where it compiles templates. Please note that if the site is located on a Linux server, please ensure that the directory defined in teamplates_c is writable and readable. Permissions, by default its compilation directory is templates_c in the current directory, for the same reason we write it out explicitly. ​
(6)Delimiter $smarty->left_delimiter and $smarty->right_delimiter:
Specifies the left and right delimiters when looking for template variables. By default, it is "{" and "}", but in practice, because we need to use <script> in the template, the function definition in Script will inevitably use {}. Although it has its own solution, it is customary We redefine it as "{#" and "#}" or "<!--{" and "}-->" or other identifiers. Note that if the left and right separators are defined here, Correspondingly, in the template file, each variable must use the same symbol as the definition. For example, it is designated as "<{" and "}>" here. In the html template, {$name} must be changed to &lt accordingly. ;{$name}>, so that the program can find the template variable correctly. ​<BR>(7)$smarty->cache="./cache": <BR> Tell Smarty the location of the cache of the output template file. In the previous article, we knew that the biggest advantage of Smarty is that it can be cached. Here is the directory where the cache is set. By default, it is the cache directory in the current directory, which is equivalent to the templates_c directory. In the Linux system, we need to ensure that it is readable and writable.   <BR>(8)$smarty->cache_lifetime = 60 * 60 * 24:  <BR> The cache validity time will be calculated in seconds. The cache will be rebuilt when Smarty's caching variable is set to true when the first cache time expires. When its value is -1, it means that the established cache never expires; when it is 0, it means that the cache is always re-established every time the program is executed. The above setting means setting cache_lifetime to one day.   <BR>(9)$smarty->caching = 1:   <BR>  This attribute tells Smarty whether to cache and how to cache. <BR> It can take 3 values, 0: Smarty default value, which means that the template will not be cached; 1: means that Smarty will use the currently defined cache_lifetime to decide whether to end the cache; 2: means that Smarty will use it when the cache is created. cache_lifetime value. It is customary to use true and false to indicate whether to cache. <BR> (10) $smarty->assign("name", $username): <BR> The prototype of this number is assign(string varname, mixed var), varname is the template variable used in the template, var indicates the The variable name that replaces the template variable; its second prototype is assign(mixed var). We will explain the use of this member function in detail in the following examples. assign is one of the core functions of Smarty. All template variables Use it for all substitutions.   <BR>(11)$smarty->display("index.tpl"):   <BR> The prototype of this function is display(string varname), which is used to display a template. To put it simply, it will display the analyzed and processed templates. There is no need to add a path to the template file here, just use a file name. We have already defined its path in $smarty->templates(string path) . <BR>After the program is executed, we can open the templates_c and cache directories in the current directory, and you will find that there are some %% directories below. These directories are Smarty’s compilation and cache directories. They are automatically generated by the program. Do not directly Make modifications to these generated files. <BR> Above I briefly introduced some commonly used basic elements in the Smarty program. In the following examples, you can see that they will be used multiple times. <BR> <p align="left"><div style="display:none;"><span id="url" itemprop="url">http://www.bkjia.com/PHPjc/326829.html<span id="indexUrl" itemprop="indexUrl">www.bkjia.com<span id="isOriginal" itemprop="isOriginal">true<span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/326829.html<span id="genre" itemprop="genre">TechArticle<span id="description" itemprop="description">1. Smarty concise tutorial 1. Installation demo Download the latest version of Smarty-3.1.12, and then unzip the downloaded file . Next, we will demonstrate the demo example that comes with Smarty. (1) Download address: http://... <div class="art_confoot"></script>
Statement
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
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.