CodeIgniter整合Smarty背景与版本说明
本实例详细解析CodeIgniter与Smarty的整合步骤,供开发者参考借鉴。
在CI 3.0.2发布后,其内置模板类因缺乏编译功能且体验不佳,往往难以满足需求。鉴于Smarty具备强大的标签体系及文件编译执行特性,能显著提升速度,将其与CI结合可有效弥补原生模板功能的短板。本文基于CI 3.0.3与Smarty 3.1.27版本演示整合流程。
第一步:获取Smarty 3.1.27安装包。
第二步:解压Smarty 3.1.27至CI项目的application\libraries目录,并删除其他无关文件。
第三步:在application\libraries目录下新建Ci_smarty.php文件,具体代码实现如下。
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'libraries/smarty-3.1.27/libs/Smarty.class.php');
class Ci_smarty extends Smarty {
protected $ci;
public function __construct()
{
parent::__construct();
$this->ci = & get_instance();
$this->ci->load->config('smarty');//加载smarty的配置文件
$this->cache_lifetime =$this->ci->config->item('cache_lifetime');
$this->caching = $this->ci->config->item('caching');
$this->config_dir = $this->ci->config->item('config_dir');
$this->template_dir = $this->ci->config->item('template_dir');
$this->compile_dir = $this->ci->config->item('compile_dir');
$this->cache_dir = $this->ci->config->item('cache_dir');
$this->use_sub_dirs = $this->ci->config->item('use_sub_dirs');
$this->left_delimiter = $this->ci->config->item('left_delimiter');
$this->right_delimiter = $this->ci->config->item('right_delimiter');
}
}
第四步:在application\config目录下创建smarty.php配置文件,代码内容如下。
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['cache_lifetime'] = 60;
$config['caching'] = false;
$config['template_dir'] = APPPATH .'views';
$config['compile_dir'] = APPPATH .'views/template_c';
$config['cache_dir'] = APPPATH . 'views/cache';
$config['config_dir'] = APPPATH . 'views/config';
$config['use_sub_dirs'] = false; //子目录变量(是否在缓存文件夹中生成子目录)
$config['left_delimiter'] = '{';
$config['right_delimiter'] = '}';
第五步:在application\core目录下创建MY_controller.php文件,代码如下。
class MY_controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function assign($key,$val)
{
$this->ci_smarty->assign($key,$val);
}
public function display($html)
{
$this->ci_smarty->display($html);
}
}
至此,基础配置工作已完成,接下来需验证配置是否生效。
第七步:修改application\controllers下的Welcome.php文件,代码示例如下。
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends MY_controller {
public function index()
{
$test='ci 3.0.3 + smarty 3.1.27 配置成功';
$this->assign('test',$test);
$this->display('test.html');
}
}
随后,在application\views目录下建立test.html文件,代码结构如下。
{$test}
在浏览器地址栏访问:http://localhost/index.php/Welcome
页面输出结果如下。
ci 3.0.3 + smarty 3.1.27 配置成功
配置测试成功!
期望上述内容对使用CodeIgniter框架进行PHP开发的读者有所助益。