Zend Framework教程之Zend_Layout布局助手详解
本文实例讲述了ZendFramework教程之Zend_Layout布局助手。分享给大家供大家参考,具体如下:
一、作用
布局的作用和模版的作用类似。可以认为是把网站通用、公共的部分拿出来作为通用的页面框架。例如一个基本的web页面,可能页面的头和尾都是一样,不一样的可能只是内容body部分不一样,可以把公共的部分做成模版。不仅可以提高开发效率,也为后期的维护带来方便。
二、使用
这里举一个简单的例子。
首先用zendstudio创建一个基本的zendframework项目:layout_demo1
结构大概如下“
├─.settings
├─application
│ ├─configs
│ ├─controllers
│ ├─models
│ └─views
│ ├─helpers
│ └─scripts
│ ├─error
│ └─index
├─docs
├─library
├─public
└─tests
├─application
│ └─controllers
└─library
1.加入layout功能:
应用配置文件/layout_demo2/application/configs/application.ini,加入如下配置
resources.frontController.controllerDirectory=APPLICATION_PATH"/controllers" resources.frontController.params.displayExceptions=0 resources.layout.layoutPath=APPLICATION_PATH"/layouts/scripts/" [staging:production]
2.相应的目录和布局模版文件/layout_demo2/application/layouts/scripts/layout.phtml
├─application
│ ├─configs
│ ├─controllers
│ ├─layouts
│ │ └─scripts
│ ├─models
│ └─views
layout.html类似如下:
<!doctypehtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"> <title>myapp</title> <body> <divid="header"> header </div> <divid="content"> <?phpecho$this->layout()->content;?> </div> <divid="footer"> header </div> </body> </html>
这里的
<?phpecho$this->layout()->content;?>
是比较重要的。表示此处为布局的内容,也就是会动态变化的地方。
这样,运行一下程序
www.localzend.com/layout_demo1/public/
生成的html源码如下
<!doctypehtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"> <title>myapp</title> <body> <divid="header"> header </div> <divid="content"> <style> a:link, a:visited { color:#0398CA; } span#zf-name { color:#91BE3F; } div#welcome { color:#FFFFFF; background-image:url(http://framework.zend.com/images/bkg_header.jpg); width:600px; height:400px; border:2pxsolid#444444; overflow:hidden; text-align:center; } div#more-information { background-image:url(http://framework.zend.com/images/bkg_body-bottom.gif); height:100%; } </style> <divid="welcome"> <h1>Welcometothe<spanid="zf-name">ZendFramework!</span></h1> <h3>Thisisyourproject'smainpage</h3> <divid="more-information"> <p><imgsrc="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png"/></p> <p> HelpfulLinks:<br/> <ahref="http://framework.zend.com/">ZendFrameworkWebsite</a>| <ahref="http://framework.zend.com/manual/en/">ZendFrameworkManual</a> </p> </div> </div></div> <divid="footer"> header </div> </body> </html>
中间部分就是/layout_demo1/application/views/scripts/index/index.phtml的内容。
注入:可以通过zf的命令工具自动生成layout的配置和文件。
命令如下:
zfenablelayout
可以参考命令行章节
三、配置
1.自定义存放位置和名称可以通过application.ini配置文件配置布局文件的存放位置以及布局文件的名称,例如:
resources.layout.layoutPath=APPLICATION_PATH"/mylayouts/scripts" resources.layout.layout="mylayout"
2.在action中使用layout对象
可以通过
$layout=$this->_helper->layout();
或者
$helper=$this->_helper->getHelper('Layout'); $layout=$helper->getLayoutInstance();
获取布局对象。
可以通过如下方式禁用当前action使用布局模式
$layout->disableLayout();
可以通过
$layout->setLayout('other');
来设置使用另一个布局文件
可以通过来传递赋值
$layout->assign('headertitle','apptitle'); $layout->somekey="value"
3.其它获取layout对象的方法
(1)
$layout=Zend_Layout::getMvcInstance();
(2)
$layout=$bootstrap->getResource('Layout');
四、其它用法,实现原理
具体其它的使用方法可以参考
Zend_Layout_Controller_Action_Helper_Layout类,
Zend_Layout_Controller_Plugin_Layout类
Zend_View_Helper_Layout类
不言自明。
<?php /**Zend_Controller_Action_Helper_Abstract*/ require_once'Zend/Controller/Action/Helper/Abstract.php'; /** *HelperforinteractingwithZend_Layoutobjects * *@usesZend_Controller_Action_Helper_Abstract *@categoryZend *@packageZend_Controller *@subpackageZend_Controller_Action *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense */ classZend_Layout_Controller_Action_Helper_LayoutextendsZend_Controller_Action_Helper_Abstract { /** *@varZend_Controller_Front */ protected$_frontController; /** *@varZend_Layout */ protected$_layout; /** *@varbool */ protected$_isActionControllerSuccessful=false; /** *Constructor * *@paramZend_Layout$layout *@returnvoid */ publicfunction__construct(Zend_Layout$layout=null) { if(null!==$layout){ $this->setLayoutInstance($layout); }else{ /** *@seeZend_Layout */ require_once'Zend/Layout.php'; $layout=Zend_Layout::getMvcInstance(); } if(null!==$layout){ $pluginClass=$layout->getPluginClass(); $front=$this->getFrontController(); if($front->hasPlugin($pluginClass)){ $plugin=$front->getPlugin($pluginClass); $plugin->setLayoutActionHelper($this); } } } publicfunctioninit() { $this->_isActionControllerSuccessful=false; } /** *Getfrontcontrollerinstance * *@returnZend_Controller_Front */ publicfunctiongetFrontController() { if(null===$this->_frontController){ /** *@seeZend_Controller_Front */ require_once'Zend/Controller/Front.php'; $this->_frontController=Zend_Controller_Front::getInstance(); } return$this->_frontController; } /** *Getlayoutobject * *@returnZend_Layout */ publicfunctiongetLayoutInstance() { if(null===$this->_layout){ /** *@seeZend_Layout */ require_once'Zend/Layout.php'; if(null===($this->_layout=Zend_Layout::getMvcInstance())){ $this->_layout=newZend_Layout(); } } return$this->_layout; } /** *Setlayoutobject * *@paramZend_Layout$layout *@returnZend_Layout_Controller_Action_Helper_Layout */ publicfunctionsetLayoutInstance(Zend_Layout$layout) { $this->_layout=$layout; return$this; } /** *MarkActionController(accordingtothisplugin)asRunningsuccessfully * *@returnZend_Layout_Controller_Action_Helper_Layout */ publicfunctionpostDispatch() { $this->_isActionControllerSuccessful=true; return$this; } /** *Didthepreviousactionsuccessfullycomplete? * *@returnbool */ publicfunctionisActionControllerSuccessful() { return$this->_isActionControllerSuccessful; } /** *Strategypattern;callobjectasmethod * *Returnslayoutobject * *@returnZend_Layout */ publicfunctiondirect() { return$this->getLayoutInstance(); } /** *Proxymethodcallstolayoutobject * *@paramstring$method *@paramarray$args *@returnmixed */ publicfunction__call($method,$args) { $layout=$this->getLayoutInstance(); if(method_exists($layout,$method)){ returncall_user_func_array(array($layout,$method),$args); } require_once'Zend/Layout/Exception.php'; thrownewZend_Layout_Exception(sprintf("Invalidmethod'%s'calledonlayoutactionhelper",$method)); } }
<?php /**Zend_Controller_Plugin_Abstract*/ require_once'Zend/Controller/Plugin/Abstract.php'; /** *Renderlayouts * *@usesZend_Controller_Plugin_Abstract *@categoryZend *@packageZend_Controller *@subpackagePlugins *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense *@version$Id:Layout.php237752011-03-0117:25:24Zralph$ */ classZend_Layout_Controller_Plugin_LayoutextendsZend_Controller_Plugin_Abstract { protected$_layoutActionHelper=null; /** *@varZend_Layout */ protected$_layout; /** *Constructor * *@paramZend_Layout$layout *@returnvoid */ publicfunction__construct(Zend_Layout$layout=null) { if(null!==$layout){ $this->setLayout($layout); } } /** *Retrievelayoutobject * *@returnZend_Layout */ publicfunctiongetLayout() { return$this->_layout; } /** *Setlayoutobject * *@paramZend_Layout$layout *@returnZend_Layout_Controller_Plugin_Layout */ publicfunctionsetLayout(Zend_Layout$layout) { $this->_layout=$layout; return$this; } /** *Setlayoutactionhelper * *@paramZend_Layout_Controller_Action_Helper_Layout$layoutActionHelper *@returnZend_Layout_Controller_Plugin_Layout */ publicfunctionsetLayoutActionHelper(Zend_Layout_Controller_Action_Helper_Layout$layoutActionHelper) { $this->_layoutActionHelper=$layoutActionHelper; return$this; } /** *Retrievelayoutactionhelper * *@returnZend_Layout_Controller_Action_Helper_Layout */ publicfunctiongetLayoutActionHelper() { return$this->_layoutActionHelper; } /** *postDispatch()pluginhook--renderlayout * *@paramZend_Controller_Request_Abstract$request *@returnvoid */ publicfunctionpostDispatch(Zend_Controller_Request_Abstract$request) { $layout=$this->getLayout(); $helper=$this->getLayoutActionHelper(); //Returnearlyifforwarddetected if(!$request->isDispatched() ||$this->getResponse()->isRedirect() ||($layout->getMvcSuccessfulActionOnly() &&(!empty($helper)&&!$helper->isActionControllerSuccessful()))) { return; } //Returnearlyiflayouthasbeendisabled if(!$layout->isEnabled()){ return; } $response=$this->getResponse(); $content=$response->getBody(true); $contentKey=$layout->getContentKey(); if(isset($content['default'])){ $content[$contentKey]=$content['default']; } if('default'!=$contentKey){ unset($content['default']); } $layout->assign($content); $fullContent=null; $obStartLevel=ob_get_level(); try{ $fullContent=$layout->render(); $response->setBody($fullContent); }catch(Exception$e){ while(ob_get_level()>$obStartLevel){ $fullContent.=ob_get_clean(); } $request->setParam('layoutFullContent',$fullContent); $request->setParam('layoutContent',$layout->content); $response->setBody(null); throw$e; } } }
<?php /**Zend_View_Helper_Abstract.php*/ require_once'Zend/View/Helper/Abstract.php'; /** *Viewhelperforretrievinglayoutobject * *@packageZend_View *@subpackageHelper *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense */ classZend_View_Helper_LayoutextendsZend_View_Helper_Abstract { /**@varZend_Layout*/ protected$_layout; /** *Getlayoutobject * *@returnZend_Layout */ publicfunctiongetLayout() { if(null===$this->_layout){ require_once'Zend/Layout.php'; $this->_layout=Zend_Layout::getMvcInstance(); if(null===$this->_layout){ //Implicitlycreateslayoutobject $this->_layout=newZend_Layout(); } } return$this->_layout; } /** *Setlayoutobject * *@paramZend_Layout$layout *@returnZend_Layout_Controller_Action_Helper_Layout */ publicfunctionsetLayout(Zend_Layout$layout) { $this->_layout=$layout; return$this; } /** *Returnlayoutobject * *Usage:$this->layout()->setLayout('alternate'); * *@returnZend_Layout */ publicfunctionlayout() { return$this->getLayout(); } }
更多关于zend相关内容感兴趣的读者可查看本站专题:《ZendFrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。