当前位置: 首页 > 编程文章 >

Zend Framework视图组件Zend_View用法详解

Zend Framework视图组件Zend_View用法详解

作者:江舟时间:2025-06-03 15:16:15浏览:429

Zend_View作为Zend Framework的MVC视图层组件,负责向用户展示页面内容。本文详细解析其目录结构、与Zend_Controller_Action的整合机制,包括默认的render实例化流程及自定义视图路径设置。同时介绍构造函数配置项、assign参数传递方式,以及在Bootstrap和Action中的初始化用法,并列举常用视图助手方法。

本文目录展开

Zend_View视图组件概述

本示例深入讲解Zend Framework中视图组件Zend_View的具体使用方法,旨在为开发者提供实用的参考指南。

在MVC架构中,Zend_View承担着视图层的职责,直接面向用户呈现最终页面。下文将剖析Zend_View的核心实现类及其与控制器(Controller)的协作机制。

View的实现

Zend_View的功能主要通过以下目录下的类文件来实现:

root@coder-671T-M:/library/Zend# tree | grep View.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

该目录结构包含6个子目录和70个文件。

Zend_View和Zend_Controller的整合

这种整合主要发生在Zend_Controller_Action类中。


/**
   * Initialize View object
   *
   * Initializes {@link $view} if not otherwise a Zend_View_Interface.
   *
   * If {@link $view} is not otherwise set, instantiates a new Zend_View
   * object, using the 'views' subdirectory at the same level as the
   * controller directory for the current module as the base directory.
   * It uses this to set the following:
   * - script path = views/scripts/
   * - helper path = views/helpers/
   * - filter path = views/filters/
   *
   * @return Zend_View_Interface
   * @throws Zend_Controller_Exception if base view directory does not exist
   */
  public function initView()
  {
    if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
      return $this->view;
    }
    require_once 'Zend/View/Interface.php';
    if (isset($this->view) && ($this->view instanceof Zend_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';
      throw new Zend_Controller_Exception('Missing base view directory ("' . $baseDir . '")');
    }
    require_once 'Zend/View.php';
    $this->view = new Zend_View(array('basePath' => $baseDir));
    return $this->view;
  }
  /**
   * Render a view
   *
   * Renders a view. By default, views are found in the view script path as
   * /.phtml. You may change the script suffix by
   * resetting {@link $viewSuffix}. You may omit the controller directory
   * prefix by specifying boolean true for $noController.
   *
   * By default, the rendered contents are appended to the response. You may
   * specify the named body content segment to set by specifying a $name.
   *
   * @see Zend_Controller_Response_Abstract::appendBody()
   * @param string|null $action Defaults to action registered in request object
   * @param string|null $name Response object named path segment to use; defaults to null
   * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script
   * @return void
   */
  public function render($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
    );
  }
  /**
   * Render a given view script
   *
   * Similar to {@link render()}, this method renders a view script. Unlike render(),
   * however, it does not autodetermine the view script via {@link getViewScript()},
   * but instead renders the script passed to it. Use this if you know the
   * exact view script name and path you wish to use, or if using paths that do not
   * conform to the spec defined with getViewScript().
   *
   * By default, the rendered contents are appended to the response. You may
   * specify the named body content segment to set by specifying a $name.
   *
   * @param string $script
   * @param string $name
   * @return void
   */
  public function renderScript($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
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category  Zend
* @package  Zend_View
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license  http://framework.zend.com/license/new-bsd   New BSD License
* @version  $Id: View.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Abstract master class for extension.
*/
require_once 'Zend/View/Abstract.php';
/**
* Concrete class for handling view scripts.
*
* @category  Zend
* @package  Zend_View
* @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_View extends Zend_View_Abstract
{
    /**
    * Whether or not to use streams to mimic short tags
    * @var bool
    */
    private $_useViewStream = false;
    /**
    * Whether or not to use stream wrapper if short_open_tag is false
    * @var bool
    */
    private $_useStreamWrapper = false;
    /**
    * Constructor
    *
    * Register Zend_View_Stream stream wrapper if short tags are disabled.
    *
    * @param array $config
    * @return void
    */
    public function __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);
    }
    /**
    * Set flag indicating if stream wrapper should be used if short_open_tag is off
    *
    * @param bool $flag
    * @return Zend_View
    */
    public function setUseStreamWrapper($flag)
    {
        $this->_useStreamWrapper = (bool) $flag;
        return $this;
    }
    /**
    * Should the stream wrapper be used if short_open_tag is off?
    *
    * @return bool
    */
    public function useStreamWrapper()
    {
        return $this->_useStreamWrapper;
    }
    /**
    * Includes the view script in a scope with only public $this variables.
    *
    * @param string The view script to execute.
    */
    protected function _run()
    {
        if ($this->_useViewStream && $this->useStreamWrapper()) {
            include 'zend.view://' . func_get_arg(0);
        } else {
            include func_get_arg(0);
        }
    }
}
</code></pre>
默认情况下,Controller会自动调用render方法来实例化Zend_View对象,并将其渲染到对应的视图文件中。当然,开发者也可以手动实例化Zend_View并进行使用。
Action默认指向的文件名与其名称相同。若需指定特定的视图文件,可通过$this->render的相关方法设定;此外,还可以利用addScriptPath或setScriptPath方法来配置视图文件的搜索目录。
例如
<pre class="brush:php;"><code class="language-php">
$view = new Zend_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".
</code></pre>
Zend_View的常用方法
<pre class="brush:php;"><code class="language-php">
public function __construct($config = array())
</code></pre>
构造函数参数
例如
<pre class="brush:php;"><code class="language-php">
array(
'escape' => array(),
'encoding' => array(),
);
</code></pre>
常见的配置键包括:
escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、 helperPathPrefix、filterPath、filterPathPrefix、filter
public function getEngine() 返回模板引擎对象
public function init() 初始化函数
<pre class="brush:php;"><code class="language-php">
/**
* Given a base path, sets the script, helper, and filter paths relative to it
*
* Assumes a directory structure of:
* <code>
* basePath/
*   scripts/
*   helpers/
*   filters/
* </code>
*
* @param string $path
* @param string $prefix Prefix to use for helper and filter paths
* @return Zend_View_Abstract
*/
public function setBasePath($path, $classPrefix = 'Zend_View')
/**
* Given a base path, add script, helper, and filter paths relative to it
*
* Assumes a directory structure of:
* <code>
* basePath/
*   scripts/
*   helpers/
*   filters/
* </code>
*
* @param string $path
* @param string $prefix Prefix to use for helper and filter paths
* @return Zend_View_Abstract
*/
public function addBasePath($path, $classPrefix = 'Zend_View')
public function addScriptPath($path)Adds to the stack of view script paths in LIFO order.
public function setScriptPath($path) Resets the stack of view script paths.
public function getScriptPath($name)Return full path to a view script specified by $name
public function getScriptPaths()Returns an array of all currently set script paths
public function addHelperPath($path, $classPrefix = 'Zend_View_Helper_')Adds to the stack of helper paths in LIFO order.
public function setHelperPath($path, $classPrefix = 'Zend_View_Helper_')Resets the stack of helper paths.
public function getHelperPath($name) Get full path to a helper class file specified by $name
public function getHelperPaths()Returns an array of all currently set helper paths
public function getHelper($name) Get a helper by name
public function getHelpers()Get array of all active helpers
public function getAllPaths() Return associative array of path types => paths
public function setEscape($spec)
/**
* Assigns variables to the view script via differing strategies.
*
* Zend_View::assign('name', $value) assigns a variable called 'name'
* with the corresponding $value.
*
* Zend_View::assign($array) assigns the array keys as variable
* names (with the corresponding array values).
*
* @see  __set()
* @param string|array The assignment strategy to use.
* @param mixed (Optional) If assigning a named variable, use this
* as the value.
* @return Zend_View_Abstract Fluent interface
* @throws Zend_View_Exception if $spec is neither a string nor an array,
* or if an attempt to set a private or protected member is detected
*/
public function assign($spec, $value = null)
</code></pre>
在Controller的Action中,可以通过assign方法将参数传递给视图脚本。
例如
<pre class="brush:php;"><code class="language-php">
$this->view->assign('roles', $roles);
$this->view->assign('num', $num);
$this->view->assign('a', $a);
</code></pre>
或者也可以使用
<pre class="brush:php;"><code class="language-php">
$this->view->roles=$roles;
$this->view->a=$a;
public function render($name) Processes a view script and returns the output.
public function escape($var):Escapes a value for output in a view script.
public function setEncoding($encoding) Set encoding to use with htmlentities() and htmlspecialchars()
public function getEncoding() :Return current escape encoding
</code></pre>
视图脚本文件中的常见用法:
获取传递过来的值
<pre class="brush:php;"><code class="language-php">
$this->roles
</code></pre>
使用一些常见的助手方法:
<pre class="brush:php;"><code class="language-php">
$this->baseUrl();
$this->url();
$this->paginationControl();
$this->partial()
</code></pre>
视图常见用法举例
在Bootstrap初始化view或者controller的init文件中
<pre class="brush:php;"><code class="language-php">
/**
* Initialize the common view helper
*/
protected function _initViewHelper()
{
    $boot=$this->bootstrap('View');
    $view = $boot->getResource('View');
    $view->setHelperPath('Sql/View/Helper', 'Sql_View_Helper');
}
</code></pre>
action中
<pre class="brush:php;"><code class="language-php">
/**
*
* @return void
*/
public function listAction()
{
    $this->view->assign('data', $data);
}
</code></pre>
视图文件
list.phtml
<pre class="brush:php;"><code class="language-php">
<?php foreach ($this->data as $item) : ?>
<?php echo($item->item1);?>
<?php endforeach; ?>

希望本文所述对大家PHP程序设计有所帮助。

上一篇
PHP header() 函数详解:HTTP 协议与常见用法实例

本文介绍 PHP 中 header() 函数的作用,该函数通过 HTTP 协议向浏览器发送标头以控制页面处理。内容涵盖 HTTP 请求响应机制、标准标头类型(Location、Content-Type、Status)及状态码含义,并提供重定向、强制刷新缓存、设置 MIME 类型及权限控制等具体代码示例。

下一篇
ThinkPHP防止表单重复提交的三种方法

在ThinkPHP开发中,若后台处理完数据后返回当前页面,刷新或后退可能导致记录被重复增加或修改。本文分析了导致该问题的内存缓存原因,并提供了三种解决方案:一是提交后重定向至其他页面;二是通过JS禁用提交按钮;三是在服务端使用隐藏随机Token进行校验,结合TP默认令牌环机制可有效避免此问题。

相关文章

更多
Zend Framework 中 Zend_Config 组件的多种配置读取方式详解

本文详细介绍 Zend Framework 中 Zend_Config 组件的四种主要数据读取方式。通过实例演示如何从 PHP 数组、PHP 代码文件、INI 格式文件以及 XML 文件中加载配置信息,并展示如何将配置对象转换为数组形式。这些方法涵盖了数据库连接参数等常见配置场景,帮助开发者灵活管理应用配置。

2026.06.16 986
Zend Framework前端控制器核心方法与参数配置详解

本文详细介绍Zend Framework中FrontController类的常用方法与环境访问器。通过实例演示如何获取控制器实例、设置动作控制器查找路径,以及利用setParam和clearParams等方法管理分发过程中的请求、路由及响应对象参数。

2026.10.30 975
Zend Framework Captcha模块使用指南

本文介绍如何使用Zend Framework的Captcha模块生成和验证图片验证码。首先需确保PHP环境已安装GD扩展,通过Zend_Captcha_Image类配置字体、尺寸及噪点参数生成验证码图片。利用Zend_Session_Namespace将验证码原文与唯一ID绑定存储,并在表单提交时比对用户输入以完成验证。此外,还探讨了清理过期图片文件及重写generate方法实现自定义ID生成的进阶技巧。

2025.10.19 960
Zend Framework分发器机制与_forward()方法详解

Zend Framework的分发器负责解析请求中的模块、控制器和动作名,并实例化相应的控制器执行逻辑。当指定组件缺失时,系统依据Zend_Controller_Dispatcher_Standard类设定的默认值(如index/default)进行回退。开发者可通过setDEfaultController等方法自定义这些默认配置。此外,在动作中调用_forward()可跳转至新的控制器或动作,实现流程控制。

2025.12.04 946
Zend Framework常用校验器详解

本文介绍了Zend Framework中常用的数据校验器,包括Date日期校验、InArray数组包含校验以及Regex正则匹配校验。通过具体代码示例展示了各校验器的使用方法和输出结果,并详细说明了如何继承Zend_Validate_Interface接口来实现自定义校验器,以满足特定的业务验证需求。

2025.04.02 946
Zend Framework动作基类Zend_Controller_Action详解

Zend_Controller_Action是Zend Framework中动作控制器的基类,提供动作执行、视图渲染及助手管理等核心功能。该类通过继承实现,支持自定义初始化、参数处理及异常捕获,并允许开发者灵活配置ViewRenderer、请求/响应对象交互以及HTTP重定向行为,适用于构建标准的MVC架构应用。

2026.09.01 942

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。