Zend Framework教程之Zend_Helpers动作助手ViewRenderer用法详解
本文实例讲述了zend framework教程之zend_helpers动作助手viewrenderer用法。分享给大家供大家参考,具体如下:
mvc结构中视图层和控制器的解耦,以及渲染。往往是重复或者冗余的工作。如果一个完善的框架,对mvc的使用,必定会对这些操作进行合理的设计。让开发者更专注内容而不是控制逻辑结构本身。在zendframework中,主要是通过动作助手viewrenderer来完成这个操作的。viewrenderer 自动的完成在控制器内建立视图对象并渲染视图的过程;
viewrenderer
介绍
视图解析(viewrenderer)助手为实现下列目标设计:
不需要在控制器内创建视图对象实例;视图对象将在控制器内自动注册。
根据当前的模块自动地设置视图脚本、助手、过滤器路径。指派当前的模块名为助手和过滤器类的类名前缀。
为所有分发的控制器和动作创建全局有效的视图对象。
允许开发人员为所有控制器设置默认的视图解析选项。
加入无需干预自动解析试图脚本的功能。
允许开发人员为视图基路径和视图脚本路径创建自己的规范。
note: 如果手动执行_forward()、redirect、或者render时,不会发生自动解析。因为执行这些动作时,等于告诉viewrenderer,你要自己确定输出结果。
note: viewrenderer助手默认启用。
你可以通过前端控制器的noviewrenderer方法、设定参数($front->setparam('noviewrenderer', true))或者从助手经纪人栈(helper broker stack)中移除助手(zend_controller_action_helperbroker::removehelper('viewrenderer'))等方式禁用该助手。
如希望在分发前端控制器前修改viewrenderer设定,可采用下面的两种方法:
创建实例并注册自己的viewrenderer对象,然后传入到助手经纪人。
$viewrenderer = new zend_controller_action_helper_viewrenderer(); $viewrenderer->setview($view) ->setviewsuffix('php'); zend_controller_action_helperbroker::addhelper($viewrenderer);
通过助手经纪人即时的初始化并/或获取viewrenderer对象。
$viewrenderer = zend_controller_action_helperbroker::getstatichelper('viewrenderer'); $viewrenderer->setview($view) ->setviewsuffix('php');
api
大多数使用中,只需要简单的创建 viewrenderer对象,然后传入到动作助手经纪人。创建实例并注册的最简单方式是使用助手经纪人的getstatichelper()方法:
zend_controller_action_helperbroker::getstatichelper('viewrenderer');
动作控制器第一次实例化时,会触发viewrenderer创建一个视图对象。动作控制器每次实例化都会调用viewrenderer的init()方法,设定动作控制器的视图属性,并以相对于当前模块的路径为参数调用addscriptpath()方法;调用时带有以当前模块命名的类前缀参数,该参数对为该模块定义的所有助手和过滤器类都有效。(this will be called with a class prefix named after the current module, effectively namespacing all helper and filter classes you define for the module. )
每次执行postdispatch()方法,它将为当前动作执行render()方法。
例如这个类:
// a controller class, foo module: class foo_barcontroller extends zend_controller_action { // render bar/index.phtml by default; no action required public function indexaction() { } // render bar/populate.phtml with variable 'foo' set to 'bar'. // since view object defined at predispatch(), it's already available. public function populateaction() { $this->view->foo = 'bar'; } } ... // in one of your view scripts: $this->foo(); // call foo_view_helper_foo::foo()
viewrenderer也定义了大量的访问器用来设定和获取视图选项。
setview($view)可以为viewrenderer设定视图对象。以公共类属性$view获取设定值。
setneverrender($flag = true)可以全局的启用或禁用自动解析,也就是对所有控制器都有效。如果设定为true,在所有控制器器内,postdispatch()将不会自动调用render()。getneverrender()返回当前的设定值。
setnorender($flag = true) 用来启用或禁用自动解析,如果设置为true,在当前控制器内,postdispatch()不会调用render()方法。这个设定在predispatch()每次执行时会被重置。getnorender()返回当前的设定值。
setnocontroller($flag = true)通知render()不要再到以控制器命名的子目录中寻找视图脚本。getnocontroller()返回当前值。
setnevercontroller($flag = true)与setnocontroller($flag = true)相似,但是其在全局范围内有效——也就是说,它不会在每次分发动作时重置。getnevercontroller()返回当前值。
setscriptaction($name)用来指定解析的视图脚本。$name是脚本的名字去掉后缀(不带控制器子目录,除非nocontroller已开启)。如果没有指定,它将寻找以请求对象中的动作命名的视图脚本。getscriptaction()返回当前值。
setresponsesegment($name)用来指定解析到响应对象中的哪个命名片段。如果没有指定,解析到默认片断。getresponsesegment()返回当前值。
initview($path, $prefix, $options)可以指定视图的基路径,为助手和过滤器脚本设置类前缀,设定viewrenderer选项。可以传入以下任意的标志:neverrender,norender,nocontroller, scriptaction,和responsesegment。
setrender($action = null, $name = null, $nocontroller = false)可以一次设定scriptaction、responsesegment和nocontroller。 direct()是它的别名,使得控制器中可以方便的调用。
// render 'foo' instead of current action script $this->_helper->viewrenderer('foo'); // render form.phtml to the 'html' response segment, without using a // controller view script subdirectory: $this->_helper->viewrenderer('form', 'html', true);
note: setrender() 和 direct()并不会实际解析视图脚本,而是提示postdispatch()和postdispatch()解析视图。
构造函数允许可选的传入参数视图对象和viewrenderer选项,接受与initview()一样的标志(flags):
$view = new zend_view(array('encoding' => 'utf-8')); $options = array('nocontroller' => true, 'neverrender' => true); $viewrenderer = new zend_controller_action_helper_viewrenderer($view, $options);
还有几个额外的方法用来定制路径规则,供确定视图基路径来增加视图对象,确定视图脚本路径查找并解析视图脚本时使用。这些方法每个都带有下面一个或更多的占位符(placehodlers)。
:moduledir 引用当前模块的基目录(常规的是模块的控制器目录的父目录)。
:module 引用当前的模块名。
:controller 引用当前的控制器名。
:action引用当前的模块名。
:suffix 引用当前的视图脚本后缀(可以通过setviewsuffix()来设置)。
控制器路径规则有关的方法:
setviewbasepathspec($spec)可以改变确定加入到视图对象的基路径的路径规则。默认规则是:moduledir/views。任何时候都可以使用getviewbasepathspec()获取当前的规则。
setviewscriptpathspec($spec)允许改变确定到达单独的视图脚本路径(去除试图脚本基路径)的路径规则。默认的路径规则是 :controller/:action.:suffix。任何时候都可以通过getviewscriptpathspec()获取当前规则。
setviewscriptpathnocontrollerspec($spec)允许改变 nocontroller有效时确定到达单独的视图脚本路径(去除试图脚本基路径)的路径规则。默认的规则是:action.:suffix,任何时候都可以通过getviewscriptpathnocontrollerspec()获取当前规则。
为在路径规范之上精心设计的控制,可以使用zend_filter_inflector。深入地,视图解析器(viewrenderer)已经使用inflector来执行路径映射。为和inflector互动 - 或者设置你自己的或者修改缺省的inflector,下面的方法可以被使用:
getinflector() 将获取inflector。如果在视图解析器中不存在, 它用缺省的规则创建一个。
缺省地,它用静态规则引用和静态目标做为后缀和模块目录;这允许不同的视图解析器具备动态修改inflector能力的属性。
setinflector($inflector, $reference) 允许设置定制的inflector和视图解析器一起使用。如果$reference 是true,它将设置后缀和模块目录作为静态引用和目标给视图解析器 属性。
note: 缺省查找约定(conventions)
视图解析器做了一些路径标准化使视图脚本查找更容易。缺省规则如下:
:module: 混合词和驼峰词被短横线分开,并整个串变成小写。例如:"foobarbaz" 变成 "foo-bar-baz"。
在内部,变形器(inflector) 使用过滤器zend_filter_word_camelcasetodash 和 zend_filter_stringtolower。
:controller: 混合词和驼峰词被短横线分开;下划线转换成目录分隔符,并且整个串变小写。例如:"foobar" becomes "foo-bar"; "foobar_admin" 变成 "foo-bar/admin".
在内部,inflector 使用过滤器zend_filter_word_camelcasetodash、zend_filter_word_underscoretoseparator 和 zend_filter_stringtolower。
:action: 混合词和驼峰词被短横线分开;非字母数字字符翻译成短横线,并且整个串变成小写。 例如 "foobar" 变成 "foo-bar"; "foo-barbaz" 变成 "foo-bar-baz"。
在内部,inflector 使用过滤器 zend_filter_word_camelcasetodash、zend_filter_pregreplace 和 zend_filter_stringtolower。
视图解析器 api中的最后一项是关于实际确定视图脚本路径和解析视图的。包括:
renderscript($script, $name)允许解析指定路径的脚本,可选的命名的路径片段。(renderscript($script, $name) allows you to render a script with a path you specify, optionally to a named path segment. )使用该方法时,viewrenderer不会自动的确定脚本名称,而是直接的向视图对象的render()传入$script参数。
note: 当视图已经被解析到响应对象,将会设置norender阻止相同的脚本被多次解析。
note: 默认的,zend_controller_action::renderscript()代理viewrenderer的renderscript()方法。
getviewscript($action, $vars)基于传入的动作和/或$vars中的变量创建到视图脚本的路径。该数组中的键可以包含所有的路径指定键('moduledir','module', 'controller', 'action', and 'suffix')。传入的任何变量都会优先使用,否则利用基于当前请求的值。
getviewscript()根据nocontroller标志的设定值使用viewscriptpathspec或者viewscriptpathnocontrollerspec。
模块、控制器以及动作中的单词定界符将后替换成短线('-')。因此,控制器名称'foo.bar'和动作'baz:bat'按照默认的路径规则将会得到视图脚本路径'foo-bar/baz-bat.phtml'。
note: 默认的,zend_controller_action::getviewscript()代理viewrenderer的getviewscript()方法。
render($action, $name, $nocontroller)首先检查$name或 $nocontroller参数是否传入,如果传入,则在viewrenderer中设定相应的标志(分别是响应片段和nocontroller)。然后传入$action参数到getviewscript(),最后传入计算的试图脚本路径到renderscript()。
note: 注意使用render()的边际效应:传入的响应片段名称和nocontroller标志在视图对象中存留。此外解析结束后norender会被设置。
note: 默认的,zend_controller_action::render()代理 viewrenderer的render()方法。
renderbyspec($action, $vars, $name)允许传入路径规则变量以确定创建的视图脚本路径。它把$action和$vars传入到getscriptpath(),将脚本路径结果和$name传入到renderscript()。
基础用法示例
example #9 基本用法
大多数基础使用中,只需在bootstrap中使用助手经纪人简单的初始化和注册viewrenderer 助手,然后在动作方法中设置变量。
// in your bootstrap: zend_controller_action_helperbroker::getstatichelper('viewrenderer'); ... // 'foo' module, 'bar' controller: class foo_barcontroller extends zend_controller_action { // render bar/index.phtml by default; no action required public function indexaction() { } // render bar/populate.phtml with variable 'foo' set to 'bar'. // since view object defined at predispatch(), it's already available. public function populateaction() { $this->view->foo = 'bar'; } // renders nothing as it forwards to another action; the new action // will perform any rendering public function bazaction() { $this->_forward('index'); } // renders nothing as it redirects to another location public function bataction() { $this->_redirect('/index'); } }
note: 命名规则:控制器和动作名中的单词定界符
如果控制器或者动作名称由几个单词组成,分发器要求在url中使用特定的路径和单词定界符分隔。viewrenderer创建路径时将控制器名称中的任何路径定界符替换成实际的路径定界符('/'),任何单词定界符替换成短线('-')。对动作/foo.bar/baz.bat的调用将分发到foobarcontroller.php中的foobarcontroller::bazbataction(),然后解析foo-bar/baz-bat.phtml;对动作/bar_baz/baz-bat的调用将分发到bar/bazcontroller.php中的bar_bazcontroller::bazbataction(),并解析bar/baz/baz-bat.phtml。
注意到在第二个例子中,模块依然是默认的模块,但由于路径分隔符的存在,控制器的接收到的名字为bar_bazcontroller,该类在文件bar/bazcontroller.php中。viewrenderer模拟了控制器的目录分层。
example #10 禁用自动解析
对于某些动作和控制器,可能希望关闭自动解析——例如,如果想发送其他类型的输出(xml,json等),或者更简单的不想发送任何东西。有两个选项:关闭所有的自动解析(setneverrender()),或者仅仅关闭当前动作的自动解析(setnorender())。
// baz controller class, bar module: class bar_bazcontroller extends zend_controller_action { public function fooaction() { // don't auto render this action <strong>$this->_helper->viewrenderer->setnorender();</strong> } } // bat controller class, bar module: class bar_batcontroller extends zend_controller_action { public function predispatch() { // never auto render this controller's actions $this->_helper->viewrenderer->setnorender(); } }
note: 大多数情况下,全局的关闭自动解析(setneverrender())没有意义,因为这样viewrenderer做的唯一件事只是自动设置了视图对象。
example #11 选择另外的视图脚本
有些情况下需要解析另一个脚本而非以动作命名的脚本。例如,如果你有一个控制器包含增加和编辑两个动作,它们可能都显示相同的'form'视图,尽管拥有不同的值集合(value set)。只需要使用setscriptaction()或者setrender()简单的改变脚本的名称,或者以成员方法的形式调用助手,它将调用setrender()。
// bar controller class, foo module: class foo_barcontroller extends zend_controller_action { public function addaction() { // render 'bar/form.phtml' instead of 'bar/add.phtml' $this->_helper->viewrenderer('form'); } public function editaction() { // render 'bar/form.phtml' instead of 'bar/edit.phtml' $this->_helper->viewrenderer->setscriptaction('form'); } public function processaction() { // do some validation... if (!$valid) { // render 'bar/form.phtml' instead of 'bar/process.phtml' $this->_helper->viewrenderer->setrender('form'); return; } // otherwise continue processing... } }
example #12 修改注册的视图modifying the registered view
如果需要修改视图对象怎么办——例如改变助手路径或者编码?可以在控制器中修改视图对象设定,或者从viewrenderer中抓取视图对象;两种方式引用的是同一个对象。
// bar controller class, foo module: class foo_barcontroller extends zend_controller_action { public function predispatch() { // change view encoding $this->view->setencoding('utf-8'); } public function bazaction() { // get view object and set escape callback to 'htmlspecialchars' $view = $this->_helper->viewrenderer->view; $view->setescape('htmlspecialchars'); } }
高级用法示例
example #13 修改路径规则
有些情况下,默认的路径规则可能并不适合站点的需要。比如,希望拥有一个单独的模板树供设计人员访问(例如,如果你使用» smarty,这是很典型的情形)。这种情况下,你可能想硬编码视图的基路径规则,为动作视图脚本路径自身创建一套规则。
假定视图的基路径(base path)为'/opt/vendor/templates',希望通过':moduledir/:controller/:action.:suffix'引用视图脚本;如果设定了nocontroller标志,想在*而不是在子目录中解析(':action.:suffix')。最终希望使用'tpl'作为视图脚本文件的后缀。
/** * in your bootstrap: */ // different view implementation $view = new zf_smarty(); $viewrenderer = new zend_controller_action_helper_viewrenderer($view); $viewrenderer->setviewbasepathspec('/opt/vendor/templates') ->setviewscriptpathspec(':module/:controller/:action.:suffix') ->setviewscriptpathnocontrollerspec(':action.:suffix') ->setviewsuffix('tpl'); zend_controller_action_helperbroker::addhelper($viewrenderer);
example #14 一个动作中解析多个视图脚本
有时可能需要在一个动作中解析多个视图脚本。这个非常简单,多次调用render()就行了:
class searchcontroller extends zend_controller_action { public function resultsaction() { // assume $this->model is the current model $this->view->results = $this->model->find($this->_getparam('query', ''); // render() by default proxies to the viewrenderer // render first the search form and then the results $this->render('form'); $this->render('results'); } public function formaction() { // do nothing; viewrenderer autorenders the view script } }
viewrenderer的相关源码如下,仔细分析,并不难看出实现方法:
<?php /** * @see zend_controller_action_helper_abstract */ require_once 'zend/controller/action/helper/abstract.php'; /** * @see zend_view */ require_once 'zend/view.php'; /** * view script integration * * zend_controller_action_helper_viewrenderer provides transparent view * integration for action controllers. it allows you to create a view object * once, and populate it throughout all actions. several global options may be * set: * * - nocontroller: if set true, render() will not look for view scripts in * subdirectories named after the controller * - viewsuffix: what view script filename suffix to use * * the helper autoinitializes the action controller view predispatch(). it * determines the path to the class file, and then determines the view base * directory from there. it also uses the module name as a class prefix for * helpers and views such that if your module name is 'search', it will set the * helper class prefix to 'search_view_helper' and the filter class prefix to ; * 'search_view_filter'. * * usage: * <code> * // in your bootstrap: * zend_controller_action_helperbroker::addhelper(new zend_controller_action_helper_viewrenderer()); * * // in your action controller methods: * $viewhelper = $this->_helper->gethelper('view'); * * // don't use controller subdirectories * $viewhelper->setnocontroller(true); * * // specify a different script to render: * $this->_helper->viewrenderer('form'); * * </code> * * @uses zend_controller_action_helper_abstract * @package zend_controller * @subpackage zend_controller_action_helper * @copyright copyright (c) 2005-2011 zend technologies usa inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd new bsd license */ class zend_controller_action_helper_viewrenderer extends zend_controller_action_helper_abstract { /** * @var zend_view_interface */ public $view; /** * word delimiters * @var array */ protected $_delimiters; /** * @var zend_filter_inflector */ protected $_inflector; /** * inflector target * @var string */ protected $_inflectortarget = ''; /** * current module directory * @var string */ protected $_moduledir = ''; /** * whether or not to autorender using controller name as subdirectory; * global setting (not reset at next invocation) * @var boolean */ protected $_nevercontroller = false; /** * whether or not to autorender postdispatch; global setting (not reset at * next invocation) * @var boolean */ protected $_neverrender = false; /** * whether or not to use a controller name as a subdirectory when rendering * @var boolean */ protected $_nocontroller = false; /** * whether or not to autorender postdispatch; per controller/action setting (reset * at next invocation) * @var boolean */ protected $_norender = false; /** * characters representing path delimiters in the controller * @var string|array */ protected $_pathdelimiters; /** * which named segment of the response to utilize * @var string */ protected $_responsesegment = null; /** * which action view script to render * @var string */ protected $_scriptaction = null; /** * view object basepath * @var string */ protected $_viewbasepathspec = ':moduledir/views'; /** * view script path specification string * @var string */ protected $_viewscriptpathspec = ':controller/:action.:suffix'; /** * view script path specification string, minus controller segment * @var string */ protected $_viewscriptpathnocontrollerspec = ':action.:suffix'; /** * view script suffix * @var string */ protected $_viewsuffix = 'phtml'; /** * constructor * * optionally set view object and options. * * @param zend_view_interface $view * @param array $options * @return void */ public function __construct(zend_view_interface $view = null, array $options = array()) { if (null !== $view) { $this->setview($view); } if (!empty($options)) { $this->_setoptions($options); } } /** * clone - also make sure the view is cloned. * * @return void */ public function __clone() { if (isset($this->view) && $this->view instanceof zend_view_interface) { $this->view = clone $this->view; } } /** * set the view object * * @param zend_view_interface $view * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setview(zend_view_interface $view) { $this->view = $view; return $this; } /** * get current module name * * @return string */ public function getmodule() { $request = $this->getrequest(); $module = $request->getmodulename(); if (null === $module) { $module = $this->getfrontcontroller()->getdispatcher()->getdefaultmodule(); } return $module; } /** * get module directory * * @throws zend_controller_action_exception * @return string */ public function getmoduledirectory() { $module = $this->getmodule(); $moduledir = $this->getfrontcontroller()->getcontrollerdirectory($module); if ((null === $moduledir) || is_array($moduledir)) { /** * @see zend_controller_action_exception */ require_once 'zend/controller/action/exception.php'; throw new zend_controller_action_exception('viewrenderer cannot locate module directory for module "' . $module . '"'); } $this->_moduledir = dirname($moduledir); return $this->_moduledir; } /** * get inflector * * @return zend_filter_inflector */ public function getinflector() { if (null === $this->_inflector) { /** * @see zend_filter_inflector */ require_once 'zend/filter/inflector.php'; /** * @see zend_filter_pregreplace */ require_once 'zend/filter/pregreplace.php'; /** * @see zend_filter_word_underscoretoseparator */ require_once 'zend/filter/word/underscoretoseparator.php'; $this->_inflector = new zend_filter_inflector(); $this->_inflector->setstaticrulereference('moduledir', $this->_moduledir) // moduledir must be specified before the less specific 'module' ->addrules(array( ':module' => array('word_camelcasetodash', 'stringtolower'), ':controller' => array('word_camelcasetodash', new zend_filter_word_underscoretoseparator('/'), 'stringtolower', new zend_filter_pregreplace('/\./', '-')), ':action' => array('word_camelcasetodash', new zend_filter_pregreplace('#[^a-z0-9' . preg_quote('/', '#') . ']+#i', '-'), 'stringtolower'), )) ->setstaticrulereference('suffix', $this->_viewsuffix) ->settargetreference($this->_inflectortarget); } // ensure that module directory is current $this->getmoduledirectory(); return $this->_inflector; } /** * set inflector * * @param zend_filter_inflector $inflector * @param boolean $reference whether the moduledir, target, and suffix should be set as references to viewrenderer properties * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setinflector(zend_filter_inflector $inflector, $reference = false) { $this->_inflector = $inflector; if ($reference) { $this->_inflector->setstaticrulereference('suffix', $this->_viewsuffix) ->setstaticrulereference('moduledir', $this->_moduledir) ->settargetreference($this->_inflectortarget); } return $this; } /** * set inflector target * * @param string $target * @return void */ protected function _setinflectortarget($target) { $this->_inflectortarget = (string) $target; } /** * set internal module directory representation * * @param string $dir * @return void */ protected function _setmoduledir($dir) { $this->_moduledir = (string) $dir; } /** * get internal module directory representation * * @return string */ protected function _getmoduledir() { return $this->_moduledir; } /** * generate a class prefix for helper and filter classes * * @return string */ protected function _generatedefaultprefix() { $default = 'zend_view'; if (null === $this->_actioncontroller) { return $default; } $class = get_class($this->_actioncontroller); if (!strstr($class, '_')) { return $default; } $module = $this->getmodule(); if ('default' == $module) { return $default; } $prefix = substr($class, 0, strpos($class, '_')) . '_view'; return $prefix; } /** * retrieve base path based on location of current action controller * * @return string */ protected function _getbasepath() { if (null === $this->_actioncontroller) { return './views'; } $inflector = $this->getinflector(); $this->_setinflectortarget($this->getviewbasepathspec()); $dispatcher = $this->getfrontcontroller()->getdispatcher(); $request = $this->getrequest(); $parts = array( 'module' => (($modulename = $request->getmodulename()) != '') ? $dispatcher->formatmodulename($modulename) : $modulename, 'controller' => $request->getcontrollername(), 'action' => $dispatcher->formatactionname($request->getactionname()) ); $path = $inflector->filter($parts); return $path; } /** * set options * * @param array $options * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ protected function _setoptions(array $options) { foreach ($options as $key => $value) { switch ($key) { case 'neverrender': case 'nevercontroller': case 'nocontroller': case 'norender': $property = '_' . $key; $this->{$property} = ($value) ? true : false; break; case 'responsesegment': case 'scriptaction': case 'viewbasepathspec': case 'viewscriptpathspec': case 'viewscriptpathnocontrollerspec': case 'viewsuffix': $property = '_' . $key; $this->{$property} = (string) $value; break; default: break; } } return $this; } /** * initialize the view object * * $options may contain the following keys: * - neverrender - flag dis/enabling postdispatch() autorender (affects all subsequent calls) * - nocontroller - flag indicating whether or not to look for view scripts in subdirectories named after the controller * - norender - flag indicating whether or not to autorender postdispatch() * - responsesegment - which named response segment to render a view script to * - scriptaction - what action script to render * - viewbasepathspec - specification to use for determining view base path * - viewscriptpathspec - specification to use for determining view script paths * - viewscriptpathnocontrollerspec - specification to use for determining view script paths when nocontroller flag is set * - viewsuffix - what view script filename suffix to use * * @param string $path * @param string $prefix * @param array $options * @throws zend_controller_action_exception * @return void */ public function initview($path = null, $prefix = null, array $options = array()) { if (null === $this->view) { $this->setview(new zend_view()); } // reset some flags every time $options['nocontroller'] = (isset($options['nocontroller'])) ? $options['nocontroller'] : false; $options['norender'] = (isset($options['norender'])) ? $options['norender'] : false; $this->_scriptaction = null; $this->_responsesegment = null; // set options first; may be used to determine other initializations $this->_setoptions($options); // get base view path if (empty($path)) { $path = $this->_getbasepath(); if (empty($path)) { /** * @see zend_controller_action_exception */ require_once 'zend/controller/action/exception.php'; throw new zend_controller_action_exception('viewrenderer initialization failed: retrieved view base path is empty'); } } if (null === $prefix) { $prefix = $this->_generatedefaultprefix(); } // determine if this path has already been registered $currentpaths = $this->view->getscriptpaths(); $path = str_replace(array('/', '\\'), '/', $path); $pathexists = false; foreach ($currentpaths as $tmppath) { $tmppath = str_replace(array('/', '\\'), '/', $tmppath); if (strstr($tmppath, $path)) { $pathexists = true; break; } } if (!$pathexists) { $this->view->addbasepath($path, $prefix); } // register view with action controller (unless already registered) if ((null !== $this->_actioncontroller) && (null === $this->_actioncontroller->view)) { $this->_actioncontroller->view = $this->view; $this->_actioncontroller->viewsuffix = $this->_viewsuffix; } } /** * init - initialize view * * @return void */ public function init() { if ($this->getfrontcontroller()->getparam('noviewrenderer')) { return; } $this->initview(); } /** * set view basepath specification * * specification can contain one or more of the following: * - :moduledir - current module directory * - :controller - name of current controller in the request * - :action - name of current action in the request * - :module - name of current module in the request * * @param string $path * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setviewbasepathspec($path) { $this->_viewbasepathspec = (string) $path; return $this; } /** * retrieve the current view basepath specification string * * @return string */ public function getviewbasepathspec() { return $this->_viewbasepathspec; } /** * set view script path specification * * specification can contain one or more of the following: * - :moduledir - current module directory * - :controller - name of current controller in the request * - :action - name of current action in the request * - :module - name of current module in the request * * @param string $path * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setviewscriptpathspec($path) { $this->_viewscriptpathspec = (string) $path; return $this; } /** * retrieve the current view script path specification string * * @return string */ public function getviewscriptpathspec() { return $this->_viewscriptpathspec; } /** * set view script path specification (no controller variant) * * specification can contain one or more of the following: * - :moduledir - current module directory * - :controller - name of current controller in the request * - :action - name of current action in the request * - :module - name of current module in the request * * :controller will likely be ignored in this variant. * * @param string $path * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setviewscriptpathnocontrollerspec($path) { $this->_viewscriptpathnocontrollerspec = (string) $path; return $this; } /** * retrieve the current view script path specification string (no controller variant) * * @return string */ public function getviewscriptpathnocontrollerspec() { return $this->_viewscriptpathnocontrollerspec; } /** * get a view script based on an action and/or other variables * * uses values found in current request if no values passed in $vars. * * if {@link $_nocontroller} is set, uses {@link $_viewscriptpathnocontrollerspec}; * otherwise, uses {@link $_viewscriptpathspec}. * * @param string $action * @param array $vars * @return string */ public function getviewscript($action = null, array $vars = array()) { $request = $this->getrequest(); if ((null === $action) && (!isset($vars['action']))) { $action = $this->getscriptaction(); if (null === $action) { $action = $request->getactionname(); } $vars['action'] = $action; } elseif (null !== $action) { $vars['action'] = $action; } $replacepattern = array('/[^a-z0-9]+$/i', '/^[^a-z0-9]+/i'); $vars['action'] = preg_replace($replacepattern, '', $vars['action']); $inflector = $this->getinflector(); if ($this->getnocontroller() || $this->getnevercontroller()) { $this->_setinflectortarget($this->getviewscriptpathnocontrollerspec()); } else { $this->_setinflectortarget($this->getviewscriptpathspec()); } return $this->_translatespec($vars); } /** * set the neverrender flag (i.e., globally dis/enable autorendering) * * @param boolean $flag * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setneverrender($flag = true) { $this->_neverrender = ($flag) ? true : false; return $this; } /** * retrieve neverrender flag value * * @return boolean */ public function getneverrender() { return $this->_neverrender; } /** * set the norender flag (i.e., whether or not to autorender) * * @param boolean $flag * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setnorender($flag = true) { $this->_norender = ($flag) ? true : false; return $this; } /** * retrieve norender flag value * * @return boolean */ public function getnorender() { return $this->_norender; } /** * set the view script to use * * @param string $name * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setscriptaction($name) { $this->_scriptaction = (string) $name; return $this; } /** * retrieve view script name * * @return string */ public function getscriptaction() { return $this->_scriptaction; } /** * set the response segment name * * @param string $name * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setresponsesegment($name) { if (null === $name) { $this->_responsesegment = null; } else { $this->_responsesegment = (string) $name; } return $this; } /** * retrieve named response segment name * * @return string */ public function getresponsesegment() { return $this->_responsesegment; } /** * set the nocontroller flag (i.e., whether or not to render into controller subdirectories) * * @param boolean $flag * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setnocontroller($flag = true) { $this->_nocontroller = ($flag) ? true : false; return $this; } /** * retrieve nocontroller flag value * * @return boolean */ public function getnocontroller() { return $this->_nocontroller; } /** * set the nevercontroller flag (i.e., whether or not to render into controller subdirectories) * * @param boolean $flag * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setnevercontroller($flag = true) { $this->_nevercontroller = ($flag) ? true : false; return $this; } /** * retrieve nevercontroller flag value * * @return boolean */ public function getnevercontroller() { return $this->_nevercontroller; } /** * set view script suffix * * @param string $suffix * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setviewsuffix($suffix) { $this->_viewsuffix = (string) $suffix; return $this; } /** * get view script suffix * * @return string */ public function getviewsuffix() { return $this->_viewsuffix; } /** * set options for rendering a view script * * @param string $action view script to render * @param string $name response named segment to render to * @param boolean $nocontroller whether or not to render within a subdirectory named after the controller * @return zend_controller_action_helper_viewrenderer provides a fluent interface */ public function setrender($action = null, $name = null, $nocontroller = null) { if (null !== $action) { $this->setscriptaction($action); } if (null !== $name) { $this->setresponsesegment($name); } if (null !== $nocontroller) { $this->setnocontroller($nocontroller); } return $this; } /** * inflect based on provided vars * * allowed variables are: * - :moduledir - current module directory * - :module - current module name * - :controller - current controller name * - :action - current action name * - :suffix - view script file suffix * * @param array $vars * @return string */ protected function _translatespec(array $vars = array()) { $inflector = $this->getinflector(); $request = $this->getrequest(); $dispatcher = $this->getfrontcontroller()->getdispatcher(); $module = $dispatcher->formatmodulename($request->getmodulename()); $controller = $request->getcontrollername(); $action = $dispatcher->formatactionname($request->getactionname()); $params = compact('module', 'controller', 'action'); foreach ($vars as $key => $value) { switch ($key) { case 'module': case 'controller': case 'action': case 'moduledir': case 'suffix': $params[$key] = (string) $value; break; default: break; } } if (isset($params['suffix'])) { $origsuffix = $this->getviewsuffix(); $this->setviewsuffix($params['suffix']); } if (isset($params['moduledir'])) { $origmoduledir = $this->_getmoduledir(); $this->_setmoduledir($params['moduledir']); } $filtered = $inflector->filter($params); if (isset($params['suffix'])) { $this->setviewsuffix($origsuffix); } if (isset($params['moduledir'])) { $this->_setmoduledir($origmoduledir); } return $filtered; } /** * render a view script (optionally to a named response segment) * * sets the norender flag to true when called. * * @param string $script * @param string $name * @return void */ public function renderscript($script, $name = null) { if (null === $name) { $name = $this->getresponsesegment(); } $this->getresponse()->appendbody( $this->view->render($script), $name ); $this->setnorender(); } /** * render a view based on path specifications * * renders a view based on the view script path specifications. * * @param string $action * @param string $name * @param boolean $nocontroller * @return void */ public function render($action = null, $name = null, $nocontroller = null) { $this->setrender($action, $name, $nocontroller); $path = $this->getviewscript(); $this->renderscript($path, $name); } /** * render a script based on specification variables * * pass an action, and one or more specification variables (view script suffix) * to determine the view script path, and render that script. * * @param string $action * @param array $vars * @param string $name * @return void */ public function renderbyspec($action = null, array $vars = array(), $name = null) { if (null !== $name) { $this->setresponsesegment($name); } $path = $this->getviewscript($action, $vars); $this->renderscript($path); } /** * postdispatch - auto render a view * * only autorenders if: * - _norender is false * - action controller is present * - request has not been re-dispatched (i.e., _forward() has not been called) * - response is not a redirect * * @return void */ public function postdispatch() { if ($this->_shouldrender()) { $this->render(); } } /** * should the viewrenderer render a view script? * * @return boolean */ protected function _shouldrender() { return (!$this->getfrontcontroller()->getparam('noviewrenderer') && !$this->_neverrender && !$this->_norender && (null !== $this->_actioncontroller) && $this->getrequest()->isdispatched() && !$this->getresponse()->isredirect() ); } /** * use this helper as a method; proxies to setrender() * * @param string $action * @param string $name * @param boolean $nocontroller * @return void */ public function direct($action = null, $name = null, $nocontroller = null) { $this->setrender($action, $name, $nocontroller); } }
更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于zend framework框架的php程序设计有所帮助。
上一篇: 3.gulp.src()
推荐阅读
-
Zend Framework教程之Zend_Helpers动作助手ViewRenderer用法详解
-
Zend Framework动作助手Url用法详解,zendframework_PHP教程
-
Zend Framework动作助手Redirector用法实例详解,zendredirector_PHP教程
-
Zend Framework动作助手(Zend_Controller_Action_Helper)用法详解,zendhelper_PHP教程
-
Zend Framework动作助手FlashMessenger用法详解,zendflashmessenger_PHP教程
-
Zend Framework动作助手Url用法详解_PHP
-
Zend Framework动作助手FlashMessenger用法详解,zendflashmessenger_PHP教程
-
Zend Framework动作助手Redirector用法实例详解
-
Zend Framework动作助手Url用法详解
-
Zend Framework动作助手(Zend_Controller_Action_Helper)用法详解