ホームページ バックエンド開発 PHPチュートリアル Zend Framework教程之视图组件Zend_View用法详解_php实例

Zend Framework教程之视图组件Zend_View用法详解_php实例

Jun 07, 2016 pm 05:09 PM
framework zend ビューコンポーネント

本文实例讲述了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类中,

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

/**

   * 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类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

<&#63;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') &#63; 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&#63;

   *

   * @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设置视图文件的目录。

例如

1

2

3

4

5

$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的常用方法

1

public function __construct($config = array())

ログイン後にコピー

构造函数参数

例如

1

2

3

4

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()初始化函数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

/**

* 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传递参数到视图脚本。

例如

1

2

3

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

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

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

ログイン後にコピー

或者也可以用

1

2

3

4

5

6

$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

ログイン後にコピー

视图脚本文件中的常见用法

获取传递过来的值

1

$this->roles

ログイン後にコピー

使用一些常见的助手方法:

1

2

3

4

$this->baseUrl();

$this->url();

$this->paginationControl();

$this->partial()

ログイン後にコピー

视图常见用法举例

在bootstrap初始化view或者controller的init文件中

1

2

3

4

5

6

7

8

9

/**

 * 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中

1

2

3

4

5

6

7

8

/**

 *

 * @return void

 */

public function listAction()

{

  $this->view->assign('data', $data);

}

ログイン後にコピー

视图文件

list.phtml

1

2

3

4

5

<&#63;php foreach ($this->data as $item) : &#63;>

<tr style="height: 19px;">

    <td class="datagrid-cell"><&#63;php echo($item->item1);&#63;></td>

</tr>

<&#63;php endforeach; &#63;>

ログイン後にコピー

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Microsoft NET Framework のインストールの問題エラー コード 0x800c0006 の修正 Microsoft NET Framework のインストールの問題エラー コード 0x800c0006 の修正 May 05, 2023 pm 04:01 PM

開発者とエンド ユーザーが Windows 上で最新バージョンのアプリケーションを実行するには、.NET Framework 4 が必要です。しかし、.NET Framework 4 のダウンロードとインストール中に、多くのユーザーから、インストーラーが途中で停止し、「ダウンロードがエラー コード 0x800c0006 で失敗したため、.NET Framework 4 はインストールされていません」というエラー メッセージが表示されるという苦情が寄せられました。デバイスに .NETFramework4 をインストールしているときにもこの問題が発生する場合は、正しい場所にいます。

Windows 11/10 で SetupDiag を使用して Windows アップグレードの問題を特定する方法 Windows 11/10 で SetupDiag を使用して Windows アップグレードの問題を特定する方法 Apr 17, 2023 am 10:07 AM

Windows 11 または Windows 10 PC でアップグレードまたはアップデートの問題が発生すると、通常、失敗の背後にある実際の理由を示すエラー コードが表示されます。ただし、エラー コードが表示されずにアップグレードまたはアップデートが失敗すると、混乱が生じることがあります。便利なエラー コードを使用すると、問題の場所が正確にわかるので、修正を試みることができます。ただし、エラー コードが表示されないため、問題を特定して解決することが困難になります。エラーの背後にある理由を見つけるだけでも多くの時間がかかります。この場合、Microsoft が提供する SetupDiag という専用ツールを使用すると、エラーの背後にある本当の理由を簡単に特定できます。

SCNotification が動作を停止しました [問題を解決する 5 つのステップ] SCNotification が動作を停止しました [問題を解決する 5 つのステップ] May 17, 2023 pm 09:35 PM

Windows ユーザーは、コンピュータを起動するたびに「SCNotification は動作を停止しました」というエラーに遭遇する可能性があります。 SCNotification.exe は Microsoft システム通知ファイルであり、アクセス許可エラーやネットワーク障害が原因で PC を起動するたびにクラッシュします。このエラーは、問題のあるイベント名でも知られています。したがって、これは SCNotification が動作を停止したということではなく、バグ clr20r3 として認識される可能性があります。この記事では、SCNotification が動作を停止した問題を修正して再び悩まされないようにするために必要なすべての手順を説明します。 SCNotification.eとは何ですか

Microsoft .NET Framework 4.5.2、4.6、および 4.6.1 は 2022 年 4 月にサポートを終了します Microsoft .NET Framework 4.5.2、4.6、および 4.6.1 は 2022 年 4 月にサポートを終了します Apr 17, 2023 pm 02:25 PM

Microsoft.NET バージョン 4.5.2、4.6、または 4.6.1 をインストールしている Microsoft Windows ユーザーが、将来の製品更新を通じて Microsoft にフレームワークをサポートさせることを希望する場合は、新しいバージョンの Microsoft Framework をインストールする必要があります。 Microsoft によると、3 つのフレームワークはすべて 2022 年 4 月 26 日にサポートを終了します。サポート期限が終了すると、製品は「セキュリティ修正またはテクニカル サポート」を受けられなくなります。ほとんどのホーム デバイスは、Windows アップデートを通じて最新の状態に保たれます。これらのデバイスには、.NET Framework 4.8 などの新しいバージョンのフレームワークがすでにインストールされています。自動的に更新されないデバイスは、

PHP 実装フレームワーク: Zend Framework 入門チュートリアル PHP 実装フレームワーク: Zend Framework 入門チュートリアル Jun 19, 2023 am 08:09 AM

PHP 実装フレームワーク: ZendFramework 入門チュートリアル ZendFramework は、PHP によって開発されたオープン ソースの Web サイト フレームワークであり、現在 ZendTechnologies によって保守されています。ZendFramework は、MVC デザイン パターンを採用し、Web2.0 アプリケーションと Web サーブの実装に役立つ一連の再利用可能なコード ライブラリを提供します。 。 ZendFramework は PHP 開発者に非常に人気があり、尊敬されており、幅広い機能を備えています。

Windows 11 の KB5012643 により .NET Framework 3.5 アプリが中断される Windows 11 の KB5012643 により .NET Framework 3.5 アプリが中断される May 09, 2023 pm 01:07 PM

Windows 11 に KB5012643 をインストールしたユーザーに影響を与える新しいセーフ モードのバグについてお話ししてから 1 週間が経過しました。このやっかいな問題は、Microsoft が発売日に投稿した既知の問題のリストには載っていなかったので、誰もが驚きました。さて、事態がこれ以上悪化するはずはないと思ったそのとき、Microsoft は、この累積的な更新プログラムをインストールしたユーザーに別の爆弾を投下します。 Windows 11 Build 22000.652 はさらなる問題を引き起こす そこで同社は、Windows 11 ユーザーに対し、一部の .NET Framework 3.5 アプリケーションの起動と使用に問題が発生する可能性があると警告しています。おなじみですね?でも驚かないでください

Zend Framework でのアクセス許可制御に ACL (アクセス コントロール リスト) を使用する方法 Zend Framework でのアクセス許可制御に ACL (アクセス コントロール リスト) を使用する方法 Jul 29, 2023 am 09:24 AM

Zend Framework でのアクセス許可制御に ACL (AccessControlList) を使用する方法 はじめに: Web アプリケーションでは、アクセス許可制御は重要な機能です。これにより、ユーザーはアクセスを許可されたページと機能にのみアクセスできるようになり、不正アクセスが防止されます。 Zend フレームワークは、ACL (AccessControlList) コンポーネントを使用してアクセス許可制御を実装する便利な方法を提供します。この記事では、Zend Framework で ACL を使用する方法を紹介します。

Cooler Master と Framework が、ラップトップのマザーボードと互換性のある革新的なミニケース キットを発売 Cooler Master と Framework が、ラップトップのマザーボードと互換性のある革新的なミニケース キットを発売 Dec 15, 2023 pm 05:35 PM

12月9日のニュースによると、Cooler Masterは最近、台北コンピューティングショーでのデモンストレーションイベントで、ノートブックモジュラーソリューションプロバイダーのFrameworkと協力して、ミニシャーシキットをデモしました。このキットのユニークな点は、マザーボードと互換性があり、マザーボードを取り付けることができることです。フレームワークノートから。現在、この製品は市場で販売が開始されており、価格は39ドル、現在の為替レートで約279元に相当します。このシャーシキットの型番は「frameWORKMAINBOARDCASE」となります。デザイン面では、わずか297x133x15mmという究極のコンパクトさと実用性を実現しています。そのオリジナルのデザインは、フレームワーク ノートブックにシームレスに接続できるようにすることです。

See all articles