Zend Framework教程之视图组件Zend_View用法详解
本文实例讲述了ZendFramework教程之视图组件Zend_View用法。分享给大家供大家参考,具体如下:
Zend_View是ZendFramework的视图组件,MVC中的视图层。Zend_View也是应用的直接对用户展示的页面。这里介绍一下Zend_View的实现类,以及如何和Controller结合在一起的。
View的实现
Zend_View的实现主要是通过如下目录的类实现:
root@coder-671T-M:/library/Zend#tree|grepView.php
│ └──View/
├──View.php
root@coder-671T-M:/library/Zend/View#tree
.
├──Abstract.php
├──Exception.php
├──Helper
│ ├──Abstract.php
│ ├──Action.php
│ ├──BaseUrl.php
│ ├──Currency.php
│ ├──Cycle.php
│ ├──DeclareVars.php
│ ├──Doctype.php
│ ├──Fieldset.php
│ ├──FormButton.php
│ ├──FormCheckbox.php
│ ├──FormElement.php
│ ├──FormErrors.php
│ ├──FormFile.php
│ ├──FormHidden.php
│ ├──FormImage.php
│ ├──FormLabel.php
│ ├──FormMultiCheckbox.php
│ ├──FormNote.php
│ ├──FormPassword.php
│ ├──Form.php
│ ├──FormRadio.php
│ ├──FormReset.php
│ ├──FormSelect.php
│ ├──FormSubmit.php
│ ├──FormTextarea.php
│ ├──FormText.php
│ ├──Gravatar.php
│ ├──HeadLink.php
│ ├──HeadMeta.php
│ ├──HeadScript.php
│ ├──HeadStyle.php
│ ├──HeadTitle.php
│ ├──HtmlElement.php
│ ├──HtmlFlash.php
│ ├──HtmlList.php
│ ├──HtmlObject.php
│ ├──HtmlPage.php
│ ├──HtmlQuicktime.php
│ ├──InlineScript.php
│ ├──Interface.php
│ ├──Json.php
│ ├──Layout.php
│ ├──Navigation
│ │ ├──Breadcrumbs.php
│ │ ├──HelperAbstract.php
│ │ ├──Helper.php
│ │ ├──Links.php
│ │ ├──Menu.php
│ │ └──Sitemap.php
│ ├──Navigation.php
│ ├──PaginationControl.php
│ ├──Partial
│ │ └──Exception.php
│ ├──PartialLoop.php
│ ├──Partial.php
│ ├──Placeholder
│ │ ├──Container
│ │ │ ├──Abstract.php
│ │ │ ├──Exception.php
│ │ │ └──Standalone.php
│ │ ├──Container.php
│ │ ├──Registry
│ │ │ └──Exception.php
│ │ └──Registry.php
│ ├──Placeholder.php
│ ├──RenderToPlaceholder.php
│ ├──ServerUrl.php
│ ├──TinySrc.php
│ ├──Translate.php
│ ├──Url.php
│ └──UserAgent.php
├──Interface.php
└──Stream.php
6directories,70files
Zend_View和Zend_Controller的整合
主要在Zend_Controller_Action类中,
/** *InitializeViewobject * *Initializes{@link$view}ifnototherwiseaZend_View_Interface. * *If{@link$view}isnototherwiseset,instantiatesanewZend_View *object,usingthe'views'subdirectoryatthesamelevelasthe *controllerdirectoryforthecurrentmoduleasthebasedirectory. *Itusesthistosetthefollowing: *-scriptpath=views/scripts/ *-helperpath=views/helpers/ *-filterpath=views/filters/ * *@returnZend_View_Interface *@throwsZend_Controller_Exceptionifbaseviewdirectorydoesnotexist */ publicfunctioninitView() { if(!$this->getInvokeArg('noViewRenderer')&&$this->_helper->hasHelper('viewRenderer')){ return$this->view; } require_once'Zend/View/Interface.php'; if(isset($this->view)&&($this->viewinstanceofZend_View_Interface)){ return$this->view; } $request=$this->getRequest(); $module=$request->getModuleName(); $dirs=$this->getFrontController()->getControllerDirectory(); if(empty($module)||!isset($dirs[$module])){ $module=$this->getFrontController()->getDispatcher()->getDefaultModule(); } $baseDir=dirname($dirs[$module]).DIRECTORY_SEPARATOR.'views'; if(!file_exists($baseDir)||!is_dir($baseDir)){ require_once'Zend/Controller/Exception.php'; thrownewZend_Controller_Exception('Missingbaseviewdirectory("'.$baseDir.'")'); } require_once'Zend/View.php'; $this->view=newZend_View(array('basePath'=>$baseDir)); return$this->view; } /** *Renderaview * *Rendersaview.Bydefault,viewsarefoundintheviewscriptpathas *<controller>/<action>.phtml.Youmaychangethescriptsuffixby *resetting{@link$viewSuffix}.Youmayomitthecontrollerdirectory *prefixbyspecifyingbooleantruefor$noController. * *Bydefault,therenderedcontentsareappendedtotheresponse.Youmay *specifythenamedbodycontentsegmenttosetbyspecifyinga$name. * *@seeZend_Controller_Response_Abstract::appendBody() *@paramstring|null$actionDefaultstoactionregisteredinrequestobject *@paramstring|null$nameResponseobjectnamedpathsegmenttouse;defaultstonull *@parambool$noControllerDefaultstofalse;i.e.usecontrollernameassubdirinwhichtosearchforviewscript *@returnvoid */ publicfunctionrender($action=null,$name=null,$noController=false) { if(!$this->getInvokeArg('noViewRenderer')&&$this->_helper->hasHelper('viewRenderer')){ return$this->_helper->viewRenderer->render($action,$name,$noController); } $view=$this->initView(); $script=$this->getViewScript($action,$noController); $this->getResponse()->appendBody( $view->render($script), $name ); } /** *Renderagivenviewscript * *Similarto{@linkrender()},thismethodrendersaviewscript.Unlikerender(), *however,itdoesnotautodeterminetheviewscriptvia{@linkgetViewScript()}, *butinsteadrendersthescriptpassedtoit.Usethisifyouknowthe *exactviewscriptnameandpathyouwishtouse,orifusingpathsthatdonot *conformtothespecdefinedwithgetViewScript(). * *Bydefault,therenderedcontentsareappendedtotheresponse.Youmay *specifythenamedbodycontentsegmenttosetbyspecifyinga$name. * *@paramstring$script *@paramstring$name *@returnvoid */ publicfunctionrenderScript($script,$name=null) { if(!$this->getInvokeArg('noViewRenderer')&&$this->_helper->hasHelper('viewRenderer')){ return$this->_helper->viewRenderer->renderScript($script,$name); } $view=$this->initView(); $this->getResponse()->appendBody( $view->render($script), $name ); }
Zend_View.php类
<?php /** *ZendFramework * *LICENSE * *ThissourcefileissubjecttothenewBSDlicensethatisbundled *withthispackageinthefileLICENSE.txt. *Itisalsoavailablethroughtheworld-wide-webatthisURL: *http://framework.zend.com/license/new-bsd *Ifyoudidnotreceiveacopyofthelicenseandareunableto *obtainitthroughtheworld-wide-web,pleasesendanemail *tolicense@zend.comsowecansendyouacopyimmediately. * *@categoryZend *@packageZend_View *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense *@version$Id:View.php237752011-03-0117:25:24Zralph$ */ /** *Abstractmasterclassforextension. */ require_once'Zend/View/Abstract.php'; /** *Concreteclassforhandlingviewscripts. * *@categoryZend *@packageZend_View *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense */ classZend_ViewextendsZend_View_Abstract { /** *Whetherornottousestreamstomimicshorttags *@varbool */ private$_useViewStream=false; /** *Whetherornottousestreamwrapperifshort_open_tagisfalse *@varbool */ private$_useStreamWrapper=false; /** *Constructor * *RegisterZend_View_Streamstreamwrapperifshorttagsaredisabled. * *@paramarray$config *@returnvoid */ publicfunction__construct($config=array()) { $this->_useViewStream=(bool)ini_get('short_open_tag')?false:true; if($this->_useViewStream){ if(!in_array('zend.view',stream_get_wrappers())){ require_once'Zend/View/Stream.php'; stream_wrapper_register('zend.view','Zend_View_Stream'); } } if(array_key_exists('useStreamWrapper',$config)){ $this->setUseStreamWrapper($config['useStreamWrapper']); } parent::__construct($config); } /** *Setflagindicatingifstreamwrappershouldbeusedifshort_open_tagisoff * *@parambool$flag *@returnZend_View */ publicfunctionsetUseStreamWrapper($flag) { $this->_useStreamWrapper=(bool)$flag; return$this; } /** *Shouldthestreamwrapperbeusedifshort_open_tagisoff? * *@returnbool */ publicfunctionuseStreamWrapper() { return$this->_useStreamWrapper; } /** *Includestheviewscriptinascopewithonlypublic$thisvariables. * *@paramstringTheviewscripttoexecute. */ protectedfunction_run() { if($this->_useViewStream&&$this->useStreamWrapper()){ include'zend.view://'.func_get_arg(0); }else{ includefunc_get_arg(0); } } }
默认情况会自动通过Controller会通过render方法来实例化Zend_View,然后rener到对应的视图文件中。当然可以自己实例化Zend_View,然后使用。
action默认指向的文件是和action的名称相同,如果要指定视图文件,可以通过$this->render的相关方法指定.也可以通过addScriptPath和setScriptPath设置视图文件的目录。
例如
$view=newZend_View(); $view->addScriptPath('/www/app/myviews'); $view->addScriptPath('/www/app/viewscomm'); //如果调用$view->render('example.php'),Zend_View将 //首先查找"/www/app/myviews/example.php",找不到再找"/www/app/viewscomm/example.php",如果还找不到,最后查找当前目录下/的"example.php".
Zend_View的常用方法
publicfunction__construct($config=array())
构造函数参数
例如
array( 'escape'=>array(), 'encoding'=>array(), );
常见key:
escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、helperPathPrefix、filterPath、filterPathPrefix、filter
publicfunctiongetEngine()Returnthetemplateengineobject
publicfunctioninit()初始化函数
/** *Givenabasepath,setsthescript,helper,andfilterpathsrelativetoit * *Assumesadirectorystructureof: *<code> *basePath/ *scripts/ *helpers/ *filters/ *</code> * *@paramstring$path *@paramstring$prefixPrefixtouseforhelperandfilterpaths *@returnZend_View_Abstract */ publicfunctionsetBasePath($path,$classPrefix='Zend_View') /** *Givenabasepath,addscript,helper,andfilterpathsrelativetoit * *Assumesadirectorystructureof: *<code> *basePath/ *scripts/ *helpers/ *filters/ *</code> * *@paramstring$path *@paramstring$prefixPrefixtouseforhelperandfilterpaths *@returnZend_View_Abstract */ publicfunctionaddBasePath($path,$classPrefix='Zend_View') publicfunctionaddScriptPath($path)AddstothestackofviewscriptpathsinLIFOorder. publicfunctionsetScriptPath($path)Resetsthestackofviewscriptpaths. publicfunctiongetScriptPath($name)Returnfullpathtoaviewscriptspecifiedby$name publicfunctiongetScriptPaths()Returnsanarrayofallcurrentlysetscriptpaths publicfunctionaddHelperPath($path,$classPrefix='Zend_View_Helper_')AddstothestackofhelperpathsinLIFOorder. publicfunctionsetHelperPath($path,$classPrefix='Zend_View_Helper_')Resetsthestackofhelperpaths. publicfunctiongetHelperPath($name)Getfullpathtoahelperclassfilespecifiedby$name publicfunctiongetHelperPaths()Returnsanarrayofallcurrentlysethelperpaths publicfunctiongetHelper($name)Getahelperbyname publicfunctiongetHelpers()Getarrayofallactivehelpers publicfunctiongetAllPaths()Returnassociativearrayofpathtypes=>paths publicfunctionsetEscape($spec) /** *Assignsvariablestotheviewscriptviadifferingstrategies. * *Zend_View::assign('name',$value)assignsavariablecalled'name' *withthecorresponding$value. * *Zend_View::assign($array)assignsthearraykeysasvariable *names(withthecorrespondingarrayvalues). * *@see__set() *@paramstring|arrayTheassignmentstrategytouse. *@parammixed(Optional)Ifassigninganamedvariable,usethis *asthevalue. *@returnZend_View_AbstractFluentinterface *@throwsZend_View_Exceptionif$specisneitherastringnoranarray, *orifanattempttosetaprivateorprotectedmemberisdetected */ publicfunctionassign($spec,$value=null)
在controller的action可以通过assign传递参数到视图脚本。
例如
$this->view->assign('roles',$roles); $this->view->assign('num',$num); $this->view->assign('a',$a);
或者也可以用
$this->view->roles=$roles; $this->view->a=$a; publicfunctionrender($name)Processesaviewscriptandreturnstheoutput. publicfunctionescape($var):Escapesavalueforoutputinaviewscript. publicfunctionsetEncoding($encoding)Setencodingtousewithhtmlentities()andhtmlspecialchars() publicfunctiongetEncoding():Returncurrentescapeencoding
视图脚本文件中的常见用法:
获取传递过来的值
$this->roles
使用一些常见的助手方法:
$this->baseUrl(); $this->url(); $this->paginationControl(); $this->partial()
视图常见用法举例
在bootstrap初始化view或者controller的init文件中
/** *Initializethecommonviewhelper */ protectedfunction_initViewHelper() { $boot=$this->bootstrap('View'); $view=$boot->getResource('View'); $view->setHelperPath('Sql/View/Helper','Sql_View_Helper'); }
action中
/** * *@returnvoid */ publicfunctionlistAction() { $this->view->assign('data',$data); }
视图文件
list.phtml
<?phpforeach($this->dataas$item):?> <trstyle="height:19px;"> <tdclass="datagrid-cell"><?phpecho($item->item1);?></td> </tr> <?phpendforeach;?>
更多关于zend相关内容感兴趣的读者可查看本站专题:《ZendFrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。