search
HomeBackend DevelopmentPHP Tutorial基于PHP Web开发MVC框架的Smarty使用说明_PHP

一、Smarty简明教程
1.安装演示
 下载最新版本的Smarty-3.1.12,然后解压下载的文件。接下来演示Smarty自带的demo例子。
(1)下载地址:http://www.smarty.net/download
(2)在你的WEB服务器根目录下建立新目录,这里我在/var/www下创建yqting/目录,然后将解压之后的目录中的demo/和libs/目录复制到/var/www/yqting/目录下。
(3)这里要特别注意demo/目录下cache/和template_c/两个目录,一定要设置它们 为可读写权限
  chmod 777 cache/
  chmod 777 template_c/
(4)启动apache。在浏览器中输入http://localhost/yqting/demo/index.php ,这样一个简单的Smarty demo就实现了。
2.Smarty目录结构
(1)以/var/www/yqting目录开始分析:
  yqting/
    ├── demo
    │ ├── cache   缓冲文件存放目录
    │ ├── configs    配置文件目录
    │ ├── index.php
    │ ├── plugins    自定义的一些实用插件
    │ ├── templates    模板目录
    │ └── templates_c   编译后的文件存放目录
    └── libs
       ├── debug.tpl   debug模板
       ├── plugins    自定义的一些实用插件
       ├── SmartyBC.class.php    支持Smarty 2兼容
       ├── Smarty.class.php   Smarty类定义文件
       └── sysplugins    Smarty核心功能插件,不需要进行修改
(2)添加自己定义的插件
  上述目录结构中,其实最核心的部分是libs/目录,同时这部分也是不允许修改的。
  而要添加自己的插件,一种方法是将自己定义的插件放在libs/plugins/目录下,另一种方式是 单独创建一个自己plugins/目录,同时还要创建cache/、configs/、templates/和templates _c/目录,而且要保证cache/和templates_c/目录的可读写权限。
  不难发现,其实上述例子中,demo/目录就是一个包含了自己定义的插件的完整目录。 我们可以参照demo/目录来实现自己的程序。
3.实现一个简单的例子
(1)在/var/www/yqting/下创建目录weibo/,然后在weibo/目录下创建cache/、 configs/、templates/和templates_c/目录,修改cache/和templates_c/目录的权限为可读写。  
(2)新建一个模板文件:index.tpl,将此文件放在/var/www/yqting/weibo/templates目录下,代码如下:
  
  


  
   Smarty
  
  
  username:{$Name}
  
    这段代码很简单,有什么不明白的继续往下看,不要着急!每一个做显示的.tpl文件都会对应一个处理业务逻辑的.php文件,下面介绍这个.php文件。
(3)新建index.php,将此文件放在/var/www/yqting/weibo/下,代码如下:
  assign("Name",$username);   $smarty->display('index.tpl');   ?>   其中require使用的路径一定要正确,可以参照上面的目录结构看一下!
(4)在Smarty3中,Smarty类的构造函数中已经指定了template_dir、compile_dir 、config_dir和cache_dir,不需要再次指定。     
(5) 在浏览器中输入http://localhost/yqting/weibo/index.php,就可以看到输出的信息username:Smarty 了。
二、解释smarty的程序
  我们可以看到,smarty的程序部分实际就是符合php语言规范的一组代码,我们依次来解释一下:   
(1)/**/语句:
  包含的部分为程序篇头注释。主要的内容应该为对程序的作用,版权与作者及编写时间 做一个简单的介绍,这在smarty中不是必需的,但从程序的风格来讲,这是一个好的风格。   
(2)include_once语句:
  它将安装到网站的smarty文件包含到当前文件中,注意包含的路径一定要写正确。   
(3)$smarty = new Smarty():
  这一句新建一个Smarty对象$smarty,简单的一个对象的实例化。   
(4)$smarty->templates="":
  这一句指明$smarty对象使用tpl模板时的路径,它是一个目录,在没有这一句时, Smarty默认的模板路径为当前目录的templates目录,实际在写程序时,我们要将这一 句写明,这也是一种好的程序风格。   
(5)$smarty->templates_c="":
  这一句指明$smarty对象进行编译时的目录。在模板设计篇我们已经知道Smarty是 一种编译型模板语言,而这个目录,就是它编译模板的目录,要注意,如果站点位于linux 服务器上,请确保 teamplates_c里定义的这个目录具有可写可读权限,默认情况下它的 编译目录是当前目录下的templates_c,出于同样的理由我们将其明确的写出来。   
(6)分隔符 $smarty->left_delimiter与$smarty->right_delimiter:
  指明在查找模板变量时的左右分割符。默认情况下为"{"与"}",但在实际中因为我们要 在模板中使用<script>,Script中的函数定义难免会使用{},虽然它有自己的解决办法,但习惯上我们将它重新定义为"{#"与"#}"或是"<!--{"与"}-->"或其它标志符,注意,如果在这里定义了左右分割符后,在模板文件中相应的要使每一个变量使用与定义相同的符号, 例如在这里指定为"<{"与"}>",html模板中也要相应的将{$name}变成<{$name}>, 这样程序才可以正确的找到模板变量。   <BR>(7)$smarty->cache="./cache": <BR>  告诉Smarty输出的模板文件缓存的位置。上一篇我们知道Smarty最大的优点在于它 可以缓存,这里就是设置缓存的目录。默认情况下为当前目录下的cache目录,与 templates_c目录相当,在linux系统中,我们要确保它的可读可写性。   <BR>(8)$smarty->cache_lifetime = 60 * 60 * 24:   <BR>  这里将以秒为单位进行计算缓存有效的时间。第一次缓存时间到期时当Smarty的 caching变量设置为true时缓存将被重建。当它的取值为-1时表示建立起的缓存从不过期, 为0时表示在程序每次执行时缓 存总是被重新建立。上面的设置表示将cache_lifetime设置为一天。   <BR>(9)$smarty->caching = 1:   <BR>  这个属性告诉Smarty是否要进行缓存以及缓存的方式。<BR>  它可以取3个值,0: Smarty默认值,表示不对模板进行缓存;1:表示Smarty将使用当前定义的 cache_lifetime来决定是否结束cache;2:表示 Smarty将使用在cache被建立时使用 cache_lifetime这个值。习惯上使用true与false来表示是否进行缓存。   <BR>(10)$smarty->assign("name", $username): <BR>  该数的原型为assign(string varname, mixed var),varname为模板中使用的模板变量,var指出要将模板变量替换的变量名;其第二种原形为assign(mixed var),我们要在后面的例子详细的讲解这个成员函数的使用方法,assign是Smarty的核心函数之一, 所有对模板变量的替换都要使用它。   <BR>(11)$smarty->display("index.tpl"):   <BR>  该函数原形为display(string varname),作用为显示一个模板。简单的讲,它将分析 处理过的模板显示出来,这里的模板文件不用加路径,只要使用一个文件名就可以了,它路 径我们已 经在$smarty->templates(string path)中定义过了。   <BR>程序执行完后我们可以打开当前目录下的templates_c与cache目录,就会发现在下 边多出一些%%的目录,这些目录就是Smarty的编译与缓存目录,它由程序自动生成,不 要直接对这些生成的文件进行修改。   <BR>以上我简单的把Smarty程序中的一些常用的基本元素介绍了一下,在后边的例子中你可以看到将它们将被多次的使用。<BR> </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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.