尽管PHP的语法本身就是套很不错的模板引擎了,但是在模板中不停的敲类似<?php ?>
的代码也挺烦的,整合smarty吧
CI框架:3.1.2
Smarty:3.1.30
网上有一大堆整合的例子可以用,但都不完全正确。
因为他们破坏了CI框架的主流程,导致CI本身的缓存机制失效了
(原机制在流程前端根据url的md5直接读取缓存),主流程必须进入到控制器再读取smarty缓存。
不改不舒服,那就改吧。
1)、将必要文件拷入application/libraries/ 目录下
遵循CI框架约定。CI框架对于放在libraries下的.php类文件可以在控制器中使用$this->load->library()方法加载并实例化对像。当然如果你愿意,也可以放到任意地方,然后include进来,再手工new一个实例对像。
2)、创建自定义类Cismarty.php(位于application/libraries/ 目录下)
该类继承Smarty类,主要用于加载并初始化smarty配置
<?php
if(!defined('BASEPATH')) EXIT('No direct script asscess allowed');
require_once( APPPATH . 'libraries/smarty-3.1.30/libs/Smarty.class.php' );
class Cismarty extends Smarty {
protected $ci;
public function __construct(){
parent::__construct();
$this->ci = & get_instance();
//加载smarty的配置文件
$this->ci->load->config('smarty');
//设置相关的配置项
//$this->template_dir=$this->ci->config->item('template_dir');
$this->setTemplateDir($this->ci->config->item('template_dir'));
$this->setCompileDir($this->ci->config->item('compile_dir'));
$this->setConfigDir($this->ci->config->item('config_dir'));
$this->setCacheDir($this->ci->config->item('cache_dir'));
}
}
这里要注意调用父类构造方法,不然会出错
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: sysplugins/smarty_internal_templatecompilerbase.php
Line Number: 334
A PHP Error was encountered
Severity: Error
Message: Call to a member function create() on null
Filename: sysplugins/smarty_internal_templatecompilerbase.php
Line Number: 334
3)、创建配置文件smarty.php(位于application/config/ 目录下)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['theme'] = 'default';
$config['template_dir'] = APPPATH . 'views';
$config['compile_dir'] = APPPATH . 'templates_c';
$config['cache_dir'] = APPPATH . 'cache';
$config['config_dir'] = APPPATH . 'configs';
$config['template_ext'] = '.html';
$config['caching'] = false;
$config['lefttime'] = 60;
4)、在项目目录的application/core文件夹中新建文件MY_Controller.php 内容如下: // 扩展核心控制类
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function assign($key,$val) {
$this->cismarty->assign($key,$val);
}
//注意这里,load类中的template方法,在后面会说到如何扩充
public function display($html) {
$this->load->template($html);
}
}
5)、配置自动加载:
因为用到了类库cismarty,我们在自动加载那里给配置上,这样就不用每次在控制器中
this−>load−>library(“cismarty”)打开config目录下的autoload.php文件给
autoload[‘libraries’]的数组加上’cismarty’。我的文件如下:
$autoload['libraries'] =array('cismarty', 'database', 'session');
6)、修改所有控制器的继承父类:从原来的CI_Controller改成MY_Controller
7)、扩展Loader类
在项目目录的application/core文件夹中新建文件MY_Loader.php 内容如下:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Loader extends CI_Loader {
public function __construct()
{
parent::__construct();
}
//扩充template函数
public function template($viewpath)
{
return $this->_ci_load($viewpath,true);
}
protected function _ci_load($_ci_data, $outstring=false)
{
//主要是这一段-------------------------------------------------
$_ci_CI =& get_instance();
if($outstring===true){
$result = $_ci_CI->cismarty->fetch($_ci_data);
ob_start();
echo $result;
if (ob_get_level() > $this->_ci_ob_level + 1)
{
ob_end_flush();
}
else
{
$_ci_CI->output->append_output(ob_get_contents());
@ob_end_clean();
}
return;
}
//---------------------------------------------------------------
//后面不变
// Set the default data variables
foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
{
$$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;
//echo $_ci_val,":",var_export($$_ci_val),'<br>';
}
$file_exists = FALSE;
// Set the path to the requested file
if (is_string($_ci_path) && $_ci_path !== '')
{
$_ci_x = explode('/', $_ci_path);
$_ci_file = end($_ci_x);
}
else
{
$_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
$_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;
foreach ($this->_ci_view_paths as $_ci_view_file => $cascade)
{
if (file_exists($_ci_view_file.$_ci_file))
{
$_ci_path = $_ci_view_file.$_ci_file;
$file_exists = TRUE;
break;
}
if ( ! $cascade)
{
break;
}
}
}
if ( ! $file_exists && ! file_exists($_ci_path))
{
show_error('Unable to load the requested file: '.$_ci_file);
}
// This allows anything loaded using $this->load (views, files, etc.)
// to become accessible from within the Controller and Model functions.
foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
{
if ( ! isset($this->$_ci_key))
{
$this->$_ci_key =& $_ci_CI->$_ci_key;
}
}
/*
* Extract and cache variables
*
* You can either set variables using the dedicated $this->load->vars()
* function or via the second parameter of this function. We'll merge
* the two types and cache them so that views that are embedded within
* other views can have access to these variables.
*/
if (is_array($_ci_vars))
{
$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
}
extract($this->_ci_cached_vars);
ob_start();
// If the PHP installation does not support short tags we'll
// do a little string replacement, changing the short tags
// to standard PHP echo statements.
if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE)
{
echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
}
else
{
include($_ci_path); // include() vs include_once() allows for multiple views with the same name
}
log_message('info', 'File loaded: '.$_ci_path);
// Return the file data if requested
if ($_ci_return === TRUE)
{
$buffer = ob_get_contents();
@ob_end_clean();
return $buffer;
}
/*
* Flush the buffer... or buff the flusher?
*
* In order to permit views to be nested within
* other views, we need to flush the content back out whenever
* we are beyond the first level of output buffering so that
* it can be seen and included properly by the first included
* template and any subsequent ones. Oy!
*/
if (ob_get_level() > $this->_ci_ob_level + 1)
{
ob_end_flush();
}
else
{
$_ci_CI->output->append_output(ob_get_contents());
@ob_end_clean();
}
return $this;
}
}
调用方式:
控制器:Sma.php
class Sma extends MY_Controller {
public function __construct()
{
parent::__construct();
}
public function test(){
$data['title'] = '明叔';
$data['desc'] = '这个大叔有点二';
$this->assign('data',$data);
//根据需要开启CI缓存
//$this->output->cache(10);
$this->display('test.html');
}
}
模板:test.html
{$data.title}<br>{$data.desc}
至此访问对应控制器输出:
明叔 这个大叔有点二
再把$this->output->cache(10);
这行注释去掉,
再次访问,发现CI的application/cache下多了CI可识别的缓存文件,内容好如下:
a:2:{s:6:”expire”;i:1479183059;s:7:”headers”;a:0:{}}ENDCI—>明叔
这个大叔有点二