Smarty 是什么?
为什么使用它?
用例和工作流程
语法比较
模板继承
最佳实践
速成课程
我们将从 index.php 开始,这是应用程序的入口点。这是由网络浏览器直接访问的文件。
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* File: index.php
* Version: 1.1
*/
// define our application directory
define('GUESTBOOK_DIR', '/web/www.example.com/smarty/guestbook/');
// define smarty lib directory
define('SMARTY_DIR', '/usr/local/lib/php/Smarty/');
// include the setup script
include(GUESTBOOK_DIR . 'libs/guestbook_setup.php');
// create guestbook object
$guestbook = new Guestbook;
// set the current action
$_action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view';
switch($_action) {
case 'add':
// adding a guestbook entry
$guestbook->displayForm();
break;
case 'submit':
// submitting a guestbook entry
$guestbook->mungeFormData($_POST);
if($guestbook->isValidForm($_POST)) {
$guestbook->addEntry($_POST);
$guestbook->displayBook($guestbook->getEntries());
} else {
$guestbook->displayForm($_POST);
}
break;
case 'view':
default:
// viewing the guestbook
$guestbook->displayBook($guestbook->getEntries());
break;
}
?>
index.php 文件充当应用程序控制器。它处理所有传入的浏览器请求并指示要执行的操作。它将定义我们的应用程序目录,包含设置脚本,并根据 $_REQUEST 超全局变量中的 action 值来执行操作。我们将有三个基本操作:当用户想要向留言本中添加一个分录时添加,当用户提交一个分录时提交,当用户显示留言本时查看。默认操作是查看。
<?php /** * Project: Guestbook Sample Smarty Application * Author: Monte Ohrt* File: guestbook_setup.php * Version: 1.1 */ require(GUESTBOOK_DIR . 'libs/guestbook.lib.php'); require(SMARTY_DIR . 'Smarty.class.php'); // smarty configuration class Guestbook_Smarty extends Smarty { function __construct() { parent::__construct(); $this->setTemplateDir(GUESTBOOK_DIR . 'templates'); $this->setCompileDir(GUESTBOOK_DIR . 'templates_c'); $this->setConfigDir(GUESTBOOK_DIR . 'configs'); $this->setCacheDir(GUESTBOOK_DIR . 'cache'); } } ?>
guestbook_setup.php是我们在其中进行一些基本应用程序配置的地方,例如我们的数据库和模板配置。我们将使用 PHP 5 提供的PDO数据库抽象化库。我们将使用 MySQL 作为我们的数据库,输入适合于您数据库设置的适当的 dsn 信息。
我们需要一个基本数据库设置。以下是您可以用 mysql < guestbook.sql 直接转储到 MySQL 中的脚本。确保使用您的数据库/用户信息更改 GRANT 行。
CREATE DATABASE GUESTBOOK; USE GUESTBOOK; CREATE TABLE GUESTBOOK ( id int(11) NOT NULL auto_increment, Name varchar(255) NOT NULL default '', EntryDate datetime NOT NULL default '0000-00-00 00:00:00', Comment text NOT NULL, PRIMARY KEY (id), KEY EntryDate (EntryDate) ) TYPE=MyISAM; GRANT ALL ON GUESTBOOK.* to guestbook@localhost identified by 'foobar';