《PHP實戰:yii,CI,yaf框架+smarty模板使用方法》要點:
本文介紹了PHP實戰:yii,CI,yaf框架+smarty模板使用方法,希望對您有用。如果有疑問,可以聯系我們。
相關主題:YII框架
PHP應用本文實例講述了yii,CI,yaf框架+smarty模板使用辦法.分享給大家供大家參考,具體如下:
PHP應用最近折騰了框架的性能測試,其中需要測試各個模板跟smarty配合的性能,所以折騰了一桶,現總結一下.之前已經寫過kohana框架+smarty模板,這里不再重復了.
PHP應用一、yii框架+smarty模板
PHP應用yii是覆蓋了viewRenderer組件.
PHP應用1.1,下載yii框架并解壓,下載smarty框架并解壓,將smarty/libs文件夾拷到yii框架application/protected/vendors下面,并重命名smarty.
PHP應用1.2,yii配置文件main.php
PHP應用
'components'=>array(
'viewRenderer' => array(
'class'=>'batman.protected.extensions.SmartyViewRender',
// 這里為Smarty支持的屬性
'config' => array (
'left_delimiter' => "{#",
'right_delimiter' => "#}",
'template_dir' => APP_DIR . "/views/",
'config_dir' => APP_DIR . "/views/conf/",
'debugging' => false,
'compile_dir' => 'D:/temp/runtime',
)
)
PHP應用其中batman是我已經在index.php定義好的別名.
PHP應用
Yii::setPathOfAlias('batman', dirname(__FILE__));
Yii::import("batman.protected.vendors.*");
define('APP_DIR', dirname(__FILE__).'/protected/');
PHP應用1.3,在protected/extensions/下面新建SmartyViewRender.php
PHP應用
<?php
class SmartyViewRender extends CApplicationComponent implements IViewRenderer {
public $fileExtension = '.html';
private $_smarty = null;
public $config = array();
public function init() {
$smartyPath = Yii::getPathOfAlias('batman.protected.vendors.smarty');
Yii::$classMap['Smarty'] = $smartyPath . '/Smarty.class.php';
Yii::$classMap['Smarty_Internal_Data'] = $smartyPath . '/sysplugins/smarty_internal_data.php';
$this->_smarty = new Smarty();
// configure smarty
if (is_array ( $this->config )) {
foreach ( $this->config as $key => $value ) {
if ($key {0} != '_') { // not setting semi-private properties
$this->_smarty->$key = $value;
}
}
}
Yii::registerAutoloader('smartyAutoload');
}
public function renderFile($context, $file, $data, $return) {
foreach ($data as $key => $value)
$this->_smarty->assign($key, $value);
$return = $this->_smarty->fetch($file);
if ($return)
return $return;
else
echo $return;
}
}
PHP應用1.4,驗證
PHP應用新建一個HelloController.php
PHP應用
<?php
class HelloController extends Controller {
public function actionWorld() {
$this->render('world', array('content'=>'hello world'));
}
}
PHP應用新建一個word.html
PHP應用
<body>
{#$content#}
</body>
PHP應用二、CI框架+smarty模板
PHP應用網上很多辦法,將smarty作為一個普通的library,在使用的時候,controller代碼類似于下面:
PHP應用
public function index()
{
$this->load->library('smarty/Ci_smarty', '', 'smarty');
$this->smarty->assign("title","恭喜你smarty安裝成功!");
$this->smarty->assign("body","歡迎使用smarty模板引擎");
$arr = array(1=>'zhang',2=>'xing',3=>'wang');
$this->smarty->assign("myarray",$arr);
$this->smarty->display('index_2.html');
}
PHP應用這種辦法跟CI自帶的使用模板的辦法
PHP應用那怎么保持CI加載view時的簡潔美呢,答案就是覆蓋Loader類的view()辦法.好吧,let's begin.
PHP應用2.1,條件:
PHP應用到官網上現在CI框架和smarty模板.
PHP應用2.2,確保CI已經能跑起來
PHP應用將CI框架解壓到網站跟目錄下,先寫一個不帶smarty模板的controller輸出“hello world”.
PHP應用2.3,引入smarty
PHP應用將smarty解壓,將libs文件夾考到application/third_paty下面,并將libs重命名smarty,重命名取什么都ok了,這里就叫smarty吧.
PHP應用2.4,覆蓋loader類的view()辦法
PHP應用因為view()辦法在Loader類里,所以我要覆蓋Loader的view()辦法.
PHP應用先看看$this->load->view()是怎么工作的?CI_Controller類的構造函數里有這么一行
PHP應用在application/core下面新建一個MY_Loader.php文件
PHP應用
<?php
define('DS', DIRECTORY_SEPARATOR);
class MY_Loader extends CI_Loader {
public $smarty;
public function __construct() {
parent::__construct();
require APPPATH.'third_party'.DS.'smarty'.DS.'smarty.class.php';
$this->smarty = new Smarty ();
// smarty 配置
$this->smarty->template_dir= APPPATH.'views'.DS;//smarty模板文件指向ci的views文件夾
$this->smarty->compile_dir = 'd:/temp/tpl_c/';
$this->smarty->config_dir = APPPATH.'libraries/smarty/configs/';
$this->smarty->cache_dir = 'd:/temp/cache';
$this->smarty->left_delimiter = '{#';
$this->smarty->right_delimiter = '#}';
}
public function view($view, $vars = array(), $return = FALSE)
{
// check if view file exists
$view .= config_item('templates_ext');
$file = APPPATH.'views'.DS.$view;
if (! file_exists ( $file ) || realpath ( $file ) === false) {
exit( __FILE__.' '.__LINE__."<br/>View file {$file} does not exist, <br/>{$file} => {$view}");
}
// changed by simeng in order to use smarty debug
foreach ( $vars as $key => $value ) {
$this->smarty->assign ( $key, $value );
}
// render or return
if ($return) {
ob_start ();
}
$this->smarty->display ( $view );
if ($return) {
$res = ob_get_contents ();
ob_end_clean ();
return $res;
}
}
}
PHP應用我把template_ext配置成了".html",這樣就ok了.我們來驗證一下吧.
PHP應用2.5,驗證
PHP應用在controller下面建一個home.php
PHP應用
class Home extends CI_Controller {
public function index() {
$data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');
$data['title'] = "恭喜你smarty安裝成功!";
$data['body'] = "歡迎使用smarty模板引";
$arr = array(1=>'zhang',2=>'xing',3=>'wang');
$data['myarray'] = $arr;
$this->load->view('index_2', $data);
}
}
PHP應用在views下面建一個index_2.html
PHP應用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src='<!--{$base_url}-->js/jquery.min.js' type='text/javascript' ></script>
<link href="<!--{$base_url}-->css/login.css" rel="stylesheet" type="text/css" />
<title>smarty安裝測試</title>
</head>
<body>
<h1>{#$title#}</h1>
<p>{#$body#}</p>
<ul>
{#foreach from=$myarray item=v#}
<li>{#$v#}</li>
{#/foreach#}
</ul>
</body>
</html>
PHP應用好了,可以試試你的成果了.
PHP應用三、yaf框架+smarty模板
PHP應用yaf是利用引導文件Bootstrap.php來加載smarty.
PHP應用3.1,使用Bootstrap
PHP應用在index.php中用
PHP應用引入Bootstrap.php文件
PHP應用3.2,在application/Bootstrap.php文件中導入smarty.
PHP應用
<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
public function _initSmarty(Yaf_Dispatcher $dispatcher) {
$smarty = new Smarty_Adapter(null, Yaf_Application::app()->getConfig()->smarty);
Yaf_Dispatcher::getInstance()->setView($smarty);
}
}
PHP應用3.3,添加Smarty_Adapter類
PHP應用將smarty解壓后放到application/library文件夾下,重命名為Smarty.在Smarty下新建Adapter.php,確保Smarty.class.php在Smarty/libs/下.Adapter.php內容:
PHP應用
<?php
Yaf_Loader::import( "Smarty/libs/Smarty.class.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatecompilerbase.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatelexer.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templateparser.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_compilebase.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_write_file.php");
class Smarty_Adapter implements Yaf_View_Interface
{
/**
* Smarty object
* @var Smarty
*/
public $_smarty;
/**
* Constructor
*
* @param string $tmplPath
* @param array $extraParams
* @return void
*/
public function __construct($tmplPath = null, $extraParams = array()) {
$this->_smarty = new Smarty;
if (null !== $tmplPath) {
$this->setScriptPath($tmplPath);
}
foreach ($extraParams as $key => $value) {
$this->_smarty->$key = $value;
}
}
/**
* Return the template engine object
*
* @return Smarty
*/
public function getEngine() {
return $this->_smarty;
}
/**
* Set the path to the templates
*
* @param string $path The directory to set as the path.
* @return void
*/
public function setScriptPath($path)
{
if (is_readable($path)) {
$this->_smarty->template_dir = $path;
return;
}
throw new Exception('Invalid path provided');
}
/**
* Retrieve the current template directory
*
* @return string
*/
public function getScriptPath()
{
return $this->_smarty->template_dir;
}
/**
* Alias for setScriptPath
*
* @param string $path
* @param string $prefix Unused
* @return void
*/
public function setBasePath($path, $prefix = 'Zend_View')
{
return $this->setScriptPath($path);
}
/**
* Alias for setScriptPath
*
* @param string $path
* @param string $prefix Unused
* @return void
*/
public function addBasePath($path, $prefix = 'Zend_View')
{
return $this->setScriptPath($path);
}
/**
* Assign a variable to the template
*
* @param string $key The variable name.
* @param mixed $val The variable value.
* @return void
*/
public function __set($key, $val)
{
$this->_smarty->assign($key, $val);
}
/**
* Allows testing with empty() and isset() to work
*
* @param string $key
* @return boolean
*/
public function __isset($key)
{
return (null !== $this->_smarty->get_template_vars($key));
}
/**
* Allows unset() on object properties to work
*
* @param string $key
* @return void
*/
public function __unset($key)
{
$this->_smarty->clear_assign($key);
}
/**
* Assign variables to the template
*
* Allows setting a specific key to the specified value, OR passing
* an array of key => value pairs to set en masse.
*
* @see __set()
* @param string|array $spec The assignment strategy to use (key or
* array of key => value pairs)
* @param mixed $value (Optional) If assigning a named variable,
* use this as the value.
* @return void
*/
public function assign($spec, $value = null) {
if (is_array($spec)) {
$this->_smarty->assign($spec);
return;
}
$this->_smarty->assign($spec, $value);
}
/**
* Clear all assigned variables
*
* Clears all variables assigned to Zend_View either via
* {@link assign()} or property overloading
* ({@link __get()}/{@link __set()}).
*
* @return void
*/
public function clearVars() {
$this->_smarty->clear_all_assign();
}
/**
* Processes a template and returns the output.
*
* @param string $name The template to process.
* @return string The output.
*/
public function render($name, $value = NULL) {
return $this->_smarty->fetch($name);
}
public function display($name, $value = NULL) {
echo $this->_smarty->fetch($name);
}
}
PHP應用3.4,smarty配置文件.
PHP應用再來看看我們的conf/application.ini文件
PHP應用
[common]
application.directory = APP_PATH "/application"
application.dispatcher.catchException = TRUE
application.view.ext="tpl"
[smarty : common]
;configures for smarty
smarty.left_delimiter = "{#"
smarty.right_delimiter = "#}"
smarty.template_dir = APP_PATH "/application/views/"
smarty.compile_dir = '/data1/www/cache/'
smarty.cache_dir = '/data1/www/cache/'
[product : smarty]
PHP應用3.5,驗證
PHP應用新建一個controller,添加辦法:
PHP應用
public function twoAction() {
$this->getView()->assign('content', 'hello World');
}
PHP應用新建一個模板two.tpl
PHP應用
<html>
<head>
<title>A Smarty Adapter Example</title>
</head>
<body>
{#$content#}
</body>
</html>
PHP應用希望本文所述對大家PHP程序設計有所贊助.
《PHP實戰:yii,CI,yaf框架+smarty模板使用方法》是否對您有啟發,歡迎查看更多與《PHP實戰:yii,CI,yaf框架+smarty模板使用方法》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/7958.html