ZendFramework tutorial-view component Zend_View usage _ php instance

Source: Internet
Author: User
Tags php foreach zend framework
This article mainly introduces the Zend_View usage of the view component in the ZendFramework tutorial, analyzes in detail the principle of trying to use the Zend_View component, and analyzes the usage skills of Zend_View in the form of instances, for more information about Zend_View, see the following example. We will share this with you for your reference. The details are as follows:

Zend_View is the view component of Zend Framework, which is the view layer in MVC. Zend_View is also the page that the application directly displays to the user. Here we will introduce the implementation class of Zend_View and how to combine it with Controller.

View implementation

The implementation of Zend_View is mainly implemented through the following Directory class:

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
│ ── Iner
│ ── 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

Integration of Zend_View and Zend_Controller

Mainly in the Zend_Controller_Action class,

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

<?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);    }  }}

By default, Zend_View is automatically instantiated through the Controller through the render method, and then rener to the corresponding View File. Of course, you can instantiate Zend_View and then use it.

By default, action is directed to the same file as action. to specify a view file, you can specify it using the $ this-> render method. you can also use addScriptPath and setScriptPath to set the directory of the View File.

For example

$ View = new Zend_View (); $ view-> addScriptPath ('/www/app/myview'); $ view-> addScriptPath ('/www/app/viewscomm '); // if you call $ view-> render ('example. php '), Zend_View will // first find "/www/app/myviews/example. php ", cannot find"/www/app/viewscomm/example. php ", if you still cannot find it, find the" example. php ".

Common Zend_View Methods

public function __construct($config = array())

Constructor Parameters

For example

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

Common keys:

Escape, encoding, basePath, basePathPrefix, scriptPath, helperPath, helperPathPrefix, filterPath, filterPathPrefix, and filter
Public function getEngine () Return the template engine object

Public function init () initialization function

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

The action in the controller can pass parameters to the View Script through assign.

For example

$this->view->assign('roles', $roles);$this->view->assign('num', $num);$this->view->assign('a', $a);

Or you can use

$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

Common usage in view script files:

Get passed Value

$this->roles

Use some common helper methods:

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

Common View usage examples

In the init file of the bootstrap initialization view or controller

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

In action

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

View File

List. phtml

<?php foreach ($this->data as $item) : ?>    <?php echo($item->item1);?><?php endforeach; ?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.