Zend Framework教程之视图组件Zend_View用法详解_php实例
本文实例讲述了Zend Framework教程之视图组件Zend_View用法。分享给大家供大家参考,具体如下:
Zend_View是Zend Framework的视图组件,MVC中的视图层。 Zend_View也是应用的直接对用户展示的页面。这里介绍一下Zend_View的实现类,以及如何和Controller结合在一起的。
View的实现
Zend_View的实现主要是通过如下目录的类实现:
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类中,
/** * 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类
<?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); } } }
默认情况会自动通过Controller会通过render方法来实例化Zend_View, 然后rener到对应的视图文件中。当然可以自己实例化Zend_View,然后使用。
action默认指向的文件是和action的名称相同,如果要指定视图文件,可以通过$this->render的相关方法指定.也可以通过addScriptPath和setScriptPath设置视图文件的目录。
例如
$view = new Zend_View(); $view->addScriptPath('/www/app/myviews'); $view->addScriptPath('/www/app/viewscomm'); // 如果调用 $view->render('example.php'), Zend_View 将 // 首先查找 "/www/app/myviews/example.php", 找不到再找"/www/app/viewscomm/example.php", 如果还找不到,最后查找当前目录下/的"example.php".
Zend_View的常用方法
public function __construct($config = array())
构造函数参数
例如
array( 'escape' => array(), 'encoding' => array(), );
常见key:
escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、 helperPathPrefix、filterPath、filterPathPrefix、filter
public function getEngine() Return the template engine object
public function init()初始化函数
/** * 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可以通过assign传递参数到视图脚本。
例如
$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
视图脚本文件中的常见用法:
获取传递过来的值
$this->roles
使用一些常见的助手方法:
$this->baseUrl(); $this->url(); $this->paginationControl(); $this->partial()
视图常见用法举例
在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; ?>
更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











.NET Framework 4는 개발자와 최종 사용자가 Windows에서 최신 버전의 애플리케이션을 실행하는 데 필요합니다. 그러나 .NET Framework 4를 다운로드하고 설치하는 동안 많은 사용자가 설치 프로그램이 중간에 중지되고 "오류 코드 0x800c0006으로 인해 다운로드에 실패했기 때문에 .NET Framework 4가 설치되지 않았습니다"라는 오류 메시지가 표시된다고 불평했습니다. 장치에 .NETFramework4를 설치하는 동안에도 이 문제가 발생한다면 올바른 위치에 있는 것입니다.

Windows 11 또는 Windows 10 PC에 업그레이드 또는 업데이트 문제가 있을 때마다 일반적으로 실패의 실제 원인을 나타내는 오류 코드가 표시됩니다. 그러나 오류 코드가 표시되지 않고 업그레이드나 업데이트가 실패하면 혼란이 발생할 수 있습니다. 편리한 오류 코드를 사용하면 문제가 어디에 있는지 정확히 알 수 있으므로 문제를 해결할 수 있습니다. 하지만 오류 코드가 나타나지 않기 때문에 문제를 식별하고 해결하기가 어렵습니다. 단순히 오류의 원인을 찾는 데 많은 시간이 걸립니다. 이 경우 오류의 실제 원인을 쉽게 식별하는 데 도움이 되는 Microsoft에서 제공하는 SetupDiag라는 전용 도구를 사용해 볼 수 있습니다.
![SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Windows 사용자는 컴퓨터를 시작할 때마다 SCNotification이 작동을 중지했습니다. 오류가 발생할 수 있습니다. SCNotification.exe는 권한 오류 및 네트워크 오류로 인해 PC를 시작할 때마다 충돌이 발생하는 Microsoft 시스템 알림 파일입니다. 이 오류는 문제가 있는 이벤트 이름으로도 알려져 있습니다. 따라서 이를 SCNotification의 작동이 중지된 것으로 표시되지 않고 버그 clr20r3으로 표시될 수 있습니다. 이 기사에서는 SCNotification이 작동을 중지하여 다시 귀찮게 하지 않도록 수정하기 위해 취해야 할 모든 단계를 살펴보겠습니다. SCNotification.e는 무엇입니까

Microsoft.NET 버전 4.5.2, 4.6 또는 4.6.1을 설치한 Microsoft Windows 사용자가 Microsoft에서 향후 제품 업데이트를 통해 프레임워크를 지원하도록 하려면 최신 버전의 Microsoft Framework를 설치해야 합니다. Microsoft에 따르면 세 가지 프레임워크 모두 2022년 4월 26일에 지원이 중단됩니다. 지원 날짜가 종료되면 해당 제품은 "보안 수정 또는 기술 지원"을 받을 수 없습니다. 대부분의 가정용 장치는 Windows 업데이트를 통해 최신 상태로 유지됩니다. 이러한 장치에는 .NET Framework 4.8과 같은 최신 버전의 프레임워크가 이미 설치되어 있습니다. 자동으로 업데이트되지 않는 장치는

Windows 11용 KB5012643을 설치한 사용자에게 영향을 미치는 새로운 안전 모드 버그에 대해 이야기한 지 일주일이 지났습니다. 이 성가신 문제는 Microsoft가 출시일에 게시한 알려진 문제 목록에 나타나지 않아 모두를 놀라게 했습니다. 글쎄, 상황이 더 이상 악화될 수 없다고 생각했을 때 Microsoft는 이 누적 업데이트를 설치한 사용자에게 또 다른 폭탄을 떨어뜨렸습니다. Windows 11 빌드 22000.652로 인해 더 많은 문제 발생 따라서 기술 회사는 Windows 11 사용자에게 일부 .NET Framework 3.5 응용 프로그램을 시작하고 사용하는 데 문제가 발생할 수 있다고 경고합니다. 익숙한 것 같나요? 하지만 놀라지 마세요.

Zend Framework에서 권한 제어를 위해 ACL(AccessControlList)을 사용하는 방법 소개: 웹 애플리케이션에서 권한 제어는 중요한 기능입니다. 이는 사용자가 액세스 권한이 있는 페이지와 기능에만 액세스할 수 있도록 하고 무단 액세스를 방지합니다. Zend 프레임워크는 ACL(AccessControlList) 구성 요소를 사용하여 권한 제어를 구현하는 편리한 방법을 제공합니다. 이 기사에서는 Zend Framework에서 ACL을 사용하는 방법을 소개합니다.

PHP 구현 프레임워크: ZendFramework 입문 튜토리얼 ZendFramework는 PHP에서 개발하고 현재 ZendTechnologies에서 유지 관리하는 오픈 소스 웹 사이트 프레임워크입니다. ZendFramework는 MVC 디자인 패턴을 채택하고 Web2.0 애플리케이션 및 Web Serve 구현을 지원하기 위한 재사용 가능한 코드 라이브러리 시리즈를 제공합니다. ZendFramework는 PHP 개발자들에게 매우 인기 있고 존경받고 있으며 다양한 기능을 갖추고 있습니다.

12월 9일 뉴스에 따르면 Cooler Master는 최근 타이페이 컴퓨트 쇼(Taipei Compute Show)의 시연 행사에서 노트북 모듈 솔루션 제공업체인 Framework와 협력하여 미니 섀시 키트를 시연했습니다. 프레임워크 노트북에서. 현재 이 제품은 시중에 판매되기 시작했으며 가격은 39달러로 현재 환율로 약 279위안(한화 약 279위안)에 해당한다. 이 섀시 키트의 모델 번호는 "frameWORKMAINBOARDCASE"로 명명됩니다. 디자인 측면에서는 297x133x15mm 크기로 최고의 컴팩트함과 실용성을 구현합니다. 원래 디자인은 프레임워크 노트북에 원활하게 연결할 수 있도록 하는 것입니다.
