侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

框架(架构)  /  管理员 发布于 7年前   170

本文实例讲述了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   * /.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类

_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:* * basePath/*   scripts/*   helpers/*   filters/* ** @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:* * basePath/*   scripts/*   helpers/*   filters/* ** @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 $namepublic function getScriptPaths()Returns an array of all currently set script pathspublic 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 $namepublic function getHelperPaths()Returns an array of all currently set helper pathspublic function getHelper($name) Get a helper by namepublic function getHelpers()Get array of all active helperspublic function getAllPaths() Return associative array of path types => pathspublic 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

data as $item) : ?>    item1);?>

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

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

您可能感兴趣的文章:

  • Zend Framework实现Zend_View集成Smarty模板系统的方法
  • Zend Framework处理Json数据方法详解
  • Zend Framework使用Zend_Loader组件动态加载文件和类用法详解
  • Zend Framework入门教程之Zend_Registry组件用法详解
  • Zend Framework入门教程之Zend_Config组件用法详解
  • Zend Framework过滤器Zend_Filter用法详解
  • Zend Framework实现自定义过滤器的方法
  • php入门教程之Zend Studio设置与开发实例
  • Zend Framework开发入门经典教程
  • Zend Framework入门教程之Zend_View组件用法示例


  • 上一条:
    Zend Framework实现Zend_View集成Smarty模板系统的方法
    下一条:
    Zend Framework教程之模型Model用法简单实例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客