一,模板,框架,cms的区别
在介绍smarty之前先讨论一下他们的区别,说实话,刚开始做开发的时候,真的没搞清楚他们的区别,感觉都差不多,记得有一次去面试,面试的人问我,模板和框架有什么区别,我说没什么区别,我汗。举个例子:
1,如果把一个项目比做一个人体模具的话,那么模板就是衣服,而框架呢就是骨架。
2,没有衣服没关系可以不穿,如果没有骨架的话,要衣服有什么呢?php本身就是脚本语言,本身就可以输出。
3,但是如果做大项目没有模板的话,如果你要把网站改版一次,我想你会疯了得。
4,框架是约束程序员开发,使他们的代码尽量一致,相互都可以改。
5,cms是半成品的人体模具,东西都做的差不多,你只要在里面修修补补,就差不多,他对程序员的约束更大。
二,什么是smarty
Smarty是一个php模板引擎。更准确的说,它分开了逻辑程序和外在的表现内容,提供了一种易于管理的方法。css使html和style分开了,jquery的出现使得html和js分开了,我想模板的出现使php和html分开了。smarty算是一个不错的模板吧。
三,举例如下
1,配置文件init.php
define('ROOT_PATH', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
define('TEM_PATH', ROOT_PATH ."smartytest". DIRECTORY_SEPARATOR);
$_path = array(
'.',
ROOT_PATH .DIRECTORY_SEPARATOR."smartytest".DIRECTORY_SEPARATOR.'smarty'.DIRECTORY_SEPARATOR.'libs',
get_include_path(),
);
set_include_path(implode(PATH_SEPARATOR, $_path));
?>
2,control.php底基类
session_start();
require('Smarty.class.php');
class Controller
{
public $tpl = NULL;
public function __construct() {
$this->tpl = new Smarty();
$this->tpl->debugging = false;
$this->tpl->compile_check = true;
$this->tpl->force_compile = false;
$this->tpl->cache_dir = TEM_PATH ."templates_cache";
$this->tpl->template_dir = TEM_PATH . "templates";
$this->tpl->compile_dir = TEM_PATH . "templates_c";
$this->tpl->cache = false;
}
public function addCss($css) {
if (!is_array($css)) {
$this->tpl->append('cssArr', $css);
} else {
$this->tpl->append('cssArr', $css, true);
}
}
public function addJs($js) {
if (!is_array($js)) {
$this->tpl->append('jsArr', $js);
} else {
$this->tpl->append('jsArr', $js, true);
}
}
}
?>
3,入口index.php
require_once 'init.php';
require_once 'control.php';
class indexController extends Controller {
private $templateName = 'index.tpl';
private $test = array("安徽","合肥","六安","苏埠");
public function __construct(){
parent::__construct();
}
//页面入口程序
public function indexAction(){
$this->tpl->assign("checkbox",$this->test);
}
//模板渲染
public function showTemplate(){
$this->tpl->display($this->templateName);
}
}
$objIndex = new indexController();
$objIndex->indexAction();
$objIndex->showTemplate();
?>