漂定

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1.       【在protected目录下建立文件夹vendor/smarty,把smarty的类包放入其中】

2.       【在extensions目录下边建立文件CSmarty.php

//CSmarty.php文件具体内容如下(意思自己体会理解):

<?php

require_once(Yii::getPathOfAlias(‘application.vendor.smarty’).DIRECTORY_SEPARATOR.’Smarty.class.php’);

define(‘SMARTY_VIEW_DIR’,Yii::getPathOfAlias(‘application.views.smarty’));

class CSmarty extends Smarty {

                  const DS =DIRECTORY_SEPARATOR;

                 function __construct() {

                     parent::__construct();

                     $this->template_dir =SMARTY_VIEW_DIR.self::DS.’tpl’;

                     $this->compile_dir =SMARTY_VIEW_DIR.self::DS.’tpl_c’;

                     $this->caching = true;

                     $this->cache_dir =SMARTY_VIEW_DIR.self::DS.’cache’;

                     $this->left_delimiter =  ‘{‘;

                     $this->right_delimiter = ‘}’;

                     $this->cache_lifetime = 3600;

                 }

                 function init() {}

}

 

3.       【根据CSmarty.php代码内容建立相应的文件夹】

4.       【主配置文件设置】
打开protected/config/main.php

在components数组中加入

‘smarty’=>array(

           ‘class’=>’application.extensions.CSmarty’,

),

5.       【得到smarty实例】

在控制器里边:

Yii::app()->smarty();

实例:

       public function actionIndex(){

           Yii::app()->smarty() -> assign(‘name’,'张三’);

              //a.tpl所在目录protected/views/smarty/tpl/a.tpl,具体代码{$name}

          Yii::app()->smarty() -> display(‘a.tpl’);

}

此时系统会报错:

原因:

YII注册了一个自动加载类spl_autoload_register(array(‘YiiBase’,'autoload’)),SMARTY也注册了一个自动加载类,spl_autoload_register(‘smartyAutoload’),YII 注册在前,这样在遇到一个类名的时候,先执行的是YII的自定义自动加载类的函数,对应SMARTY里的每个类名而言,也是先调用YII的自动加载类的函 数,但是如果不符合YII自动加载的条件的话,就会执行SMARTY的自动加载类的函数,然而,SMARTY的类名在自动加载类的时候,确符合了YII自 动加载类的逻辑语句,结果就是YII使用Include语句要包含的类肯定找不到。

解决方法:

当SMARTY的类自动加载的时候,跳出在YII定义的自动加载函数,这样就会执行SMARTY的加载函数。

具体实现是,修改YIIBase类里面的autoload函数,增加如下代码:

public static function autoload($className){

                 //只要类名包含smarty的,无论大小写,都返回,

//这样就跳出了YII自动加载类而去执行SMARTY的自动加载类函数了

                 if(preg_match(‘/smarty/i’, $className)){

                    return;

                 }

。。。。。

再次测试:

OK了

 

6.       【优化】

在action中直接用Yii::app()->smarty就可以试用smarty了。

如果每次在action中使用Yii::app()->smarty比较麻烦的话,

可以在components下的Controller中可以加入

protected $smarty = ”;

protected function init() {

       $this->smarty = Yii::app()->smarty;

      }

然后在action中就直接可以用$this->smarty使用smarty了。

Yii集成smarty说明

posted on 2013-12-26 20:28  漂定  阅读(535)  评论(0编辑  收藏  举报