当前位置:首页 > CMS教程 > 其它CMS > 列表

yii,CI,yaf框架+smarty模板使用方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-03 15:29:15 浏览: 评论:0 

这篇文章主要介绍了yii,CI,yaf框架+smarty模板使用方法,结合实例形式介绍了yii,CI及yaf框架整合smaryt模板的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了yii,CI,yaf框架+smarty模板使用方法。分享给大家供大家参考,具体如下:

最近折腾了框架的性能测试,其中需要测试各个模板跟smarty配合的性能,所以折腾了一桶,现总结一下。之前已经写过kohana框架+smarty模板,这里不再重复了。

一、yii框架+smarty模板

yii是覆盖了viewRenderer组件。

1.1,下载yii框架并解压,下载smarty框架并解压,将smarty/libs文件夹拷到yii框架application/protected/vendors下面,并重命名smarty。

1.2,yii配置文件main.php

  1. 'components'=>array( 
  2.  'viewRenderer' => array( 
  3.   'class'=>'batman.protected.extensions.SmartyViewRender', 
  4.   // 这里为Smarty支持的属性 
  5.   'config' => array ( 
  6.     'left_delimiter' => "{#", 
  7.     'right_delimiter' => "#}", 
  8.     'template_dir' => APP_DIR . "/views/", 
  9.     'config_dir' => APP_DIR . "/views/conf/", 
  10.     'debugging' => false, 
  11.     'compile_dir' => 'D:/temp/runtime', 
  12.   ) 
  13. ) 

其中batman是我已经在index.php定义好的别名。

  1. Yii::setPathOfAlias('batman', dirname(__FILE__)); 
  2. Yii::import("batman.protected.vendors.*"); 
  3. define('APP_DIR', dirname(__FILE__).'/protected/'); 

1.3,在protected/extensions/下面新建SmartyViewRender.php

  1. <?php 
  2. class SmartyViewRender extends CApplicationComponent implements IViewRenderer { 
  3.  public $fileExtension = '.html'; 
  4.  private $_smarty = null; 
  5.  public $config = array(); 
  6.  public function init() { 
  7.   $smartyPath = Yii::getPathOfAlias('batman.protected.vendors.smarty'); 
  8.   Yii::$classMap['Smarty'] = $smartyPath . '/Smarty.class.php'; 
  9.   Yii::$classMap['Smarty_Internal_Data'] = $smartyPath . '/sysplugins/smarty_internal_data.php'; 
  10.   $this->_smarty = new Smarty(); 
  11.   // configure smarty 
  12.   if (is_array ( $this->config )) { 
  13.    foreach ( $this->config as $key => $value ) { 
  14.     if ($key {0} != '_') { // not setting semi-private properties 
  15.      $this->_smarty->$key = $value; 
  16.     } 
  17.    } 
  18.   } 
  19.   Yii::registerAutoloader('smartyAutoload'); 
  20.  } 
  21.  public function renderFile($context, $file, $data, $return) { 
  22.    foreach ($data as $key => $value) 
  23.     $this->_smarty->assign($key, $value); 
  24.   $return = $this->_smarty->fetch($file); 
  25.   if ($return) 
  26.     return $return; 
  27.   else 
  28.     echo $return; 
  29.  } 
  30. } 

1.4,验证

新建一个HelloController.php

  1. <?php 
  2. class HelloController extends Controller { 
  3.  public function actionWorld() { 
  4.   $this->render('world', array('content'=>'hello world')); 
  5.  } 
  6. } 

新建一个word.html

  1. <body> 
  2. {#$content#} 
  3. </body> 

二、CI框架+smarty模板

网上很多方法,将smarty作为一个普通的library,在使用的时候,controller代码类似于下面:

  1. public function index() 
  2. { 
  3.   $this->load->library('smarty/Ci_smarty', '', 'smarty'); 
  4.   $this->smarty->assign("title","恭喜你smarty安装成功!"); 
  5.   $this->smarty->assign("body","欢迎使用smarty模板引擎"); 
  6.   $arr = array(1=>'zhang',2=>'xing',3=>'wang'); 
  7.   $this->smarty->assign("myarray",$arr); 
  8.   $this->smarty->display('index_2.html'); 
  9. } 

这种方法跟CI自带的使用模板的方法,代码如下:

$this->load->view();

不和谐,而且要一系列的代码如下:

$this->smarty->assign();

语句,麻烦不说,还破坏了原本CI的简洁美,所以果断唾弃之。

那怎么保持CI加载view时的简洁美呢,答案就是覆盖Loader类的view()方法。好吧,let's begin。

2.1,条件:

到官网上现在CI框架和smarty模板。

2.2,确保CI已经能跑起来

将CI框架解压到网站跟目录下,先写一个不带smarty模板的controller输出“hello world”。

2.3,引入smarty

将smarty解压,将libs文件夹考到application/third_paty下面,并将libs重命名smarty,重命名取什么都ok了,这里就叫smarty吧。

2.4,覆盖loader类的view()方法

因为view()方法在Loader类里,所以我要覆盖Loader的view()方法。

先看看$this->load->view()是怎么工作的?CI_Controller类的构造函数里有这么一行,代码如下:

$this->load =& load_class('Loader', 'core');

load_class函数会先在application/core下面找config_item('subclass_prefix').Loader.php文件,找不到再到system/core下面找Loader.php。config_item('subclass_prefix')就是在配置文件里写的你要继承CI核心类的子类的前缀。我使用的是默认值'MY_'。找到文件后,require该文件,然后new MY_Loader(如果application/core/MY_Loader.php存在),或者是new Loader,赋值给$this->load。

在application/core下面新建一个MY_Loader.php文件

  1. <?php 
  2. define('DS', DIRECTORY_SEPARATOR); 
  3. class MY_Loader extends CI_Loader { 
  4.  public $smarty; 
  5.  public function __construct() { 
  6.   parent::__construct(); 
  7.   require APPPATH.'third_party'.DS.'smarty'.DS.'smarty.class.php'; 
  8.   $this->smarty = new Smarty (); 
  9.   // smarty 配置 
  10.   $this->smarty->template_dir= APPPATH.'views'.DS;//smarty模板文件指向ci的views文件夹 
  11.   $this->smarty->compile_dir = 'd:/temp/tpl_c/'; 
  12.   $this->smarty->config_dir = APPPATH.'libraries/smarty/configs/'; 
  13.   $this->smarty->cache_dir  = 'd:/temp/cache'; 
  14.   $this->smarty->left_delimiter = '{#'; 
  15.   $this->smarty->right_delimiter = '#}'; 
  16.  } 
  17.  public function view($view, $vars = array(), $return = FALSE) 
  18.  { 
  19.   // check if view file exists 
  20.   $view .= config_item('templates_ext'); 
  21.   $file = APPPATH.'views'.DS.$view; 
  22.   if (! file_exists ( $file ) || realpath ( $file ) === false) { 
  23.    exit( __FILE__.' '.__LINE__."<br/>View file {$file} does not exist, <br/>{$file} => {$view}"); 
  24.   } 
  25.   // changed by simeng in order to use smarty debug 
  26.   foreach ( $vars as $key => $value ) { 
  27.    $this->smarty->assign ( $key, $value ); 
  28.   } 
  29.   // render or return 
  30.   if ($return) { 
  31.    ob_start (); 
  32.   } 
  33.   $this->smarty->display ( $view ); 
  34.   if ($return) { 
  35.    $res = ob_get_contents (); 
  36.    ob_end_clean (); 
  37.    return $res; 
  38.   } 
  39.  } 
  40. } 

我把template_ext配置成了".html",这样就ok了。我们来验证一下吧。

2.5,验证

在controller下面建一个home.php

  1. class Home extends CI_Controller { 
  2.  public function index() { 
  3.   $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); 
  4.   $data['title'] = "恭喜你smarty安装成功!"; 
  5.   $data['body'] = "欢迎使用smarty模板引"; 
  6.   $arr = array(1=>'zhang',2=>'xing',3=>'wang'); 
  7.   $data['myarray'] = $arr; 
  8.   $this->load->view('index_2', $data); 
  9.  } 
  10. } 

在views下面建一个index_2.html

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4.  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  5.  <script src='<!--{$base_url}-->js/jquery.min.js' type='text/javascript' ></script> 
  6.  <link href="<!--{$base_url}-->css/login.css" rel="stylesheet" type="text/css" /> 
  7.  <title>smarty安装测试</title> 
  8. </head> 
  9. <body> 
  10. <h1>{#$title#}</h1> 
  11. <p>{#$body#}</p> 
  12. <ul> 
  13.   {#foreach from=$myarray item=v#} 
  14.   <li>{#$v#}</li> 
  15.   {#/foreach#} 
  16. </ul> 
  17. </body> 
  18. </html> 

好了,可以试试你的成果了。

三、yaf框架+smarty模板

yaf是利用引导文件Bootstrap.php来加载smarty。

3.1,使用Bootstrap

在index.php中用:

$app->bootstrap()->run();

引入Bootstrap.php文件

3.2,在application/Bootstrap.php文件中导入smarty。

  1. <?php 
  2. class Bootstrap extends Yaf_Bootstrap_Abstract { 
  3.  public function _initSmarty(Yaf_Dispatcher $dispatcher) { 
  4.   $smarty = new Smarty_Adapter(null, Yaf_Application::app()->getConfig()->smarty); 
  5.   Yaf_Dispatcher::getInstance()->setView($smarty); 
  6.  } 
  7. } 

3.3,添加Smarty_Adapter类

将smarty解压后放到application/library文件夹下,重命名为Smarty。在Smarty下新建Adapter.php,确保Smarty.class.php在Smarty/libs/下。Adapter.php内容:

  1. <?php 
  2. Yaf_Loader::import( "Smarty/libs/Smarty.class.php"); 
  3. Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatecompilerbase.php"); 
  4. Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatelexer.php"); 
  5. Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templateparser.php"); 
  6. Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_compilebase.php"); 
  7. Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_write_file.php"); 
  8. class Smarty_Adapter implements Yaf_View_Interface 
  9. { 
  10.  /** 
  11.   * Smarty object 
  12.   * @var Smarty 
  13.   */ 
  14.  public $_smarty; 
  15.  /** 
  16.   * Constructor 
  17.   * 
  18.   * @param string $tmplPath 
  19.   * @param array $extraParams 
  20.   * @return void 
  21.   */ 
  22.  public function __construct($tmplPath = null, $extraParams = array()) { 
  23.   $this->_smarty = new Smarty; 
  24.   if (null !== $tmplPath) { 
  25.    $this->setScriptPath($tmplPath); 
  26.   } 
  27.   foreach ($extraParams as $key => $value) { 
  28.    $this->_smarty->$key = $value; 
  29.   } 
  30.  } 
  31.  /** 
  32.   * Return the template engine object 
  33.   * 
  34.   * @return Smarty 
  35.   */ 
  36.  public function getEngine() { 
  37.   return $this->_smarty; 
  38.  } 
  39.  /** 
  40.   * Set the path to the templates 
  41.   * 
  42.   * @param string $path The directory to set as the path. 
  43.   * @return void 
  44.   */ 
  45.  public function setScriptPath($path) 
  46.  { 
  47.   if (is_readable($path)) { 
  48.    $this->_smarty->template_dir = $path; 
  49.    return; 
  50.   } 
  51.   throw new Exception('Invalid path provided'); 
  52.  } 
  53.  /** 
  54.   * Retrieve the current template directory 
  55.   * 
  56.   * @return string 
  57.   */ 
  58.  public function getScriptPath() 
  59.  { 
  60.   return $this->_smarty->template_dir; 
  61.  } 
  62.  /** 
  63.   * Alias for setScriptPath 
  64.   * 
  65.   * @param string $path 
  66.   * @param string $prefix Unused 
  67.   * @return void 
  68.   */ 
  69.  public function setBasePath($path, $prefix = 'Zend_View') 
  70.  { 
  71.   return $this->setScriptPath($path); 
  72.  } 
  73.  /** 
  74.   * Alias for setScriptPath 
  75.   * 
  76.   * @param string $path 
  77.   * @param string $prefix Unused 
  78.   * @return void 
  79.   */ 
  80.  public function addBasePath($path, $prefix = 'Zend_View') 
  81.  { 
  82.   return $this->setScriptPath($path); 
  83.  } 
  84.  /** 
  85.   * Assign a variable to the template 
  86.   * 
  87.   * @param string $key The variable name. 
  88.   * @param mixed $val The variable value. 
  89.   * @return void 
  90.   */ 
  91.  public function __set($key, $val) 
  92.  { 
  93.   $this->_smarty->assign($key, $val); 
  94.  } 
  95.  /** 
  96.   * Allows testing with empty() and isset() to work 
  97.   * 
  98.   * @param string $key 
  99.   * @return boolean 
  100.   */ 
  101.  public function __isset($key) 
  102.  { 
  103.   return (null !== $this->_smarty->get_template_vars($key)); 
  104.  } 
  105.  /** 
  106.   * Allows unset() on object properties to work 
  107.   * 
  108.   * @param string $key 
  109.   * @return void 
  110.   */ 
  111.  public function __unset($key) 
  112.  { 
  113.   $this->_smarty->clear_assign($key); 
  114.  } 
  115.  /** 
  116.   * Assign variables to the template 
  117.   * 
  118.   * Allows setting a specific key to the specified value, OR passing 
  119.   * an array of key => value pairs to set en masse. 
  120.   * 
  121.   * @see __set() 
  122.   * @param string|array $spec The assignment strategy to use (key or 
  123.   * array of key => value pairs) 
  124.   * @param mixed $value (Optional) If assigning a named variable, 
  125.   * use this as the value. 
  126.   * @return void 
  127.   */ 
  128.  public function assign($spec, $value = null) { 
  129.   if (is_array($spec)) { 
  130.    $this->_smarty->assign($spec); 
  131.    return; 
  132.   } 
  133.   $this->_smarty->assign($spec, $value); 
  134.  } 
  135.  /** 
  136.   * Clear all assigned variables 
  137.   * 
  138.   * Clears all variables assigned to Zend_View either via 
  139.   * {@link assign()} or property overloading 
  140.   * ({@link __get()}/{@link __set()}). 
  141.   * 
  142.   * @return void 
  143.   */ 
  144.  public function clearVars() { 
  145.   $this->_smarty->clear_all_assign(); 
  146.  } 
  147.  /** 
  148.   * Processes a template and returns the output. 
  149.   * 
  150.   * @param string $name The template to process. 
  151.   * @return string The output. 
  152.   */ 
  153.  public function render($name, $value = NULL) { 
  154.   return $this->_smarty->fetch($name); 
  155.  } 
  156.  public function display($name, $value = NULL) { 
  157.   echo $this->_smarty->fetch($name); 
  158.  } 
  159. } 

3.4,smarty配置文件。

再来看看我们的conf/application.ini文件

  1. [common] 
  2. application.directory = APP_PATH "/application" 
  3. application.dispatcher.catchException = TRUE 
  4. application.view.ext="tpl" 
  5. [smarty : common] 
  6. ;configures for smarty 
  7. smarty.left_delimiter = "{#" 
  8. smarty.right_delimiter = "#}" 
  9. smarty.template_dir  = APP_PATH "/application/views/" 
  10. smarty.compile_dir  = '/data1/www/cache/' 
  11. smarty.cache_dir  = '/data1/www/cache/' 
  12. [product : smarty] 

3.5,验证

新建一个controller,添加方法:

  1. public function twoAction() { 
  2.   $this->getView()->assign('content', 'hello World'); 
  3. } 

新建一个模板two.tpl

  1. <html> 
  2. <head> 
  3. <title>A Smarty Adapter Example</title> 
  4. </head> 
  5. <body> 
  6. {#$content#} 
  7. </body> 
  8. </html> 

希望本文所述对大家PHP程序设计有所帮助。

Tags: yii CI yaf smarty

分享到: