基本方法:将Smarty以组件方式加入应用中。
一导入smarty核心包文件夹libs,此时Smarty.class.php路径如下:
---protected/extensions/smarty/libs/Smarty.class.php
二新建一个类以继承核心类Smarty,主要是设置smarty的参数(包括四个目录和定界符),这里类名为YCSmarty,路径如下
--protected/extensions/smarty/YCSmarty.php
该文件的全部代码如下
<?php
require_once(Yii::getPathOfAlias('application.extensions.smarty.libs').DIRECTORY_SEPARATOR.'Smarty.class.php');
define('SMARTY_VIEW_DIR', Yii::getPathOfAlias('application.views'));
class YCSmarty extends Smarty{
const DIR_SEP = DIRECTORY_SEPARATOR;
public function __construct(){
parent::__construct();
$this->template_dir = SMARTY_VIEW_DIR.self::DIR_SEP.'templates';
$this->compile_dir = SMARTY_VIEW_DIR.self::DIR_SEP.'template_c';
$this->config_dir = SMARTY_VIEW_DIR.self::DIR_SEP.'config';
$this->cache_dir = SMARTY_VIEW_DIR.self::DIR_SEP.'cache';
$this->left_delimiter = '<{';
$this->right_delimiter = '}>';
}
public function init(){}
}
?>
三修改配置文件protected/config/main.php,在组件项目添加YCSmarty类的配置,并在导入项目中增加一二步的所有文件导入配置。
此时配置文件如下:
return array(
'import'=>array(
'application.extensions.*',
),
'components'=>array(
'smarty'=>array(
'class' => 'application.extensions.smarty.YCSmarty',
),
),
);
四在protected/views下新建四个文件夹templates,template_c,cache,config,此路径的配置在YCSmarty.php文件中。
五测试在控制器中就可以用$smarty = Yii::app()->smarty来获取到自己定义的YCSmarty这个对象,注意的是组件表现为单例模式,smarty就是它的ID。