Zend Framework Tutorial View component Zend_view Usage _php instance

Source: Internet
Author: User

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 *
 
  
/.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 to the 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:** basePath/* scripts/* helpers/* filters/* * * @param string $path * @param string $prefix prefix to use for helper and filter paths* @return Zend_view_abstract*/publi C function Setbasepath ($path, $classPrefix = ' Zend_view ')/*** Given a base path, add script, helper, and filter paths RelA tive 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*/publi C function Addbasepath ($path, $classPrefix = ' zend_view ') public function Addscriptpath ($path) Adds to the stack of View SCR IPT paths in LIFO order.public function Setscriptpath ($path) resets the stack of view script Paths.public function Getscri Ptpath ($name) Return full path to a view script specified by $namepublic function getscriptpaths () Returns An array of all C urrently Set Script Pathspublic function Addhelperpath ($path, $classPrefix = ' zend_view_helper_ ') Adds to the stack of help Er 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 Gethelpe Rpaths () Returns An array of all currently set helper Pathspublic function Gethelper ($name) Get a helper by namepublic func tion gethelpers () Get arrAy of all active Helperspublic function getallpaths () Return associative array of path types = Pathspublic function se Tescape ($SPEC)/*** assigns variables to the view script via differing strategies.** zend_view::assign (' name ', $value) Assi GNS A variable called ' name ' * with the corresponding $value. * * Zend_view::assign ($array) assigns the array keys as VARIABL e* names (with the corresponding array values). * * @see __set () * @param string|array the assignment strategy to use.* @par Am 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 memb ER 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):?>    <?php Echo ($item->item1);? ><?php Endforeach;?>

More interested in Zend related content readers can view the topic: "Zend framework of the introductory tutorial", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Tutorial", "PHP object-oriented Programming introduction tutorial "," Introduction to Php+mysql Database Operation "and" PHP common database Operation Skills Summary "

I hope this article is helpful to you in PHP programming.

  • Related Article

    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.

    Tags Index: