Zend Framework Tutorial View component Zend_view Usage _php instance

Source: Internet
Author: User
Tags php class php foreach wrapper zend zend framework

This example describes the view component Zend_view usage of the Zend Framework tutorial. Share to everyone for your reference, specific as follows:

Zend_view is the view component of the Zend framework, the view layer in MVC. Zend_view is also a page that is applied directly to the user. Here is a description of the Zend_view implementation class, and how to combine with controller.

Realization of view

The implementation of the Zend_view is implemented primarily through classes in the following directory:

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, 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 is 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 ()->get
    Defaultmodule (); $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. The script suffix by * resetting {@link $viewSuffix}.
   The May omit the controller directory * Prefix by specifying Boolean true for $noController. * * BY default, the rendered contents are appended to the response.
   The 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 the 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 into which to search for view script * @return void */Public function render ($AC tion = null, $name = NULL, $noController = False) {if (! $this->getinvokearg (' noviewrenderer ') && $this-& Gt;_helper->hashelper (' Viewrenderer ') {return $this->_helper->viewrenderer->render ($action, $name, $n
    Ocontroller);
    $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 DERs the script passed to it. Use this if your know the * exact view script name and path you wish to use, or if using paths that does not * conform
   To the spec defined with Getviewscript (). * By default, the rendered contents are appended to the response.
   The 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, $nam E = 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 was subject to the new BSD LICENSE-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 Li
 cense@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.Z end.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.Z End.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 $_usestreamwrappe
  R = false;
   /** * constructor * Register Zend_view_stream Stream Wrapper If short tags are disabled. * @param array $config * @return void */Public function __construct ($config = Array ()) {$this->_us Eviewstream = (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 are 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 are 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 ()) {inclu De ' zend.view://'.
    Func_get_arg (0);
    else {include func_get_arg (0);

 }
  }
}

By default, the Render method is used automatically to instantiate Zend_view, and then rener to the corresponding view file by controller. Of course, you can instantiate the Zend_view yourself, and then use.

The action defaults to the same file as the action, and if you want to specify a view file, you can specify it by $this->render related methods. You can also set the directory for the view file through Addscriptpath and Setscriptpath.

For example

$view = new Zend_view ();
$view->addscriptpath ('/www/app/myviews ');
$view->addscriptpath ('/www/app/viewscomm ');
If you call $view->render (' example.php '), Zend_view will
///First Find "/www/app/myviews/example.php" and find "/www/app/" Viewscomm/example.php ", if you can't find it, finally find the" example.php "in the current directory.

Common methods of Zend_view

Public function __construct ($config = Array ())

Constructor parameters

For example

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

Common key:

Escape, encoding, BasePath, Basepathprefix, ScriptPath, Helperpath, Helperpathprefix, FilterPath, Filterpathprefix, Filter
Public Function Getengine () return the template engine object

Public function init () initialization functions

/** * Given A base path, sets 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, $class  Prefix = ' Zend_view ')/** * Given A base path, add script, helper, and filter paths relative to it * assumes directory  Structure of: * <code> * basepath/* scripts/* helpers/* filters/* </code> * * @param string $path * @param string $prefix prefix to the helper and filter paths * @return zend_view_abstract/Public Function Addbasepa Th ($path, $classPrefix = ' zend_view ') public function Addscriptpath ($path) Adds to the stack of View script paths in LIFO O
Rder.
The 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 A array of all currently set script paths public functio
N Addhelperpath ($path, $classPrefix = ' zend_view_helper_ ') Adds to the stack of Helper paths in LIFO order.
The 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 Gethelperpath S () Returns an array to all currently set helper paths Public function Gethelper ($name) get a helper by name public functio n gethelpers () get array ' All ' active helpers public Function getallpaths () return associative array of path types => p
Aths 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, * o

 R If a attempt to set a private or protected the detected/Public function assign ($spec, $value = null)

The controller action 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 it.

$this->view->roles= $roles;
$this->view->a= $a;
The 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 to current escape encoding

common usage in view script files :

Gets the value passed over

$this->roles

Some common helper methods are used:

$this->baseurl ();
$this->url ();
$this->paginationcontrol ();
$this->partial ()

Examples of common usage of views

In bootstrap initialization view or controller init file

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

/**
 *
 * @return void
/Public Function listaction ()
{
  $this->view->assign (' Data ', $data);
}

View File

List.phtml

<?php foreach ($this->data as $item):?>
<tr style= "HEIGHT:19PX;" >
    <td class= "Datagrid-cell" ><?php Echo ($item->item1);? ></td>
</tr>
<?php Endforeach;?>

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design.

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.