yii,CI,yaf框架+smarty模板使用方法
本文实例讲述了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
'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',
)
)
其中batman是我已经在index.php定义好的别名。
Yii::setPathOfAlias('batman',dirname(__FILE__));
Yii::import("batman.protected.vendors.*");
define('APP_DIR',dirname(__FILE__).'/protected/');
1.3,在protected/extensions/下面新建SmartyViewRender.php
<?php
classSmartyViewRenderextendsCApplicationComponentimplementsIViewRenderer{
public$fileExtension='.html';
private$_smarty=null;
public$config=array();
publicfunctioninit(){
$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=newSmarty();
//configuresmarty
if(is_array($this->config)){
foreach($this->configas$key=>$value){
if($key{0}!='_'){//notsettingsemi-privateproperties
$this->_smarty->$key=$value;
}
}
}
Yii::registerAutoloader('smartyAutoload');
}
publicfunctionrenderFile($context,$file,$data,$return){
foreach($dataas$key=>$value)
$this->_smarty->assign($key,$value);
$return=$this->_smarty->fetch($file);
if($return)
return$return;
else
echo$return;
}
}
1.4,验证
新建一个HelloController.php
<?php
classHelloControllerextendsController{
publicfunctionactionWorld(){
$this->render('world',array('content'=>'helloworld'));
}
}
新建一个word.html
<body>
{#$content#}
</body>
二、CI框架+smarty模板
网上很多方法,将smarty作为一个普通的library,在使用的时候,controller代码类似于下面:
publicfunctionindex()
{
$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');
}
这种方法跟CI自带的使用模板的方法
$this->load->view();
不和谐,而且要一系列的
$this->smarty->assign();
语句,麻烦不说,还破坏了原本CI的简洁美,所以果断唾弃之。
那怎么保持CI加载view时的简洁美呢,答案就是覆盖Loader类的view()方法。好吧,let'sbegin。
2.1,条件:
到官网上现在CI框架和smarty模板。
2.2,确保CI已经能跑起来
将CI框架解压到网站跟目录下,先写一个不带smarty模板的controller输出“helloworld”。
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该文件,然后newMY_Loader(如果application/core/MY_Loader.php存在),或者是newLoader,赋值给$this->load。
在application/core下面新建一个MY_Loader.php文件
<?php
define('DS',DIRECTORY_SEPARATOR);
classMY_LoaderextendsCI_Loader{
public$smarty;
publicfunction__construct(){
parent::__construct();
requireAPPPATH.'third_party'.DS.'smarty'.DS.'smarty.class.php';
$this->smarty=newSmarty();
//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='#}';
}
publicfunctionview($view,$vars=array(),$return=FALSE)
{
//checkifviewfileexists
$view.=config_item('templates_ext');
$file=APPPATH.'views'.DS.$view;
if(!file_exists($file)||realpath($file)===false){
exit(__FILE__.''.__LINE__."<br/>Viewfile{$file}doesnotexist,<br/>{$file}=>{$view}");
}
//changedbysimenginordertousesmartydebug
foreach($varsas$key=>$value){
$this->smarty->assign($key,$value);
}
//renderorreturn
if($return){
ob_start();
}
$this->smarty->display($view);
if($return){
$res=ob_get_contents();
ob_end_clean();
return$res;
}
}
}
我把template_ext配置成了".html",这样就ok了。我们来验证一下吧。
2.5,验证
在controller下面建一个home.php
classHomeextendsCI_Controller{
publicfunctionindex(){
$data['todo_list']=array('CleanHouse','CallMom','RunErrands');
$data['title']="恭喜你smarty安装成功!";
$data['body']="欢迎使用smarty模板引";
$arr=array(1=>'zhang',2=>'xing',3=>'wang');
$data['myarray']=$arr;
$this->load->view('index_2',$data);
}
}
在views下面建一个index_2.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<scriptsrc='<!--{$base_url}-->js/jquery.min.js'type='text/javascript'></script>
<linkhref="<!--{$base_url}-->css/login.css"rel="stylesheet"type="text/css"/>
<title>smarty安装测试</title>
</head>
<body>
<h1>{#$title#}</h1>
<p>{#$body#}</p>
<ul>
{#foreachfrom=$myarrayitem=v#}
<li>{#$v#}</li>
{#/foreach#}
</ul>
</body>
</html>
好了,可以试试你的成果了。
三、yaf框架+smarty模板
yaf是利用引导文件Bootstrap.php来加载smarty。
3.1,使用Bootstrap
在index.php中用
$app->bootstrap()->run();
引入Bootstrap.php文件
3.2,在application/Bootstrap.php文件中导入smarty。
<?php
classBootstrapextendsYaf_Bootstrap_Abstract{
publicfunction_initSmarty(Yaf_Dispatcher$dispatcher){
$smarty=newSmarty_Adapter(null,Yaf_Application::app()->getConfig()->smarty);
Yaf_Dispatcher::getInstance()->setView($smarty);
}
}
3.3,添加Smarty_Adapter类
将smarty解压后放到application/library文件夹下,重命名为Smarty。在Smarty下新建Adapter.php,确保Smarty.class.php在Smarty/libs/下。Adapter.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");
classSmarty_AdapterimplementsYaf_View_Interface
{
/**
*Smartyobject
*@varSmarty
*/
public$_smarty;
/**
*Constructor
*
*@paramstring$tmplPath
*@paramarray$extraParams
*@returnvoid
*/
publicfunction__construct($tmplPath=null,$extraParams=array()){
$this->_smarty=newSmarty;
if(null!==$tmplPath){
$this->setScriptPath($tmplPath);
}
foreach($extraParamsas$key=>$value){
$this->_smarty->$key=$value;
}
}
/**
*Returnthetemplateengineobject
*
*@returnSmarty
*/
publicfunctiongetEngine(){
return$this->_smarty;
}
/**
*Setthepathtothetemplates
*
*@paramstring$pathThedirectorytosetasthepath.
*@returnvoid
*/
publicfunctionsetScriptPath($path)
{
if(is_readable($path)){
$this->_smarty->template_dir=$path;
return;
}
thrownewException('Invalidpathprovided');
}
/**
*Retrievethecurrenttemplatedirectory
*
*@returnstring
*/
publicfunctiongetScriptPath()
{
return$this->_smarty->template_dir;
}
/**
*AliasforsetScriptPath
*
*@paramstring$path
*@paramstring$prefixUnused
*@returnvoid
*/
publicfunctionsetBasePath($path,$prefix='Zend_View')
{
return$this->setScriptPath($path);
}
/**
*AliasforsetScriptPath
*
*@paramstring$path
*@paramstring$prefixUnused
*@returnvoid
*/
publicfunctionaddBasePath($path,$prefix='Zend_View')
{
return$this->setScriptPath($path);
}
/**
*Assignavariabletothetemplate
*
*@paramstring$keyThevariablename.
*@parammixed$valThevariablevalue.
*@returnvoid
*/
publicfunction__set($key,$val)
{
$this->_smarty->assign($key,$val);
}
/**
*Allowstestingwithempty()andisset()towork
*
*@paramstring$key
*@returnboolean
*/
publicfunction__isset($key)
{
return(null!==$this->_smarty->get_template_vars($key));
}
/**
*Allowsunset()onobjectpropertiestowork
*
*@paramstring$key
*@returnvoid
*/
publicfunction__unset($key)
{
$this->_smarty->clear_assign($key);
}
/**
*Assignvariablestothetemplate
*
*Allowssettingaspecifickeytothespecifiedvalue,ORpassing
*anarrayofkey=>valuepairstosetenmasse.
*
*@see__set()
*@paramstring|array$specTheassignmentstrategytouse(keyor
*arrayofkey=>valuepairs)
*@parammixed$value(Optional)Ifassigninganamedvariable,
*usethisasthevalue.
*@returnvoid
*/
publicfunctionassign($spec,$value=null){
if(is_array($spec)){
$this->_smarty->assign($spec);
return;
}
$this->_smarty->assign($spec,$value);
}
/**
*Clearallassignedvariables
*
*ClearsallvariablesassignedtoZend_Vieweithervia
*{@linkassign()}orpropertyoverloading
*({@link__get()}/{@link__set()}).
*
*@returnvoid
*/
publicfunctionclearVars(){
$this->_smarty->clear_all_assign();
}
/**
*Processesatemplateandreturnstheoutput.
*
*@paramstring$nameThetemplatetoprocess.
*@returnstringTheoutput.
*/
publicfunctionrender($name,$value=NULL){
return$this->_smarty->fetch($name);
}
publicfunctiondisplay($name,$value=NULL){
echo$this->_smarty->fetch($name);
}
}
3.4,smarty配置文件。
再来看看我们的conf/application.ini文件
[common]
application.directory=APP_PATH"/application"
application.dispatcher.catchException=TRUE
application.view.ext="tpl"
[smarty:common]
;configuresforsmarty
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]
3.5,验证
新建一个controller,添加方法:
publicfunctiontwoAction(){
$this->getView()->assign('content','helloWorld');
}
新建一个模板two.tpl
<html>
<head>
<title>ASmartyAdapterExample</title>
</head>
<body>
{#$content#}
</body>
</html>
希望本文所述对大家PHP程序设计有所帮助。