Zend Framework教程之視圖組件Zend_View用法詳解
本文實(shí)例講述了Zend Framework教程之視圖組件Zend_View用法。分享給大家供大家參考,具體如下:
Zend_View是Zend Framework的視圖組件,MVC中的視圖層。 Zend_View也是應(yīng)用的直接對(duì)用戶展示的頁(yè)面。這里介紹一下Zend_View的實(shí)現(xiàn)類(lèi),以及如何和Controller結(jié)合在一起的。
View的實(shí)現(xiàn)
Zend_View的實(shí)現(xiàn)主要是通過(guò)如下目錄的類(lèi)實(shí)現(xiàn):
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類(lèi)中,
/** * 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 * <controller>/<action>.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類(lèi)
<?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); } } }
默認(rèn)情況會(huì)自動(dòng)通過(guò)Controller會(huì)通過(guò)render方法來(lái)實(shí)例化Zend_View, 然后rener到對(duì)應(yīng)的視圖文件中。當(dāng)然可以自己實(shí)例化Zend_View,然后使用。
action默認(rèn)指向的文件是和action的名稱相同,如果要指定視圖文件,可以通過(guò)$this->render的相關(guān)方法指定.也可以通過(guò)addScriptPath和setScriptPath設(shè)置視圖文件的目錄。
例如
$view = new Zend_View(); $view->addScriptPath('/www/app/myviews'); $view->addScriptPath('/www/app/viewscomm'); // 如果調(diào)用 $view->render('example.php'), Zend_View 將 // 首先查找 "/www/app/myviews/example.php", 找不到再找"/www/app/viewscomm/example.php", 如果還找不到,最后查找當(dāng)前目錄下/的"example.php".
Zend_View的常用方法
public function __construct($config = array())
構(gòu)造函數(shù)參數(shù)
例如
array( 'escape' => array(), 'encoding' => array(), );
常見(jiàn)key:
escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、 helperPathPrefix、filterPath、filterPathPrefix、filter
public function getEngine() Return the template engine object
public function init()初始化函數(shù)
/** * 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_View') /** * 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_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 $name public function getScriptPaths()Returns an array of all currently set script paths public 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 $name public function getHelperPaths()Returns an array of all currently set helper paths public function getHelper($name) Get a helper by name public function getHelpers()Get array of all active helpers public function getAllPaths() Return associative array of path types => paths 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, * or if an attempt to set a private or protected member is detected */ public function assign($spec, $value = null)
在controller的action可以通過(guò)assign傳遞參數(shù)到視圖腳本。
例如
$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
視圖腳本文件中的常見(jiàn)用法:
獲取傳遞過(guò)來(lái)的值
$this->roles
使用一些常見(jiàn)的助手方法:
$this->baseUrl(); $this->url(); $this->paginationControl(); $this->partial()
視圖常見(jiàn)用法舉例
在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
<?php foreach ($this->data as $item) : ?> <tr style="height: 19px;"> <td class="datagrid-cell"><?php echo($item->item1);?></td> </tr> <?php endforeach; ?>
更多關(guān)于zend相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Zend FrameWork框架入門(mén)教程》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《Yii框架入門(mén)及常用技巧總結(jié)》、《ThinkPHP入門(mén)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- Zend Framework實(shí)現(xiàn)Zend_View集成Smarty模板系統(tǒng)的方法
- Zend Framework處理Json數(shù)據(jù)方法詳解
- Zend Framework使用Zend_Loader組件動(dòng)態(tài)加載文件和類(lèi)用法詳解
- Zend Framework入門(mén)教程之Zend_Registry組件用法詳解
- Zend Framework入門(mén)教程之Zend_Config組件用法詳解
- Zend Framework過(guò)濾器Zend_Filter用法詳解
- Zend Framework實(shí)現(xiàn)自定義過(guò)濾器的方法
- php入門(mén)教程之Zend Studio設(shè)置與開(kāi)發(fā)實(shí)例
- Zend Framework開(kāi)發(fā)入門(mén)經(jīng)典教程
- Zend Framework入門(mén)教程之Zend_View組件用法示例
相關(guān)文章
PHP 表單提交及處理表單數(shù)據(jù)詳解及實(shí)例
本文章向大家介紹表單的一些知識(shí)點(diǎn),然后介紹PHP是如何接收表單數(shù)據(jù)并如何處理表單數(shù)據(jù),文章以一個(gè)發(fā)送郵件的表單實(shí)例來(lái)向大家講解表單提交及php如何處理表單數(shù)據(jù),需要的朋友可以參考下2016-12-12一個(gè)php Mysql類(lèi) 可以參考學(xué)習(xí)熟悉下
慢慢研究吧,非常適合學(xué)習(xí)的php數(shù)據(jù)庫(kù)(mysql)類(lèi),也可以拿來(lái)直接就用,稍微熟悉一下就可以啦!2009-06-06Zend Framework框架之Zend_Mail實(shí)現(xiàn)發(fā)送Email郵件驗(yàn)證功能及解決標(biāo)題亂碼的方法
這篇文章主要介紹了Zend Framework框架之Zend_Mail實(shí)現(xiàn)發(fā)送Email郵件驗(yàn)證功能及解決標(biāo)題亂碼的方法,詳細(xì)分析了Zend_Mail組件實(shí)現(xiàn)郵件發(fā)送的具體步驟,并給出了標(biāo)題亂碼的解決方法,需要的朋友可以參考下2016-03-03PHP框架Laravel學(xué)習(xí)心得體會(huì)
Laravel是一套簡(jiǎn)潔、優(yōu)雅的PHP Web開(kāi)發(fā)框架 (PHP Web Framework) 。在世界(不含中國(guó))PHP框架的占有率超過(guò)40%。下面通過(guò)本文給大家分享我的PHP框架Laravel學(xué)習(xí)心得體會(huì),歡迎大家給我留言2015-10-10php頁(yè)面,mysql數(shù)據(jù)庫(kù)轉(zhuǎn)utf-8亂碼,utf-8編碼問(wèn)題總結(jié)
一個(gè)網(wǎng)站如果需要國(guó)際化,就需要將編碼從GB2312轉(zhuǎn)成UTF-8,其中有很多的問(wèn)題需要注意,如果沒(méi)有轉(zhuǎn)換徹底,將會(huì)有很多的編碼問(wèn)題出現(xiàn)!接下來(lái)通過(guò)本篇文章給大家分享php頁(yè)面,mysql數(shù)據(jù)庫(kù)轉(zhuǎn)utf-8亂碼,utf-8編碼問(wèn)題總結(jié),需要的朋友可以參考下2015-08-08CodeIgniter采用config控制的多語(yǔ)言實(shí)現(xiàn)根據(jù)瀏覽器語(yǔ)言自動(dòng)轉(zhuǎn)換功能
這篇文章主要介紹了CodeIgniter采用config控制的多語(yǔ)言實(shí)現(xiàn)根據(jù)瀏覽器語(yǔ)言自動(dòng)轉(zhuǎn)換功能,非常實(shí)用,需要的朋友可以參考下2014-07-07Swoole-1.7.22 版本已發(fā)布,修復(fù)PHP7相關(guān)問(wèn)題
swoole-1.7.22 版本已發(fā)布,此版本是一個(gè)BUG修復(fù)版本,專門(mén)針對(duì)PHP7做了大量修改,可完美運(yùn)行于PHP7環(huán)境2015-12-12PHP實(shí)現(xiàn)多關(guān)鍵字加亮功能
關(guān)鍵字加亮可以更好的幫助閱讀,本篇文章主要PHP實(shí)現(xiàn)多關(guān)鍵字加亮功能,具有一定的參考價(jià)值,有需要的可以看一下。2016-10-10