Zend Framework教程之视图组件Zend_View用法详解


Posted in PHP onMarch 05, 2016

本文实例讲述了Zend Framework教程之视图组件Zend_View用法。分享给大家供大家参考,具体如下:

Zend_View是Zend Framework的视图组件,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 directories, 70 files

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
   * <controller>/<action>.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);
    }
  }
}

默认情况会自动通过Controller会通过render方法来实例化Zend_View, 然后rener到对应的视图文件中。当然可以自己实例化Zend_View,然后使用。

action默认指向的文件是和action的名称相同,如果要指定视图文件,可以通过$this->render的相关方法指定.也可以通过addScriptPath和setScriptPath设置视图文件的目录。

例如

$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".

Zend_View的常用方法

public function __construct($config = array())

构造函数参数

例如

array(
 'escape' => array(),
 'encoding' => array(),
);

常见key:

escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、 helperPathPrefix、filterPath、filterPathPrefix、filter
public function getEngine() Return the template engine object

public function init()初始化函数

/**
* 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)

在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;
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

视图脚本文件中的常见用法

获取传递过来的值

$this->roles

使用一些常见的助手方法:

$this->baseUrl();
$this->url();
$this->paginationControl();
$this->partial()

视图常见用法举例

在bootstrap初始化view或者controller的init文件中

/**
 * Initialize the common view helper
 */
protected function _initViewHelper()
{
  $boot=$this->bootstrap('View');
  $view = $boot->getResource('View');
        $view->setHelperPath('Sql/View/Helper', 'Sql_View_Helper');
}

action中

/**
 *
 * @return void
 */
public function listAction()
{
  $this->view->assign('data', $data);
}

视图文件

list.phtml

<?php foreach ($this->data as $item) : ?>
<tr style="height: 19px;">
    <td class="datagrid-cell"><?php echo($item->item1);?></td>
</tr>
<?php endforeach; ?>

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

PHP 相关文章推荐
web方式ftp
Oct 09 PHP
php 过滤器实现代码
Aug 09 PHP
PHP数组对比函数,存在交集则返回真,否则返回假
Feb 03 PHP
php的ajax简单实例
Feb 27 PHP
PHP rsa加密解密使用方法
Apr 27 PHP
利用“多说”制作留言板、评论系统
Jul 14 PHP
php 问卷调查结果统计
Oct 08 PHP
php cookie工作原理与实例详解
Jul 18 PHP
PHP获取当前执行php文件名的代码
Mar 02 PHP
PHP+iframe模拟Ajax上传文件功能示例
Jul 02 PHP
thinkphp5.1框架容器与依赖注入实例分析
Jul 23 PHP
php实例化对象的实例方法
Nov 17 PHP
Zend Framework教程之模型Model用法简单实例
Mar 04 #PHP
基于PHP实现等比压缩图片大小
Mar 04 #PHP
Zend Framework教程之模型Model基本规则和使用方法
Mar 04 #PHP
Zend Framework教程之Zend_Layout布局助手详解
Mar 04 #PHP
php mailer类调用远程SMTP服务器发送邮件实现方法
Mar 04 #PHP
PHP使用curl模拟post上传及接收文件的方法
Mar 04 #PHP
PHP生成和获取XML格式数据的方法
Mar 04 #PHP
You might like
生成静态页面的PHP类
2006/07/15 PHP
php 数组动态添加实现代码(最土团购系统的价格排序)
2011/12/30 PHP
使用PHP实现阻止用户上传成人照片或者裸照
2014/12/25 PHP
windows中为php安装mongodb与memcache
2015/01/06 PHP
日常整理PHP中简单的图形处理(经典)
2015/10/26 PHP
浅谈PHP Cookie处理函数
2016/06/10 PHP
thinkPHP中U方法加密传递参数功能示例
2018/05/29 PHP
PHP使用ajax的post方式下载excel文件简单示例
2019/08/06 PHP
PHP Swoole异步读取、写入文件操作示例
2019/10/24 PHP
php7 新增功能实例总结
2020/05/25 PHP
科讯商业版中用到的ajax空间与分页函数
2007/09/02 Javascript
jQuery checkbox全选/取消全选实现代码
2009/11/14 Javascript
初识Node.js
2014/09/03 Javascript
Javascript无参数和有参数类继承问题解决方法
2015/03/02 Javascript
JavaScript中常用的六种互动方法示例
2015/03/13 Javascript
Jsonp 关键字详解及json和jsonp的区别,ajax和jsonp的区别
2015/12/30 Javascript
WordPress中利用AJAX异步获取评论用户头像的方法
2016/01/08 Javascript
进阶之初探nodeJS
2017/01/24 NodeJs
vue项目实战总结篇
2018/02/11 Javascript
微信小程序实现自上而下字幕滚动
2018/07/14 Javascript
JS组件库AlloyTouch实现图片轮播过程解析
2020/05/29 Javascript
nodeJS与MySQL实现分页数据以及倒序数据
2020/06/05 NodeJs
从0到1学习JavaScript编写贪吃蛇游戏
2020/07/28 Javascript
详解Howler.js Web音频播放终极解决方案
2020/08/23 Javascript
python实现的防DDoS脚本
2011/02/08 Python
新手入门Python编程的8个实用建议
2019/07/12 Python
opencv实现简单人脸识别
2021/02/19 Python
Pytorch中的variable, tensor与numpy相互转化的方法
2019/10/10 Python
python多线程案例之多任务copy文件完整实例
2019/10/29 Python
pytorch 实现cross entropy损失函数计算方式
2020/01/02 Python
利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式
2020/01/20 Python
利于python脚本编写可视化nmap和masscan的方法
2020/12/29 Python
CSS3+font字体文件实现圆形半透明菜单具体步骤(图解)
2013/06/03 HTML / CSS
欢迎家长标语
2014/10/08 职场文书
电子商务专业求职信范文
2015/03/19 职场文书
python爬虫请求库httpx和parsel解析库的使用测评
2021/05/10 Python