Zend Framework View Component Zend_view

Source: Internet
Author: User
Tags php class php foreach zend framework
This article mainly introduces the Zend Framework Tutorial View component Zend_view Usage, a more detailed analysis of the attempt to zend_view principle of the component and the use of examples to analyze the zend_view of using skills, the need for friends can refer to the following

This example describes the Zend Framework Tutorial View component Zend_view usage. Share to everyone for your reference, as follows:

Zend_view is the view component of the Zend framework, the view layer in MVC. Zend_view is also a page that the app directly displays to the user. Here's an introduction to Zend_view's implementation class and how to combine it with a controller.

Implementation of view

The implementation of Zend_view is mainly implemented by classes of the following directories:

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 th   E same level as the * Controller directory of the current module as the base directory. * It uses this to set the following: *-Script PATH = views/scripts/*-Helper Path = views/helpers/*-Filter PA th = 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->_helpe    R->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 ()->getd    Efaultmodule (); } $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 is found in the view script path as * <controller>/<action>.phtml. The script suffix by * resetting {@link $viewSuffix}.   Omit the Controller directory * Prefix by specifying Boolean true for $noController. * By default, the rendered contents is appended toThe response.   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 ($actio n = null, $name = NULL, $noController = False) {if (! $this->getinvokearg (' noviewrenderer ') && $this->_h Elper->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 Rende Rs the script passed to it.  Use this if you know the * exact view script name and path of wish to use, or if using paths that does not * conform to   The spec defined with Getviewscript (). * By default, the rendered contents is appended to the response.   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 = n      ull) {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 that's bundled * with Thi s 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 do no T receive a copy of the license and is unable to * obtain it through the World-wide-web, please send a mail * to Licens e@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 1 7: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  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 = f  Alse;   /** * Constructor * * Register zend_view_stream Stream Wrapper If short tags is disabled. * * @param array $config * @return void */Public function __construct ($config = Array ()) {$this->_useviews Tream = (bool) ini_get (' Short_open_tag ')?    False:true; if ($this->_useviewstream) {if (!in_array (' Zend.view ', Stream_get_wrappers ())) {require_once ' zend/view/s        Tream.php ';      Stream_wrapper_register (' Zend.view ', ' zend_view_stream '); }} if (Array_key_exists (' Usestreamwrapper ', $config)) {$this->setusestreamwrapper ($config [' Usestreamwrappe    R ']);  } parent::__construct ($config); }/** * SetFlag 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, the controller automatically instantiates the Zend_view through the Render method, and then rener to the corresponding view file. Of course, you can instantiate the Zend_view yourself, and then use.

The action by default points to the same file as the action, and if you want to specify a view file, you can specify it by using the $this->render method. 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 the call $view->render (' example.php '), Zend_view will//First look for "/www/app/myviews/example.php", Can not find "/www/app/viewscomm /example.php ", if not found, finally find" 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 function

/*** 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_v Iew ')/*** 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_v Iew ') Public function Addscriptpath ($path) Adds to the stack of view script paths in LIFO order.public function Setscriptpat H ($path) resets the stack of view script Paths.public function Getscriptpath ($name) Return full path to a view script Speci Fied 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 F Ile specified by $namepublic function gethelperpaths () Returns A array of all currently set helper Pathspublic function ge Thelper ($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 SCR  IPT 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). * * @s EE __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 Controller's action can pass parameters to the view script via assign.

For example

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

Or it can be used

$this->view->roles= $roles, $this->view->a= $a;p ublic 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 ($e ncoding) Set encoding to use with htmlentities () and htmlspecialchars () public Function getencoding (): Return Current ESCAP E encoding

Common uses in view script files :

Gets the value passed over

$this->roles

Use some of the common helper methods:

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

Examples of common uses of views

In the init file of the bootstrap initialization view or controller

/** * Initialize The Common view helper */protected function _initviewhelper () {  $boot = $this->bootstrap (' View '); c1/> $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): ><tr style= "HEIGHT:19PX;" >    <td class= "Datagrid-cell" ><?php Echo ($item->item1);? ></td></tr><?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.