Programmer's Reference Guide

ビュースクリプト

ビューヘルパー

ビュースクリプトの中で、複雑な関数を繰り返し実行しなければならないこともあるでしょう (例えば日付のフォーマット、フォーム要素の作成、リンクの作成など)。 このような作業を行うために、ヘルパークラスを使用できます。

ヘルパーの正体は、単なるクラスです。たとえば 'fooBar' という名前のヘルパーを使用するとしましょう。 デフォルトでは、クラス名の先頭には 'Zend_View_Helper_' がつきます (ヘルパーのパスを設定する際に、これは独自のものに変更できます)。 そしてクラス名の最後の部分がヘルパーの名前となります。 このとき、単語の先頭は大文字にしなければなりません。つまり、 ヘルパーのクラス名は Zend_View_Helper_FooBar となります。このクラスには、最低限ヘルパー名と同じ名前 (camelCase 形式にしたもの) のメソッド fooBar() が含まれていなければなりません。

注意: 大文字小文字の扱い
ヘルパー名は常に camelCase 形式となります。 つまり、最初は常に小文字となります。 クラス名は MixedCase 形式ですが、実際に実行されるメソッドは camelCase 形式となります。

注意: デフォルトのヘルパーのパス
デフォルトのヘルパーのパスは常に Zend Framework のビューヘルパーのパス、すなわち 'Zend/View/Helper/' となります。 setHelperPath() をコールして既存のパスを上書きしても、 このパスだけは残ります。これにより、 デフォルトのヘルパーは常に動作することが保証されます。

ビュースクリプト内でヘルパーを使用するには、 $this->helperName() をコールします。これをコールすると、裏側では Zend_ViewZend_View_Helper_HelperName クラスを読み込み、 そのクラスのインスタンスを作成して helperName() メソッドをコールします。 オブジェクトのインスタンスは Zend_View インスタンスの中に残り続け、 後で $this->helperName() がコールされたときには再利用されます。

付属のヘルパー

Zend_View には、はじめからいくつかのヘルパークラスが付属しています。 これらのほとんどはフォーム要素の生成に関するもので、 適切なエスケープ処理を自動的に行います。 さらに、ルートにもとづいた URLHTML の一覧を作成したり、 変数を宣言したりするものもあります。 現在付属しているヘルパーは、次のとおりです。

  • declareVars(): strictVars() を使用する際に同時に使用します。 このヘルパーを使用すると、テンプレート変数を宣言できます。 この変数は、すでにビュースクリプトで設定されているものでもいないものでもかまいません。 また、同時にデフォルト値も設定します。 このメソッドへの引数として配列を渡すとデフォルト値を設定します。 それ以外の場合は、もしその変数が存在しない場合は空文字列を設定します。

  • fieldset($name, $content, $attribs): XHTML の fieldset を作成します。$attribs に 'legend' というキーが含まれる場合、その値をフィールドセットの説明として使用します。 フィールドセットで囲む内容は、このヘルパーに渡した $content です。

  • form($name, $attribs, $content): XHTML の form を作成します。すべての $attribs はエスケープされ、form タグの XHTML 属性としてレンダリングされます。 $content が存在してその値が FALSE 以外の場合は、 その内容がフォームの開始タグと終了タグの間にレンダリングされます。 $contentFALSE (既定値) の場合は、 フォームの開始タグのみを作成します。

  • formButton($name, $value, $attribs): <button /> 要素を作成します。

  • formCheckbox($name, $value, $attribs, $options): <input type="checkbox" /> 要素を作成します。

    デフォルトでは、$value を指定せず $options が存在しなかった場合は、未チェックの値として '0' そしてチェック状態の値として '1' を使用します。 $value が渡されたけれど $options が存在しなかった場合は、 渡された値をチェック状態の値とみなします。

    $options は配列でなければなりません。 数値添字形式の配列の場合は、最初の要素がチェック状態の値となり、 その次の要素が未チェック状態の値となります。 3 番目以降の要素の内容は無視されます。 キー 'checked' および 'unChecked' を持つ連想配列を指定することもできます。

    $options を渡した場合は、$value が「チェック状態の値」と一致した場合にその要素がチェック状態だとみなされます。 チェック状態あるいは未チェック状態は、 属性 'checked' に boolean 値を渡して指定することもできます。

    これらの内容を簡単にまとめた例を示します。

    1. // '1' および '0' でチェック状態と未チェック状態を表します。これはチェックされていません
    2. echo $this->formCheckbox('foo');
    3.  
    4. // '1' および '0' でチェック状態と未チェック状態を表します。これはチェックされています
    5. echo $this->formCheckbox('foo', null, array('checked' => true));
    6.  
    7. // 'bar' および '0' でチェック状態と未チェック状態を表します。これはチェックされていません
    8. echo $this->formCheckbox('foo', 'bar');
    9.  
    10. // 'bar' および '0' でチェック状態と未チェック状態を表します。これはチェックされています
    11. echo $this->formCheckbox('foo', 'bar', array('checked' => true));
    12.  
    13. // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    14. echo $this->formCheckbox('foo', null, null, array('bar', 'baz'));
    15.  
    16. // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    17. echo $this->formCheckbox('foo', null, null, array(
    18.     'checked' => 'bar',
    19.     'unChecked' => 'baz'
    20. ));
    21.  
    22. // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされています
    23. echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz'));
    24. echo $this->formCheckbox('foo',
    25.                          null,
    26.                          array('checked' => true),
    27.                          array('bar', 'baz'));
    28.  
    29. // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    30. echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz'));
    31. echo $this->formCheckbox('foo',
    32.                          null,
    33.                          array('checked' => false),
    34.                          array('bar', 'baz'));

    どの場合についても、マークアップの先頭に hidden 要素を追加してそこに「未チェック状態」を表す値を保持します。 そうすることで、仮に未チェック状態であったとしても フォームから何らかの値が返されるようになるのです。

  • formErrors($errors, $options): エラーの表示用に、XHTML の順序なしリストを作成します。 $errors は、文字列あるいは文字列の配列となります。 $options は、リストの開始タグの属性として設定したい内容です。

    エラー出力の開始時、終了時、そして各エラーの区切りとして使用する コンテンツを指定することもできます。 そのためにはヘルパーのこれらのメソッドをコールします。

    • setElementStart($string); デフォルトは '<ul class="errors"%s"><li>' で、%s の部分には $options で指定した属性が入ります。

    • setElementSeparator($string); デフォルトは '</li><li>' です。

    • setElementEnd($string); デフォルトは '</li></ul>' です。

  • formFile($name, $attribs): type="file" /> 要素を作成します。

  • formHidden($name, $value, $attribs): <input type="hidden" /> 要素を作成します。

  • formLabel($name, $value, $attribs): <label> 要素を作成します。for 属性の値は $name に、そしてラベルのテキストは $value になります。 attribsdisable を渡すと、結果を何も返しません。

  • formMultiCheckbox($name, $value, $attribs, $options, $listsep): チェックボックスのリストを作成します。 $options は連想配列で、任意の深さにできます。 $value は単一の値か複数の値の配列で、これが $options 配列のキーにマッチします。 $listsep は、デフォルトでは HTML の改行 ("<br />") です。デフォルトでは、 この要素は配列として扱われます。 つまり、すべてのチェックボックスは同じ名前となり、 入力内容は配列形式で送信されます。

  • formPassword($name, $value, $attribs): <input type="password" /> 要素を作成します。

  • formRadio($name, $value, $attribs, $options): 一連の <input type="radio" /> 要素を、 $options の要素ごとに作成します。$options は、 ラジオボタンの値をキー、ラベルを値とする配列となります。 $value はラジオボタンの初期選択状態を設定します。

  • formReset($name, $value, $attribs): <input type="reset" /> 要素を作成します。

  • formSelect($name, $value, $attribs, $options): <select>...</select> ブロックを作成します。 $options の要素ごとに <option> を作成します。 $options は、選択肢の値をキー、 ラベルを値とする配列となります。$value は初期選択状態を設定します。

  • formSubmit($name, $value, $attribs): <input type="submit" /> 要素を作成します。

  • formText($name, $value, $attribs): <input type="text" /> 要素を作成します。

  • formTextarea($name, $value, $attribs): <textarea>...</textarea> ブロックを作成します。

  • url($urlOptions, $name, $reset): 指定したルートにもとづく URL 文字列を作成します。 $urlOptions は、そのルートで使用する キー/値 のペアの配列となります。

  • htmlList($items, $ordered, $attribs, $escape): $items で渡した内容をもとに 順序つきリストあるいは順序なしリストを作成します。 $items が多次元配列の場合は、入れ子状のリストとなります。 $escape フラグを TRUE (既定値) にすると、 各項目はビューオブジェクトに登録されているエスケープ方式でエスケープされます。 リスト内でマークアップを行いたい場合は FALSE を渡します。

これらをビュースクリプト内で使用するのはとても簡単です。 以下に例を示します。ただ単に、ヘルパーをコールするだけでよいことに注意しましょう。 読み込みやインスタンス作成は、必要に応じて自動的に行われます。

  1. // ビュースクリプト内では、$this は Zend_View のインスタンスを指します。
  2. //
  3. // select の選択肢を、変数 $countries に
  4. // array('us' => 'United States', 'il' => 'Israel', 'de' => 'Germany')
  5. // として設定済みであることにします。
  6. ?>
  7. <form action="action.php" method="post">
  8.     <p><label>メールアドレス:
  9. <?php echo $this->formText('email', 'you@example.com', array('size' => 32)) ?>
  10.     </label></p>
  11.     <p><label>国:
  12. <?php echo $this->formSelect('country', 'us', null, $this->countries) ?>
  13.     </label></p>
  14.     <p><label>メールを受け取りますか?
  15. <?php echo $this->formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?>
  16.     </label></p>
  17. </form>

ビュースクリプトの出力結果は、次のようになります。

  1. <form action="action.php" method="post">
  2.     <p><label>メールアドレス:
  3.         <input type="text" name="email" value="you@example.com" size="32" />
  4.     </label></p>
  5.     <p><label>国:
  6.         <select name="country">
  7.             <option value="us" selected="selected">United States</option>
  8.             <option value="il">Israel</option>
  9.             <option value="de">Germany</option>
  10.         </select>
  11.     </label></p>
  12.     <p><label>メールを受け取りますか?
  13.         <input type="hidden" name="opt_in" value="no" />
  14.         <input type="checkbox" name="opt_in" value="yes" checked="checked" />
  15.     </label></p>
  16. </form>

Action ビューヘルパー

Action ビューヘルパーは、 ビュースクリプトから指定したコントローラのアクションを実行し、 その結果のレスポンスオブジェクトを返します。 これは、特定のアクションが再利用可能なコンテンツを返す場合や、 いわゆる "ウィジェット風" のコンテンツを返す場合に便利です。

最終的に _forward() されたりリダイレクトされたりするアクションは使えず、 空の文字列を返します。

Action ビューヘルパーの API はコントローラアクションを起動する大半の MVC コンポーネントと同じで、action($action, $controller, $module = null, array $params = array()) のようになります。$action$controller は必須です。モジュールを省略した場合はデフォルトのモジュールを使用します。

例1 Action ビューヘルパーの基本的な使用法

たとえば CommentControllerlistAction() というメソッドがあったとしましょう。 コメント一覧を取得するために現在のリクエストからこのメソッドを起動するには、 次のようにします。

  1. <div id="sidebar right">
  2.     <div class="item">
  3.         <?php echo $this->action('list',
  4.                                  'comment',
  5.                                  null,
  6.                                  array('count' => 10)); ?>
  7.     </div>
  8. </div>

BaseUrl ヘルパー

フレームワークによって生成された大部分のURLが自動的に基底 URLを前に付加するとはいえ、 開発者はリソースへのパスを正しくするために 彼ら自身のURLの前に基底URLを付加する必要があります。

BaseUrlヘルパーの使用法は非常に簡単です:

  1. /*
  2. * 下記では、page/application の基底URLが "/mypage" であると仮定します。
  3. */
  4.  
  5. /*
  6. * 出力:
  7. * <base href="/mypage/" />
  8. */
  9. <base href="<?php echo $this->baseUrl(); ?>" />
  10.  
  11. /*
  12. * 出力:
  13. * <link rel="stylesheet" type="text/css" href="/mypage/css/base.css" />
  14. */
  15. <link rel="stylesheet" type="text/css"
  16.      href="<?php echo $this->baseUrl('css/base.css'); ?>" />

注意: 単純にする目的で、Zend_Controllerに含まれた基底 URLから、 入り口のPHPファイル (例えば、「index.php」)を剥ぎ取ります。 しかし、何かの場面では、問題を引き起こす場合があります。 問題が起きたら、固有のBaseUrlを設定するために、 $this->getHelper('BaseUrl')->setBaseUrl()を使います。

Currency Helper

Displaying localized currency values is a common task; the Zend_Currency view helper is intended to simply this task. See the Zend_Currency documentation for specifics on this localization feature. In this section, we will focus simply on usage of the view helper.

There are several ways to initiate the Currency view helper:

  • Registered, through a previously registered instance in Zend_Registry.

  • Afterwards, through the fluent interface.

  • Directly, through instantiating the class.

A registered instance of Zend_Currency is the preferred usage for this helper. Doing so, you can select the currency to be used prior to adding the adapter to the registry.

There are several ways to select the desired currency. First, you may simply provide a currency string; alternately, you may specify a locale. The preferred way is to use a locale as this information is automatically detected and selected via the HTTP client headers provided when a user accesses your application, and ensures the currency provided will match their locale.

注意: We are speaking of "locales" instead of "languages" because a language may vary based on the geographical region in which it is used. For example, English is spoken in different dialects: British English, American English, etc. As a currency always correlates to a country you must give a fully-qualified locale, which means providing both the language and region. Therefore, we say "locale" instead of "language."

例2 Registered instance

To use a registered instance, simply create an instance of Zend_Currency and register it within Zend_Registry using Zend_Currency as its key.

  1. // our example currency
  2. $currency = new Zend_Currency('de_AT');
  3. Zend_Registry::set('Zend_Currency', $currency);
  4.  
  5. // within your view
  6. echo $this->currency(1234.56);
  7. // this returns '€ 1.234,56'

If you are more familiar with the fluent interface, then you can also create an instance within your view and configure the helper afterwards.

例3 Within the view

To use the fluent interface, create an instance of Zend_Currency, call the helper without a parameter, and call the setCurrency() method.

  1. // within your view
  2. $currency = new Zend_Currency('de_AT');
  3. $this->currency()->setCurrency($currency)->currency(1234.56);
  4. // this returns '€ 1.234,56'

If you are using the helper without Zend_View then you can also use it directly.

例4 Direct usage

  1. // our example currency
  2. $currency = new Zend_Currency('de_AT');
  3.  
  4. // initiate the helper
  5. $helper = new Zend_View_Helper_Currency($currency);
  6. echo $helper->currency(1234.56); // this returns '€ 1.234,56'

As already seen, the currency() method is used to return the currency string. Just call it with the value you want to display as a currency. It also accepts some options which may be used to change the behaviour and output of the helper.

例5 Direct usage

  1. // our example currency
  2. $currency = new Zend_Currency('de_AT');
  3.  
  4. // initiate the helper
  5. $helper = new Zend_View_Helper_Currency($currency);
  6. echo $helper->currency(1234.56); // this returns '€ 1.234,56'
  7. echo $helper->currency(1234.56, array('precision' => 1));
  8. // this returns '€ 1.234,6'

For details about the available options, search for Zend_Currency's toCurrency() method.

Cycle ヘルパー

Cycleヘルパーは 一組の値を交互に切り替えるために使われます。

例6 Cycle ヘルパーの基本的な使用法

循環する要素を追加するためには、コンストラクタで指定するか、 assign(array $data)関数を使います。

  1. <?php foreach ($this->books as $book):?>
  2.   <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
  3.                                                             "#FFFFFF"))
  4.                                               ->next()?>">
  5.   <td><?php echo $this->escape($book['author']) ?></td>
  6. </tr>
  7. <?php endforeach;?>
  8.  
  9. // 後方への移動は関数に指示して割り当てます。
  10. $this->cycle()->assign(array("#F0F0F0","#FFFFFF"));
  11. $this->cycle()->prev();
  12. ?>

出力

  1. <tr style="background-color:'#F0F0F0'">
  2.    <td>First</td>
  3. </tr>
  4. <tr style="background-color:'#FFFFFF'">
  5.    <td>Second</td>
  6. </tr>

例7 2つ以上の繰り返しを利用する

2つ以上の繰り返しを利用する場合は、繰り返しの名前を指定しなければなりません。 第2パラメータを cycle メソッドで設定してください。 $this->cycle(array("#F0F0F0","#FFFFFF"),'cycle2'). setName($name)関数を使うこともできます。

  1. <?php foreach ($this->books as $book):?>
  2.   <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
  3.                                                             "#FFFFFF"))
  4.                                               ->next()?>">
  5.   <td><?php echo $this->cycle(array(1,2,3),'number')->next()?></td>
  6.   <td><?php echo $this->escape($book['author'])?></td>
  7. </tr>
  8. <?php endforeach;?>

Partial ヘルパー

Partial ビューヘルパーは、 指定したテンプレートを自分自身のスコープ内でレンダリングします。 主な使い道は、 再利用可能な部分テンプレートを変数名の競合を気にせずに使うというものです。 さらに、特定のモジュールから部分ビュースクリプトを指定できるようになります。

Partial と兄弟関係にある PartialLoop ビューヘルパーは、反復処理可能なデータを渡して その各要素に対してレンダリングを行うものです。

注意: PartialLoop カウンタ
PartialLoop ビューヘルパーは、変数を partialCounter というビューに代入します。 これは、配列の現在の位置をビュースクリプトに渡します。 これを利用すると、たとえばテーブルの行の色を一行おきに入れ替えるなどが簡単にできます。

例8 Partial の基本的な使用法

partial の基本的な使用法は、 自分自身のビューのスコープで部分テンプレートをレンダリングすることです。 次のようなスクリプトを考えてみましょう。

  1. <?php // partial.phtml ?>
  2. <ul>
  3.     <li>From: <?php echo $this->escape($this->from) ?></li>
  4.     <li>Subject: <?php echo $this->escape($this->subject) ?></li>
  5. </ul>

これを、ビュースクリプトから次のようにコールします。

  1. <?php echo $this->partial('partial.phtml', array(
  2.     'from' => 'Team Framework',
  3.     'subject' => 'view partials')); ?>

レンダリングした結果は、このようになります。

  1. <ul>
  2.     <li>From: Team Framework</li>
  3.     <li>Subject: view partials</li>
  4. </ul>

注意: モデルは何?
Partial ビューヘルパーが使用するモデルは、 次のいずれかとなります。

  • 配列。 配列を渡す場合は、連想配列形式でなければなりません。 そのキーと値のペアがビューに渡され、 キーが変数名となります。

  • toArray() メソッドを実装したオブジェクト。 そのオブジェクトの toArray() メソッドを実行した結果が、ビューオブジェクトに渡されます。

  • 標準のオブジェクト。 それ以外のオブジェクトについては、 object_get_vars() の結果 (そのオブジェクトのすべての public プロパティ) がビューオブジェクトに渡されます。

使用するモデルがオブジェクトである場合は、 それを変数の配列などに変換するのではなく オブジェクトのまま 直接 partial スクリプトに渡したくなるものでしょう。 そのためには、しかるべきヘルパーでプロパティ 'objectKey' を設定します。
  1. // オブジェクトを、変数 'model' として渡すよう通知します
  2. $view->partial()->setObjectKey('model');
  3.  
  4. // partialLoop のオブジェクトを、最終的なビュースクリプト内で
  5. // 変数 'model' として渡すよう通知します
  6. $view->partialLoop()->setObjectKey('model');
このテクニックが特に役立つのは、 Zend_Db_Table_RowsetpartialLoop() に渡すような場合です。 ビュースクリプト内で row オブジェクトに自由にアクセスでき、 そのメソッド (親の値を取得したり従属行を取得したりなど) を自在に使えるようになります。

例9 PartialLoop による反復処理可能なモデルのレンダリング

一般に、ループ内で partial を使用して特定のコンテンツを繰り返しレンダリングしたくなることもあるでしょう。 こうすることで、繰り返し表示される大量のコンテンツや複雑な表示ロジックを ひとつにまとめることができます。 しかし、この方法はパフォーマンスに影響を及ぼします。 というのも、partial ヘルパーをループ内で毎回実行することになるからです。

PartialLoop ビューヘルパーは、 この問題を解決します。これを使用すると、反復処理可能な内容 (配列、あるいは Iterator を実装したオブジェクト) をモデルに渡せるようになります。 そしてその各要素が partial スクリプトへモデルとして渡されます。 各要素の内容は、Partial ビューヘルパーが受け付ける任意の形式のモデルとできます。

次のような部分ビュースクリプトを考えます。

  1. <?php // partialLoop.phtml ?>
  2.     <dt><?php echo $this->key ?></dt>
  3.     <dd><?php echo $this->value ?></dd>

そして "モデル" はこのようになります。

  1. $model = array(
  2.     array('key' => 'Mammal', 'value' => 'Camel'),
  3.     array('key' => 'Bird', 'value' => 'Penguin'),
  4.     array('key' => 'Reptile', 'value' => 'Asp'),
  5.     array('key' => 'Fish', 'value' => 'Flounder'),
  6. );

そして、ビュースクリプト内で PartialLoop ヘルパーを実行します。

  1. <dl>
  2. <?php echo $this->partialLoop('partialLoop.phtml', $model) ?>
  3. </dl>
  1. <dl>
  2.     <dt>Mammal</dt>
  3.     <dd>Camel</dd>
  4.  
  5.     <dt>Bird</dt>
  6.     <dd>Penguin</dd>
  7.  
  8.     <dt>Reptile</dt>
  9.     <dd>Asp</dd>
  10.  
  11.     <dt>Fish</dt>
  12.     <dd>Flounder</dd>
  13. </dl>

例10 他のモジュールの Partial のレンダリング

時には partial が別のモジュールに存在することもあるでしょう。 そのモジュールの名前がわかっていれば、モジュール名を partial() あるいは partialLoop() の 2 番目の引数として渡し、 $model を 3 番目の引数に移動させることができます。

たとえば、'list' モジュールにある pager というスクリプトを使用したい場合は、 次のようにします。

  1. <?php echo $this->partial('pager.phtml', 'list', $pagerData) ?>

こうすると、特定の partial を他のモジュールで再利用できるようになります。 再利用可能な partial は、共有のビュースクリプトのパスに配置することをおすすめします。

Placeholder ヘルパー

Placeholder ビューヘルパーは、 ビュースクリプトとビューのインスタンスとの間でコンテンツを永続化させます。 それ以外の便利な機能としては次のようなものがあります。 たとえばコンテンツの集約、ビュースクリプトの内容をキャプチャして後で再利用、 コンテンツの前後へのテキストの追加 (そして集約したコンテンツ間のセパレータの追加) などです。

例11 プレースホルダの基本的な使用法

プレースホルダの基本的な使用法は、ビューのデータを永続化させることです。 Placeholder ヘルパーを起動する際にプレースホルダ名を指定し、 ヘルパーはプレースホルダコンテナオブジェクトを返します。 これを処理するなり、単純に echo するなりして使用できます。

  1. <?php $this->placeholder('foo')->set("Some text for later") ?>
  2.  
  3. <?php
  4.     echo $this->placeholder('foo');
  5.     // 出力は "Some text for later" となります
  6. ?>

例12 プレースホルダによるコンテンツの集約

プレースホルダによるコンテンツの集約も、時には便利です。 たとえば、ビュースクリプトで変数の配列を保持し、 後で表示するためのメッセージを取得しておくと、 それをどのようにレンダリングするかを後で決めることができます。

Placeholder ビューヘルパーは、 ArrayObject を継承したコンテナを使用します。 これは、配列をより高機能に操作できるものです。 さらに、コンテナに格納された内容をフォーマットするために さまざまなメソッドが用意されています。

  • setPrefix($prefix) は、 コンテンツの先頭に付加するテキストを設定します。 getPrefix() を使用すると、 その時点での設定内容を取得できます。

  • setPostfix($prefix) は、 コンテンツの末尾に付加するテキストを設定します。 getPostfix() を使用すると、 その時点での設定内容を取得できます。

  • setSeparator($prefix) は、 各コンテンツの間に挿入するテキストを設定します。 getSeparator() を使用すると、 その時点での設定内容を取得できます。

  • setIndent($prefix) は、 コンテンツの字下げ幅を設定します。 整数値を渡すと、渡された数のスペースを使用します。 文字列を渡すと、その文字列を使用します。 getIndent() を使用すると、 その時点での設定内容を取得できます。

  1. <!-- 最初のビュースクリプト -->
  2. <?php $this->placeholder('foo')->exchangeArray($this->data) ?>
  1. <!-- 後で使用するビュースクリプト -->
  2. <?php
  3. $this->placeholder('foo')->setPrefix("<ul>\n    <li>")
  4.                          ->setSeparator("</li><li>\n")
  5.                          ->setIndent(4)
  6.                          ->setPostfix("</li></ul>\n");
  7. ?>
  8.  
  9. <?php
  10.     echo $this->placeholder('foo');
  11.     // 順序なしリストをきれいに字下げして出力します
  12. ?>

Placeholder コンテナオブジェクトは ArrayObject を継承しているので、 単純にコンテナに格納するのではなく そのコンテナの特定のキーにコンテンツを格納するのも簡単です。 キーへのアクセスは、オブジェクトのプロパティか配列のキーのいずれでも可能です。

  1. <?php $this->placeholder('foo')->bar = $this->data ?>
  2. <?php echo $this->placeholder('foo')->bar ?>
  3.  
  4. <?php
  5. $foo = $this->placeholder('foo');
  6. echo $foo['bar'];
  7. ?>

例13 プレースホルダによるコンテンツのキャプチャ

時には、プレースホルダの中身を テンプレートに渡しやすいようビュースクリプトで保持することもあるでしょう。 Placeholder ビューヘルパーは、 任意のコンテンツをキャプチャして後でレンダリングできます。 そのために使用する API は次のようなものです。

  • captureStart($type, $key) は、 コンテンツのキャプチャを開始します。

    $type は、 Placeholder の定数 APPEND あるいは SET のいずれかとなります。APPEND を指定すると、キャプチャされたコンテンツが プレースホルダ内の現在のコンテンツの末尾に追加されます。 SET の場合は、 キャプチャされたコンテンツをそれ単体でプレースホルダの値として使用します (それまでに登録されていたコンテンツを上書きします)。 デフォルトの $typeAPPEND です。

    $key には、コンテンツのキャプチャ先として プレースホルダのコンテナの特定のキーを指定できます。

    captureStart() は、 captureEnd() がコールされるまで他のキャプチャをロックします。 同一のプレースホルダコンテナでキャプチャをネストすることはできません。 しようとすると例外が発生します。

  • captureEnd() は、 コンテンツのキャプチャを終了して、 captureStart() がコールされたときの指定に応じてそれをコンテナに格納します。

  1. <!-- デフォルトのキャプチャは追記モードです -->
  2. <?php $this->placeholder('foo')->captureStart();
  3. foreach ($this->data as $datum): ?>
  4. <div class="foo">
  5.     <h2><?php echo $datum->title ?></h2>
  6.     <p><?php echo $datum->content ?></p>
  7. </div>
  8. <?php endforeach; ?>
  9. <?php $this->placeholder('foo')->captureEnd() ?>
  10.  
  11. <?php echo $this->placeholder('foo') ?>
  1. <!-- 特定のキーにキャプチャします -->
  2. <?php $this->placeholder('foo')->captureStart('SET', 'data');
  3. foreach ($this->data as $datum): ?>
  4. <div class="foo">
  5.     <h2><?php echo $datum->title ?></h2>
  6.     <p><?php echo $datum->content ?></p>
  7. </div>
  8.  <?php endforeach; ?>
  9. <?php $this->placeholder('foo')->captureEnd() ?>
  10.  
  11. <?php echo $this->placeholder('foo')->data ?>

プレースホルダの具象実装

Zend Framework には、"具体的な" プレースホルダの実装が標準でいくつか含まれています。 これらはみな一般的に用いられるもので、doctype やページのタイトル、<head> の要素群などを扱います。 どのプレースホルダについても、 引数なしでコールするとその要素自身を返します。

各要素のドキュメントは、以下のリンク先で個別に扱います。

Doctype ヘルパー

正しい形式の HTML ドキュメントおよび XHTML ドキュメントには、 DOCTYPE 宣言が必要です。 覚えておくことが難しいというだけではなく、 これらは特定の要素のレンダリング方法 (たとえば、<script><style> 要素における CDATA のエスケープ方法) に影響を与えます。

Doctype ヘルパーは、以下のいずれかの形式を指定します。

  • XHTML11

  • XHTML1_STRICT

  • XHTML1_TRANSITIONAL

  • XHTML1_FRAMESET

  • XHTML1_RDFA

  • XHTML_BASIC1

  • HTML4_STRICT

  • HTML4_LOOSE

  • HTML4_FRAMESET

  • HTML5

整形式なものであれば、独自の doctype を追加できます。

Doctype ヘルパーは、 Placeholder ヘルパー の具象実装です。

例14 Doctype ヘルパーの基本的な使用法

doctype は、いつでも指定できます。 しかし、doctype によって出力を切りかえるヘルパーを使用する場合は まず doctype を設定してからでないと動作しません。もっともシンプルな使用法は、 レイアウトスクリプトの先頭で指定と出力を同時に行うことでしょう。

  1. $doctypeHelper = new Zend_View_Helper_Doctype();
  2. $doctypeHelper->doctype('XHTML1_STRICT');

そして、それをレイアウトスクリプトの先頭で表示します。

  1. <?php echo $this->doctype() ?>

例15 Doctype の取得

doctype を知りたくなったら、オブジェクトの getDoctype() をコールします。 このオブジェクトは、ヘルパーを起動した際に取得できるものです。

  1. $doctype = $view->doctype()->getDoctype();
  2. ?>

一般的な使用法としては、doctype が XHTML か否かを調べるということがあります。それ用のメソッドとしては isXhtml() があります。

  1. if ($view->doctype()->isXhtml()) {
  2.     // 何かをします
  3. }

doctype が HTML5 文書を表すかどうかチェックすることもできます。

  1. if ($view->doctype()->isHtml5()) {
  2.     // 何かをします
  3. }

例16 Open Graph プロトコルで使用する Doctype を選択

» Open Graph プロトコルを実装するには、 XHTML1_RDFA doctype を指定するでしょう。この doctype により、開発者は XHTML 文書内で» Resource Description Framework を使用できるようになります。

  1. $doctypeHelper = new Zend_View_Helper_Doctype();
  2. $doctypeHelper->doctype('XHTML1_RDFA');

'property' メタタグ属性が Open Graph プロトコル仕様の通りに使用されると、 RDFa doctype により、XHTMLでの検証が可能になります。 ビュースクリプト内部の例です。

  1. <?php echo $this->doctype('XHTML1_RDFA'); ?>
  2. <html xmlns="http://www.w3.org/1999/xhtml"
  3.       xmlns:og="http://opengraphprotocol.org/schema/">
  4. <head>
  5.    <meta property="og:type" content="musician" />

前記の例では、property に og:type を設定しました。 og は、HTMLタグで指定した Open Graph 名前空間を参照します。 content は、そのページが musician (音楽家)についてのものであることを特定します。 サポートされるプロパティについては、» Open Graph プロトコル・ドキュメント をご覧下さい。HeadMeta ヘルパーは、 それらの Open Graph プロトコルのメタタグをプログラム的に設定するために使用されるかもしれません。

これは、もし XHTML1_RDFA に設定された場合にチェックする方法です。

  1. <?php echo $this->doctype() ?>
  2. <html xmlns="http://www.w3.org/1999/xhtml"
  3.       <?php if ($view->doctype()->isRdfa()): ?>
  4.       xmlns:og="http://opengraphprotocol.org/schema/"
  5.       xmlns:fb="http://www.facebook.com/2008/fbml"
  6.       <?php endif; ?>
  7. >

Gravatar View Helper

The Gravatar view helper is used to received avatars from Gravatar's service.

例17 Basic Usage of Gravatar View Helper

  1. // From a view script (using XHTML DOCTYPE):
  2. echo $this->gravatar('example@example.com');
  3.  
  4. /* results in the following output:
  5.     <img src="http://www.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=80&d=mm&r=g" />
  6. */

注意: Of course we can configure this helper. We can change height of image (by default it is 80px), and add CSS class or other attributes to image tag. The above simply shows the most basic usage.

警告

Use a valid email address!

The email address you provide the helper should be valid. This class does not validate the address (only the rating parameter). It is recommended to validate your email address within your model layer.

例18 Advanced Usage of Gravatar View Helper

There are several ways to configure the returned gravatar. In most cases, you may either pass an array of options as a second argument to the helper, or call methods on the returned object in order to configure it.

  • The img_size option can be used to specify an alternate height; alternately, call setImgSize().

  • The secure option can be used to force usage of SSL in the returned image URI by passing a boolean true value (or disabling SSL usage by passing false). Alternately, call the setSecure() method. (By default, the setting follows the same security as the current page request.)

  • To add attributes to the image, pass an array of key/value pairs as the third argument to the helper, or call the setAttribs() method.

  1. // Within the view script (using HTML DOCTYPE)
  2. echo $this->gravatar('example@example.com',
  3.     array('imgSize' => 90, 'defaultImg' => 'monsterid', 'secure' => true),
  4.     array('class' => 'avatar', 'title' => 'Title for this image')
  5. );
  6.    
  7. // Or use mutator methods
  8. $this->gravatar()
  9.      ->setEmail('example@example.com')
  10.      ->setImgSize(90)
  11.      ->setDefaultImg(Zend_View_Helper_Gravatar::DEFAULT_MONSTERID)
  12.      ->setSecure(true)
  13.      ->setAttribs(array('class' => 'avatar', 'title' => 'Title for this image'));
  14.  
  15. /* Both generate the following output:
  16. <img class="avatar" title="Title for this image"
  17.     src="https://secure.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=90&d=monsterid&r=g" >
  18. */

Options

Zend_Service_Gravatar Options

img_size

An integer describing the height of the avatar, in pixels; defaults to "80".

default_img

Image to return if the gravatar service is unable to match the email address provided. Defaults to "mm", the "mystery man" image.

rating

Audience rating to confine returned images to. Defaults to "g"; may be one of "g", "pg", "r", or "x", in order of least offensive to most offensive.

secure

Whether or not to load the image via an SSL connection. Defaults to the what is detected from the current request.

HeadMeta ヘルパー

HTML<meta> 要素は、 HTML ドキュメントに関するメタ情報を扱います。 たとえばキーワードや文字セット、キャッシュ方式などです。 Meta タグには 'http-equiv' 形式と 'name' 形式があり、 'content' 属性が必須となります。また、 'lang' あるいは 'scheme' のいずれかの属性を含むことができます。

HeadMeta ヘルパーは、 meta タグを設定したり追加したりするための次のようなメソッドを提供します。

  • appendName($keyValue, $content, $conditionalName)

  • offsetSetName($index, $keyValue, $content, $conditionalName)

  • prependName($keyValue, $content, $conditionalName)

  • setName($keyValue, $content, $modifiers)

  • appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

  • offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)

  • prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

  • setHttpEquiv($keyValue, $content, $modifiers)

XHTML1_RDFA doctype では、Doctype ヘルパー で設定される以下のメソッドもサポートされます。

  • appendProperty($property, $content, $modifiers)

  • offsetSetProperty($index, $property, $content, $modifiers)

  • prependProperty($property, $content, $modifiers)

  • setProperty($property, $content, $modifiers)

$keyValue は 'name' あるいは 'http-equiv' キーの値を定義します。$content は 'content' キーの値を定義し、$modifiers はオプションで連想配列を指定します。この配列には 'lang' や 'scheme' といったキーが含まれます。

ヘルパーメソッド headMeta() で meta タグを設定することもできます。 このメソッドのシグネチャは headMeta($content, $keyValue, $keyType = 'name', $modifiers = array(), $placement = 'APPEND') です。$keyValue には、 $keyType ('name' あるいは 'http-equiv') で指定したキーのコンテンツを指定します。 もし doctype が XHTML1_RDFA に設定されていたら、$keyType は 'property' としても指定されるかもしれません。 $placement は 'SET' (既存の値をすべて上書きする) か 'APPEND' (スタックの最後に追加する)、 あるいは 'PREPEND' (スタックの先頭に追加する) となります。

HeadMetaappend()offsetSet()prepend()、そして set() をそれぞれオーバーライドして、上にあげた特別なメソッドを使用させるようにします。 内部的には、各項目を stdClass のトークンとして保管し、 あとで itemToString() メソッドでシリアライズします。 これはスタック内の項目についてチェックを行い、 オプションでそれを修正したものを返します。

HeadMeta ヘルパーは、 Placeholder ヘルパー の具象実装です。

例20 HeadMeta ヘルパーの基本的な使用法

meta タグは、いつでも好きなときに指定できます。 一般的には、クライアント側でのキャッシュの制御方法や SEO 用キーワードなどを指定します。

たとえば、SEO 用のキーワードを指定したい場合は 'keywords' という名前の meta タグを作成します。 そして、そのページに関連するキーワードを値として指定します。

  1. // meta タグでキーワードを指定します
  2. $this->headMeta()->appendName('keywords', 'framework, PHP, productivity');

クライアント側でのキャッシュの制御方法を指定したい場合は、 http-equiv タグを設定してルールを指定します。

  1. // クライアント側でのキャッシュを無効にします
  2. $this->headMeta()->appendHttpEquiv('expires',
  3.                                    'Wed, 26 Feb 1997 08:21:57 GMT')
  4.                  ->appendHttpEquiv('pragma', 'no-cache')
  5.                  ->appendHttpEquiv('Cache-Control', 'no-cache');

meta タグの使い方としてもうひとつよくあるのは、 コンテンツタイプや文字セット、言語を指定するものです。

  1. // コンテンツタイプと文字セットを設定します
  2. $this->headMeta()->appendHttpEquiv('Content-Type',
  3.                                    'text/html; charset=UTF-8')
  4.                  ->appendHttpEquiv('Content-Language', 'en-US');

もし HTML5 文書を提供しているなら、 このように文字セットを提示すべきです。:

  1. // HTML5 で文字セットを設定します
  2. $this->headMeta()->setCharset('UTF-8'); // <meta charset="UTF-8"> のように見えます

最後の例として、リダイレクトの前に見せるメッセージを "meta refresh" で指定するものを示します。

  1. // 3 秒後に新しい URL に移動させます
  2. $this->headMeta()->appendHttpEquiv('Refresh',
  3.                                    '3;URL=http://www.some.org/some.html');

レイアウト内で meta タグを指定し終えたら、ヘルパーの内容を出力します。

  1. <?php echo $this->headMeta() ?>

例21 XHTML1_RDFA doctype を用いた HeadMeta 使用法

Doctype ヘルパー で RDFa doctype を有功にすると、標準的な 'name' や 'http-equiv' に加えて、 HeadMeta で 'property' 属性が使えるようになります。 これは Facebook の » Open Graph プロトコル で一般的に用いられます。

例えば、Open Graph ページのタイトルと型を以下のように指定するかもしれません。

  1. $this->doctype(Zend_View_Helper_Doctype::XHTML_RDFA);
  2. $this->headMeta()->setProperty('og:title', 'my article title');
  3. $this->headMeta()->setProperty('og:type', 'article');
  4. echo $this->headMeta();
  5.  
  6. //出力です。
  7. //   <meta property="og:title" content="my article title" />
  8. //   <meta property="og:type" content="article" />

HeadScript ヘルパー

HTML<script> 要素を使用して、 クライアントサイトのスクリプトをインラインで指定したり 外部のリソースからスクリプトのコードを読み込んだりします。 HeadScript ヘルパーは、この両方の方式に対応しています。

HeadScript ヘルパーは、 以下のメソッド群によってスクリプトの設定や追加をサポートします。

  • appendFile($src, $type = 'text/javascript', $attrs = array())

  • offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())

  • prependFile($src, $type = 'text/javascript', $attrs = array())

  • setFile($src, $type = 'text/javascript', $attrs = array())

  • appendScript($script, $type = 'text/javascript', $attrs = array())

  • offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())

  • prependScript($script, $type = 'text/javascript', $attrs = array())

  • setScript($script, $type = 'text/javascript', $attrs = array())

*File() 系のメソッドでは、$src は読み込みたいリモートスクリプトの場所となります。 通常は、URL あるいはパスの形式となります。*Script() 系のメソッドでは、$script はその要素に使用したいクライアント側のスクリプトとなります。

注意: 条件コメントの設定
HeadScript では、script タグを条件コメントで囲むことができます。 そうすれば、特定のブラウザでだけスクリプトを実行しないこともできます。 これを使用するには conditional タグを設定し、条件をメソッドコール時の $attrs パラメータで渡します。

例22 Headscript で条件コメントを使う例

  1. // スクリプトを追加します
  2. $this->headScript()->appendFile(
  3.     '/js/prototype.js',
  4.     'text/javascript',
  5.     array('conditional' => 'lt IE 7')
  6. );

HeadScript はスクリプトのキャプチャも行います。 これは、クライアント側スクリプトをプログラム上で作成してから どこか別の場所で使いたい場合に便利です。 使用法は、以下の例で示します。

headScript() メソッドを使うと、 スクリプト要素を手っ取り早く追加できます。 シグネチャは headScript($mode = 'FILE', $spec, $placement = 'APPEND') です。$mode は 'FILE' あるいは 'SCRIPT' のいずれかで、 スクリプトへのリンクを指定するのかスクリプト自体を定義するのかによって切り替えます。 $spec は、リンクするスクリプトファイルあるいはスクリプトのソースとなります。 $placement は 'APPEND'、'PREPEND' あるいは 'SET' のいずれかでなければなりません。

HeadScriptappend()offsetSet()prepend()、そして set() をそれぞれオーバーライドして、上にあげた特別なメソッドを使用させるようにします。 内部的には、各項目を stdClass のトークンとして保管し、 あとで itemToString() メソッドでシリアライズします。 これはスタック内の項目についてチェックを行い、 オプションでそれを修正したものを返します。

HeadScript ヘルパーは、 Placeholder ヘルパー の具象実装です。

注意: HTML Body スクリプトでの InlineScript の使用
HTMLbody 部にスクリプトを埋め込みたい場合は、 HeadScript の姉妹版である InlineScript を使わなければなりません。 スクリプトをドキュメントの最後のほうに配置するようにすると、 ページの表示速度が向上します。特に、 サードパーティのアクセス解析用スクリプトを使用する場合などにこの効果が顕著にあらわれます。

注意: すべての属性はデフォルトで無効
デフォルトでは、HeadScript がレンダリングする <script> の属性は W3C に認められているものだけです。 'type' や 'charset'、'defer'、'language' そして 'src' が該当します。 しかし、Javascript のフレームワーク (» Dojo など) では独自の属性を用いることでその挙動を変更しています。 このような属性を許可するには、 setAllowArbitraryAttributes() メソッドを使用します。

  1. $this->headScript()->setAllowArbitraryAttributes(true);

例23 HeadScript ヘルパーの基本的な使用法

上で説明したように、新しい script タグを、好きなときに指定できます。 外部のリソースへのリンクも可能ですし、 スクリプト自体を指定することも可能です。

  1. // スクリプトを追加します
  2. $this->headScript()->appendFile('/js/prototype.js')
  3.                    ->appendScript($onloadScript);

クライアント側のスクリプトでは並び順が重要となります。 指定した並び順で出力させる必要が出てくることでしょう。 そのために使用するのが、append、prepend そして offsetSet といったディレクティブです。

  1. // スクリプトの順番を指定します
  2.  
  3. // 特定の位置を指定し、確実に最後に読み込まれるようにします
  4. $this->headScript()->offsetSetFile(100, '/js/myfuncs.js');
  5.  
  6. // scriptaculous のエフェクトを使用します (次のインデックスである 101 に追加されます)
  7. $this->headScript()->appendFile('/js/scriptaculous.js');
  8.  
  9. // でも、もととなる prototype スクリプトは常に最初に読み込まれるようにします
  10. $this->headScript()->prependFile('/js/prototype.js');

すべてのスクリプトを出力する準備が整ったら、 あとはレイアウトスクリプトでそれを出力するだけです。

  1. <?php echo $this->headScript() ?>

例24 HeadScript ヘルパーによるスクリプトのキャプチャ

時にはクライアント側のスクリプトをプログラムで生成しなければならないこともあるでしょう。 文字列の連結やヒアドキュメント等を使っても構いませんが、 ふつうにスクリプトを作成してそれを PHP のタグに埋め込めればより簡単です。 HeadScript は、スタックにキャプチャすることでこれを実現します。

  1. <?php $this->headScript()->captureStart() ?>
  2. var action = '<?php echo $this->baseUrl ?>';
  3. $('foo_form').action = action;
  4. <?php $this->headScript()->captureEnd() ?>

前提条件は次のとおりです。

  • スクリプトは、スタックの末尾に追加されていきます。 既存のスタックを上書きしたりスタックの先頭に追加したりしたい場合は、 それぞれ 'SET' あるいは 'PREPEND' を captureStart() の最初の引数として渡します。

  • スクリプトの MIME タイプは 'text/javascript' を想定しています。 別のものを指定したい場合は、それを captureStart() の 2 番目の引数として渡します。

  • <script> タグに追加の属性を指定したい場合は、 captureStart() の 3 番目の引数に配列形式で渡します。

HeadStyle ヘルパー

HTML<style> 要素を使用して、 CSS スタイルシートを HTML<head> 要素に埋め込みます。

注意: HeadLink を使用した CSS ファイルへのリンク
外部スタイルシートの読み込み用の <link> 要素を作成する場合は HeadLink を使用する必要があります。スタイルシートをインラインで定義したい場合に HeadStyle を使用します。

HeadStyle ヘルパーがサポートするメソッドは次のとおりです。 これらによってスタイルシート宣言の設定や追加を行います。

  • appendStyle($content, $attributes = array())

  • offsetSetStyle($index, $content, $attributes = array())

  • prependStyle($content, $attributes = array())

  • setStyle($content, $attributes = array())

すべての場合において、$content には実際の CSS 宣言を指定します。 $attributes には、style タグに追加したい属性があれば指定します。 lang、title、media そして dir のすべてが使用可能です。

注意: 条件コメントの設定
HeadStyle では、script タグを条件コメントで囲むことができます。 そうすれば、特定のブラウザでだけスクリプトを実行しないこともできます。 これを使用するには conditional タグを設定し、条件をメソッドコール時の $attributes パラメータで渡します。

例25 Headstyle で条件コメントを使う例

  1. // スクリプトを追加します
  2. $this->headStyle()->appendStyle($styles, array('conditional' => 'lt IE 7'));

HeadStyle はスタイル宣言のキャプチャも行います。 これは、宣言をプログラム上で作成してからどこか別の場所で使いたい場合に便利です。 使用法は、以下の例で示します。

headStyle() メソッドを使うと、宣言の要素を手っ取り早く追加できます。 シグネチャは headStyle($content$placement = 'APPEND', $attributes = array()) です。$placement には 'APPEND'、'PREPEND' あるいは 'SET' のいずれかを指定します。

HeadStyleappend()offsetSet()prepend()、そして set() をそれぞれオーバーライドして、上にあげた特別なメソッドを使用させるようにします。 内部的には、各項目を stdClass のトークンとして保管し、 あとで itemToString() メソッドでシリアライズします。 これはスタック内の項目についてチェックを行い、 オプションでそれを修正したものを返します。

HeadStyle ヘルパーは、 Placeholder ヘルパー の具象実装です。

注意: デフォルトで使用される UTF-8 エンコーディング
By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it's possible that if you are using a custom view implementation with this view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.
If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.

例26 HeadStyle ヘルパーの基本的な使用法

新しい style タグを、好きなときに指定できます。

  1. // スタイルを追加します
  2. $this->headStyle()->appendStyle($styles);

CSS では並び順が重要となります。 指定した並び順で出力させる必要が出てくることでしょう。 そのために使用するのが、append、prepend そして offsetSet といったディレクティブです。

  1. // スタイルの順番を指定します
  2.  
  3. // 特定の位置に置きます
  4. $this->headStyle()->offsetSetStyle(100, $customStyles);
  5.  
  6. // 最後に置きます
  7. $this->headStyle()->appendStyle($finalStyles);
  8.  
  9. // 先頭に置きます
  10. $this->headStyle()->prependStyle($firstStyles);

すべてのスタイル宣言を出力する準備が整ったら、 あとはレイアウトスクリプトでそれを出力するだけです。

  1. <?php echo $this->headStyle() ?>

例27 HeadStyle ヘルパーによるスタイル宣言のキャプチャ

時には CSS のスタイル宣言をプログラムで生成しなければならないこともあるでしょう。 文字列の連結やヒアドキュメント等を使っても構いませんが、 ふつうにスタイルを作成してそれを PHP のタグに埋め込めればより簡単です。 HeadStyle は、スタックにキャプチャすることでこれを実現します。

  1. <?php $this->headStyle()->captureStart() ?>
  2. body {
  3.     background-color: <?php echo $this->bgColor ?>;
  4. }
  5. <?php $this->headStyle()->captureEnd() ?>

前提条件は次のとおりです。

  • スタイル宣言は、スタックの末尾に追加されていきます。 既存のスタックを上書きしたりスタックの先頭に追加したりしたい場合は、 それぞれ 'SET' あるいは 'PREPEND' を captureStart() の最初の引数として渡します。

  • <style> タグに追加の属性を指定したい場合は、 captureStart() の 2 番目の引数に配列形式で渡します。

HeadTitle ヘルパー

HTML<title> 要素を使用して、 HTML ドキュメントのタイトルを設定します。 HeadTitle ヘルパーは、 プログラム上で作成したタイトルを保存しておいて、 後で出力の際にそれを取得するためのものです。

HeadTitle ヘルパーは、 Placeholder ヘルパー の具象実装です。 toString() メソッドをオーバーライドして <title> 要素を生成するようにしており、 headTitle() メソッドによって title 要素の設定や集約を簡単にできるようになっています。 このメソッドのシグネチャは headTitle($title, $setType = null) です。デフォルトでは、 null のままだと、値はスタック (title 部の内容を集約したもの) の最後に追加されます。しかしこれを 'PREPEND' (スタックの先頭に追加する) や 'SET' (スタック全体を上書きする) にすることもできます。

Since setting the aggregating (attach) order on each call to headTitle can be cumbersome, you can set a default attach order by calling setDefaultAttachOrder() which is applied to all headTitle() calls unless you explicitly pass a different attach order as the second parameter.

例28 HeadTitle ヘルパーの基本的な使用法

title タグは、いつでも好きなときに指定できます。 一般的な使用法としては、アプリケーション内での階層、 つまりサイト、コントローラ、アクションその他のリソースについての情報を示すことがあります。

  1. // コントローラとアクションの名前を title 部に設定します
  2. $request = Zend_Controller_Front::getInstance()->getRequest();
  3. $this->headTitle($request->getActionName())
  4.      ->headTitle($request->getControllerName());
  5.  
  6. // サイト名を title に設定します。これはレイアウトスクリプトで行うことになるでしょう
  7. $this->headTitle('Zend Framework');
  8.  
  9. // 各部分を区切る文字列を設定します
  10. $this->headTitle()->setSeparator(' / ');

最後に、レイアウトスクリプト内でタイトルをレンダリングする際にそれを出力するだけです。

  1. <!-- <アクション名> / <コントローラ名> / Zend Framework と出力されます -->
  2. <?php echo $this->headTitle() ?>

HTML オブジェクトヘルパー

HTML<object> 要素は、 Flash や QuickTime といったメディアをウェブページに埋め込むために使用するものです。 オブジェクトビューヘルパーは、 最低限の労力でメディアを埋め込めるよう手助けします。

最初は、以下の 4 つのオブジェクトヘルパーを提供します。

  • htmlFlash() は、Flash ファイルの埋め込み用のマークアップを生成します。

  • htmlObject() は、カスタムオブジェクトの埋め込み用のマークアップを生成します。

  • htmlPage() は、他の (X)HTML ページの埋め込み用のマークアップを生成します。

  • htmlQuicktime() は、QuickTime ファイルの埋め込み用のマークアップを生成します。

これらのヘルパーはすべて、同じインターフェイスを共有しています。 そのため、このドキュメントでは、そのうちの 2 つのヘルパーの例だけを紹介します。

例29 Flash ヘルパー

このヘルパーを使うと、Flash をページの中に簡単に埋め込めるようになります。 リソースの URI を引数として渡すだけの簡単な作業です。

  1. <?php echo $this->htmlFlash('/path/to/flash.swf'); ?>

この結果は、次のような HTML となります。

  1. <object data="/path/to/flash.swf"
  2.         type="application/x-shockwave-flash"
  3.         classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  4.         codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
  5. </object>

さらに、属性やパラメータ、コンテンツなど <object> とともにレンダリングする内容も指定できます。その方法は htmlObject() ヘルパーで紹介します。

例30 追加属性を渡すことによるオブジェクトのカスタマイズ

オブジェクトヘルパーの最初の引数は常に必須です。 これは、埋め込みたいリソースの URI となります。 2 番目の引数は htmlObject() ヘルパーの場合のみ必須となります。 それ以外のヘルパーはこの引数の正確な値を既に知っているからです。 3 番目の引数には、object 要素の属性を渡します。 キー/値 のペア形式の配列のみを受け付けます。 属性の例としては、たとえば classidcodebase などがあります。 4 番目の引数も同様に キー/値 のペア形式の配列のみを受け取り、 それを使用して <param> 要素を作成します。例を参照ください。 最後に、オプションでそのオブジェクトの追加コンテンツを指定できます。 これらすべての引数を使用した例をごらんください。

  1. echo $this->htmlObject(
  2.     '/path/to/file.ext',
  3.     'mime/type',
  4.     array(
  5.         'attr1' => 'aval1',
  6.         'attr2' => 'aval2'
  7.     ),
  8.     array(
  9.         'param1' => 'pval1',
  10.         'param2' => 'pval2'
  11.     ),
  12.     'some content'
  13. );
  14.  
  15. /*
  16. 出力は次のようになります
  17.  
  18. <object data="/path/to/file.ext" type="mime/type"
  19.     attr1="aval1" attr2="aval2">
  20.     <param name="param1" value="pval1" />
  21.     <param name="param2" value="pval2" />
  22.     some content
  23. </object>
  24. */

InlineScript ヘルパー

HTML<script> 要素を使用して、 クライアントサイトのスクリプトをインラインで指定したり 外部のリソースからスクリプトのコードを読み込んだりします。 InlineScript ヘルパーは、この両方の方式に対応しています。 これは HeadScript から派生したものであり、このヘルパーで使えるメソッドはすべて使用可能です。 ただ、 headScript() メソッドのかわりに inlineScript() メソッドを使用します。

注意: HTML Body スクリプトでの InlineScript の使用法
InlineScript は、スクリプトを HTMLbody 部に埋め込みたいときに使用します。 スクリプトをドキュメントの最後のほうに配置するようにすると、 ページの表示速度が向上します。特に、 サードパーティのアクセス解析用スクリプトを使用する場合などにこの効果が顕著にあらわれます。
JS ライブラリの中には、 HTMLhead で読み込まなければならないものもあります。そのような場合は HeadScript を使用します。

JSON ヘルパー

JSON を返すビューを作成する際に大事なのは、 適切なレスポンスヘッダを設定することです。 JSON ビューヘルパーは、まさにその作業を行います。 さらに、デフォルトでレイアウト機能を無効にします (現在有効である場合)。 JSON レスポンスでは通常レイアウト機能は使わないからです。

JSON ヘルパーは次のようなヘッダを設定します。

  1. Content-Type: application/json

たいていの AJAX ライブラリは、 レスポンスでこのヘッダを見つけると適切に処理してくれます。

JSON ヘルパーの使用法は、このように非常に単純です。

  1. <?php echo $this->json($this->data) ?>

注意: レイアウトの維持、およびZend_Json_Expr によるエンコードの有効化
JSON ヘルパーの各メソッドには、オプションで 2 番目の引数を指定できます。 この 2 番目の引数は、レイアウト機能の有効/無効を指定する boolean フラグか あるいは Zend_Json::encode() に渡して内部的なデータのエンコードに使用するオプションの配列となります。
レイアウトを維持するには、2 番目のパラメータを TRUE としなければなりません。 2 番目のパラメータを配列ににする場合にレイアウトを維持するには、配列に keepLayouts というキーを含め、その値を TRUE にします。

  1. // 2 番目の引数に true を指定するとレイアウトが有効になります
  2. echo $this->json($this->data, true);
  3.  
  4. // あるいは、キー "keepLayouts" に true を指定します
  5. echo $this->json($this->data, array('keepLayouts' => true));
Zend_Json::encode() は、ネイティブ JSON 式を Zend_Json_Expr オブジェクトを使用してエンコードできます。 このオプションはデフォルトでは無効になっています。 有効にするには、enableJsonExprFinder オプションに TRUE を設定します。
  1. <?php echo $this->json($this->data, array(
  2.     'enableJsonExprFinder' => true,
  3.     'keepLayouts'          => true,
  4. )) ?>

Navigation Helpers

The navigation helpers are used for rendering navigational elements from Zend_Navigation_Container instances.

There are 5 built-in helpers:

  • Breadcrumbs, used for rendering the path to the currently active page.

  • Links, used for rendering navigational head links (e.g. <link rel="next" href="..." />)

  • Menu, used for rendering menus.

  • Sitemap, used for rendering sitemaps conforming to the » Sitemaps XML format.

  • Navigation, used for proxying calls to other navigational helpers.

All built-in helpers extend Zend_View_Helper_Navigation_HelperAbstract, which adds integration with ACL and translation. The abstract class implements the interface Zend_View_Helper_Navigation_Helper, which defines the following methods:

  • getContainer() and setContainer() gets and sets the navigation container the helper should operate on by default, and hasContainer() checks if the helper has container registered.

  • getTranslator() and setTranslator() gets and sets the translator used for translating labels and titles. getUseTranslator() and setUseTranslator() controls whether the translator should be enabled. The method hasTranslator() checks if the helper has a translator registered.

  • getAcl(), setAcl(), getRole() and setRole(), gets and sets ACL (Zend_Acl) instance and role ( String or Zend_Acl_Role_Interface) used for filtering out pages when rendering. getUseAcl() and setUseAcl() controls whether ACL should be enabled. The methods hasAcl() and hasRole() checks if the helper has an ACL instance or a role registered.

  • __toString(), magic method to ensure that helpers can be rendered by echoing the helper instance directly.

  • render(), must be implemented by concrete helpers to do the actual rendering.

In addition to the method stubs from the interface, the abstract class also implements the following methods:

  • getIndent() and setIndent() gets and sets indentation. The setter accepts a String or an Integer . In the case of an Integer , the helper will use the given number of spaces for indentation. I.e., setIndent(4) means 4 initial spaces of indentation. Indentation can be specified for all helpers except the Sitemap helper.

  • getMinDepth() and setMinDepth() gets and sets the minimum depth a page must have to be included by the helper. Setting NULL means no minimum depth.

  • getMaxDepth() and setMaxDepth() gets and sets the maximum depth a page can have to be included by the helper. Setting NULL means no maximum depth.

  • getRenderInvisible() and setRenderInvisible() gets and sets whether to render items that have been marked as invisible or not.

  • __call() is used for proxying calls to the container registered in the helper, which means you can call methods on a helper as if it was a container. See example below.

  • findActive($container, $minDepth, $maxDepth) is used for finding the deepest active page in the given container. If depths are not given, the method will use the values retrieved from getMinDepth() and getMaxDepth(). The deepest active page must be between $minDepth and $maxDepth inclusively. Returns an array containing a reference to the found page instance and the depth at which the page was found.

  • htmlify() renders an 'a' HTML element from a Zend_Navigation_Page instance.

  • accept() is used for determining if a page should be accepted when iterating containers. This method checks for page visibility and verifies that the helper's role is allowed access to the page's resource and privilege.

  • The static method setDefaultAcl() is used for setting a default ACL object that will be used by helpers.

  • The static method setDefaultRole() is used for setting a default ACL that will be used by helpers

If a navigation container is not explicitly set in a helper using $helper->setContainer($nav), the helper will look for a container instance with the key Zend_Navigation in the registry. If a container is not explicitly set or found in the registry, the helper will create an empty Zend_Navigation container when calling $helper->getContainer().

例31 Proxying calls to the navigation container

Navigation view helpers use the magic method __call() to proxy method calls to the navigation container that is registered in the view helper.

  1. $this->navigation()->addPage(array(
  2.     'type' => 'uri',
  3.     'label' => 'New page'));

The call above will add a page to the container in the Navigation helper.

Translation of labels and titles

The navigation helpers support translation of page labels and titles. You can set a translator of type Zend_Translate or Zend_Translate_Adapter in the helper using $helper->setTranslator($translator), or like with other I18n-enabled components; by adding the translator to the registry by using the key Zend_Translate.

If you want to disable translation, use $helper->setUseTranslator(false).

The proxy helper will inject its own translator to the helper it proxies to if the proxied helper doesn't already have a translator.

注意: There is no translation in the sitemap helper, since there are no page labels or titles involved in an XML sitemap.

Integration with ACL

All navigational view helpers support ACL inherently from the class Zend_View_Helper_Navigation_HelperAbstract. A Zend_Acl object can be assigned to a helper instance with $helper->setAcl($acl), and role with $helper->setRole('member') or $helper->setRole(new Zend_Acl_Role('member')) . If ACL is used in the helper, the role in the helper must be allowed by the ACL to access a page's resource and/or have the page's privilege for the page to be included when rendering.

If a page is not accepted by ACL, any descendant page will also be excluded from rendering.

The proxy helper will inject its own ACL and role to the helper it proxies to if the proxied helper doesn't already have any.

The examples below all show how ACL affects rendering.

Navigation setup used in examples

This example shows the setup of a navigation container for a fictional software company.

Notes on the setup:

  • The domain for the site is www.example.com.

  • Interesting page properties are marked with a comment.

  • Unless otherwise is stated in other examples, the user is requesting the URL http://www.example.com/products/server/faq/, which translates to the page labeled FAQ under Foo Server.

  • The assumed ACL and router setup is shown below the container setup.

  1. /*
  2. * Navigation container (config/array)
  3.  
  4. * Each element in the array will be passed to
  5. * Zend_Navigation_Page::factory() when constructing
  6. * the navigation container below.
  7. */
  8. $pages = array(
  9.     array(
  10.         'label'      => 'Home',
  11.         'title'      => 'Go Home',
  12.         'module'     => 'default',
  13.         'controller' => 'index',
  14.         'action'     => 'index',
  15.         'order'      => -100 // make sure home is the first page
  16.     ),
  17.     array(
  18.         'label'      => 'Special offer this week only!',
  19.         'module'     => 'store',
  20.         'controller' => 'offer',
  21.         'action'     => 'amazing',
  22.         'visible'    => false // not visible
  23.     ),
  24.     array(
  25.         'label'      => 'Products',
  26.         'module'     => 'products',
  27.         'controller' => 'index',
  28.         'action'     => 'index',
  29.         'pages'      => array(
  30.             array(
  31.                 'label'      => 'Foo Server',
  32.                 'module'     => 'products',
  33.                 'controller' => 'server',
  34.                 'action'     => 'index',
  35.                 'pages'      => array(
  36.                     array(
  37.                         'label'      => 'FAQ',
  38.                         'module'     => 'products',
  39.                         'controller' => 'server',
  40.                         'action'     => 'faq',
  41.                         'rel'        => array(
  42.                             'canonical' => 'http://www.example.com/?page=faq',
  43.                             'alternate' => array(
  44.                                 'module'     => 'products',
  45.                                 'controller' => 'server',
  46.                                 'action'     => 'faq',
  47.                                 'params'     => array('format' => 'xml')
  48.                             )
  49.                         )
  50.                     ),
  51.                     array(
  52.                         'label'      => 'Editions',
  53.                         'module'     => 'products',
  54.                         'controller' => 'server',
  55.                         'action'     => 'editions'
  56.                     ),
  57.                     array(
  58.                         'label'      => 'System Requirements',
  59.                         'module'     => 'products',
  60.                         'controller' => 'server',
  61.                         'action'     => 'requirements'
  62.                     )
  63.                 )
  64.             ),
  65.             array(
  66.                 'label'      => 'Foo Studio',
  67.                 'module'     => 'products',
  68.                 'controller' => 'studio',
  69.                 'action'     => 'index',
  70.                 'pages'      => array(
  71.                     array(
  72.                         'label'      => 'Customer Stories',
  73.                         'module'     => 'products',
  74.                         'controller' => 'studio',
  75.                         'action'     => 'customers'
  76.                     ),
  77.                     array(
  78.                         'label'      => 'Support',
  79.                         'module'     => 'prodcts',
  80.                         'controller' => 'studio',
  81.                         'action'     => 'support'
  82.                     )
  83.                 )
  84.             )
  85.         )
  86.     ),
  87.     array(
  88.         'label'      => 'Company',
  89.         'title'      => 'About us',
  90.         'module'     => 'company',
  91.         'controller' => 'about',
  92.         'action'     => 'index',
  93.         'pages'      => array(
  94.             array(
  95.                 'label'      => 'Investor Relations',
  96.                 'module'     => 'company',
  97.                 'controller' => 'about',
  98.                 'action'     => 'investors'
  99.             ),
  100.             array(
  101.                 'label'      => 'News',
  102.                 'class'      => 'rss', // class
  103.                 'module'     => 'company',
  104.                 'controller' => 'news',
  105.                 'action'     => 'index',
  106.                 'pages'      => array(
  107.                     array(
  108.                         'label'      => 'Press Releases',
  109.                         'module'     => 'company',
  110.                         'controller' => 'news',
  111.                         'action'     => 'press'
  112.                     ),
  113.                     array(
  114.                         'label'      => 'Archive',
  115.                         'route'      => 'archive', // route
  116.                         'module'     => 'company',
  117.                         'controller' => 'news',
  118.                         'action'     => 'archive'
  119.                     )
  120.                 )
  121.             )
  122.         )
  123.     ),
  124.     array(
  125.         'label'      => 'Community',
  126.         'module'     => 'community',
  127.         'controller' => 'index',
  128.         'action'     => 'index',
  129.         'pages'      => array(
  130.             array(
  131.                 'label'      => 'My Account',
  132.                 'module'     => 'community',
  133.                 'controller' => 'account',
  134.                 'action'     => 'index',
  135.                 'resource'   => 'mvc:community.account' // resource
  136.             ),
  137.             array(
  138.                 'label' => 'Forums',
  139.                 'uri'   => 'http://forums.example.com/',
  140.                 'class' => 'external' // class
  141.             )
  142.         )
  143.     ),
  144.     array(
  145.         'label'      => 'Administration',
  146.         'module'     => 'admin',
  147.         'controller' => 'index',
  148.         'action'     => 'index',
  149.         'resource'   => 'mvc:admin', // resource
  150.         'pages'      => array(
  151.             array(
  152.                 'label'      => 'Write new article',
  153.                 'module'     => 'admin',
  154.                 'controller' => 'post',
  155.                 'aciton'     => 'write'
  156.             )
  157.         )
  158.     )
  159. );
  160.  
  161. // Create container from array
  162. $container = new Zend_Navigation($pages);
  163.  
  164. // Store the container in the proxy helper:
  165. $view->getHelper('navigation')->setContainer($container);
  166.  
  167. // ...or simply:
  168. $view->navigation($container);
  169.  
  170. // ...or store it in the reigstry:
  171. Zend_Registry::set('Zend_Navigation', $container);

In addition to the container above, the following setup is assumed:

  1. // Setup router (default routes and 'archive' route):
  2. $front = Zend_Controller_Front::getInstance();
  3. $router = $front->getRouter();
  4. $router->addDefaultRoutes();
  5. $router->addRoute(
  6.     'archive',
  7.     new Zend_Controller_Router_Route(
  8.         '/archive/:year',
  9.         array(
  10.             'module'     => 'company',
  11.             'controller' => 'news',
  12.             'action'     => 'archive',
  13.             'year'       => (int) date('Y') - 1
  14.         ),
  15.         array('year' => '\d+')
  16.     )
  17. );
  18.  
  19. // Setup ACL:
  20. $acl = new Zend_Acl();
  21. $acl->addRole(new Zend_Acl_Role('member'));
  22. $acl->addRole(new Zend_Acl_Role('admin'));
  23. $acl->add(new Zend_Acl_Resource('mvc:admin'));
  24. $acl->add(new Zend_Acl_Resource('mvc:community.account'));
  25. $acl->allow('member', 'mvc:community.account');
  26. $acl->allow('admin', null);
  27.  
  28. // Store ACL and role in the proxy helper:
  29. $view->navigation()->setAcl($acl)->setRole('member');
  30.  
  31. // ...or set default ACL and role statically:
  32. Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
  33. Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole('member');

Breadcrumbs Helper

Breadcrumbs are used for indicating where in a sitemap a user is currently browsing, and are typically rendered like this: "You are here: Home > Products > FantasticProduct 1.0". The breadcrumbs helper follows the guidelines from » Breadcrumbs Pattern - Yahoo! Design Pattern Library, and allows simple customization (minimum/maximum depth, indentation, separator, and whether the last element should be linked), or rendering using a partial view script.

The Breadcrumbs helper works like this; it finds the deepest active page in a navigation container, and renders an upwards path to the root. For MVC pages, the "activeness" of a page is determined by inspecting the request object, as stated in the section on Zend_Navigation_Page_Mvc.

The helper sets the minDepth property to 1 by default, meaning breadcrumbs will not be rendered if the deepest active page is a root page. If maxDepth is specified, the helper will stop rendering when at the specified depth (e.g. stop at level 2 even if the deepest active page is on level 3).

Methods in the breadcrumbs helper:

  • {get|set}Separator() gets/sets separator string that is used between breadcrumbs. Defualt is ' &gt; '.

  • {get|set}LinkLast() gets/sets whether the last breadcrumb should be rendered as an anchor or not. Default is FALSE.

  • {get|set}Partial() gets/sets a partial view script that should be used for rendering breadcrumbs. If a partial view script is set, the helper's render() method will use the renderPartial() method. If no partial is set, the renderStraight() method is used. The helper expects the partial to be a String or an Array with two elements. If the partial is a String , it denotes the name of the partial script to use. If it is an Array , the first element will be used as the name of the partial view script, and the second element is the module where the script is found.

  • renderStraight() is the default render method.

  • renderPartial() is used for rendering using a partial view script.

例32 Rendering breadcrumbs

This example shows how to render breadcrumbs with default settings.

  1. In a view script or layout:
  2. <?php echo $this->navigation()->breadcrumbs(); ?>
  3.  
  4. The two calls above take advantage of the magic __toString() method,
  5. and are equivalent to:
  6. <?php echo $this->navigation()->breadcrumbs()->render(); ?>
  7.  
  8. Output:
  9. <a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

例33 Specifying indentation

This example shows how to render breadcrumbs with initial indentation.

  1. Rendering with 8 spaces indentation:
  2. <?php echo $this->navigation()->breadcrumbs()->setIndent(8);?>
  3.  
  4. Output:
  5.         <a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

例34 Customize breadcrumbs output

This example shows how to customze breadcrumbs output by specifying various options.

  1. In a view script or layout:
  2.  
  3. <?php
  4. echo $this->navigation()
  5.           ->breadcrumbs()
  6.           ->setLinkLast(true)                   // link last page
  7.           ->setMaxDepth(1)                      // stop at level 1
  8.           ->setSeparator(' &#9654;' . PHP_EOL); // cool separator with newline
  9. ?>
  10.  
  11. Output:
  12. <a href="/products">Products</a> &#9654;
  13. <a href="/products/server">Foo Server</a>
  14.  
  15. /////////////////////////////////////////////////////
  16.  
  17. Setting minimum depth required to render breadcrumbs:
  18.  
  19. <?php
  20. $this->navigation()->breadcrumbs()->setMinDepth(10);
  21. echo $this->navigation()->breadcrumbs();
  22. ?>
  23.  
  24. Output:
  25. Nothing, because the deepest active page is not at level 10 or deeper.

例35 Rendering breadcrumbs using a partial view script

This example shows how to render customized breadcrumbs using a partial vew script. By calling setPartial(), you can specify a partial view script that will be used when calling render(). When a partial is specified, the renderPartial() method will be called. This method will find the deepest active page and pass an array of pages that leads to the active page to the partial view script.

In a layout:

  1. $partial = ;
  2. echo $this->navigation()->breadcrumbs()
  3.                         ->setPartial(array('breadcrumbs.phtml', 'default'));

Contents of application/modules/default/views/breadcrumbs.phtml:

  1.         create_function('$a', 'return $a->getLabel();'),
  2.         $this->pages));

Output:

  1. Products, Foo Server, FAQ

Menu Helper

The Menu helper is used for rendering menus from navigation containers. By default, the menu will be rendered using HTML UL and LI tags, but the helper also allows using a partial view script.

Methods in the Menu helper:

  • {get|set}UlClass() gets/sets the CSS class used in renderMenu().

  • {get|set}OnlyActiveBranch() gets/sets a flag specifying whether only the active branch of a container should be rendered.

  • {get|set}RenderParents() gets/sets a flag specifying whether parents should be rendered when only rendering active branch of a container. If set to FALSE, only the deepest active menu will be rendered.

  • {get|set}Partial() gets/sets a partial view script that should be used for rendering menu. If a partial view script is set, the helper's render() method will use the renderPartial() method. If no partial is set, the renderMenu() method is used. The helper expects the partial to be a String or an Array with two elements. If the partial is a String , it denotes the name of the partial script to use. If it is an Array , the first element will be used as the name of the partial view script, and the second element is the module where the script is found.

  • htmlify() overrides the method from the abstract class to return span elements if the page has no href.

  • renderMenu($container = null, $options = array()) is the default render method, and will render a container as a HTML UL list.

    If $container is not given, the container registered in the helper will be rendered.

    $options is used for overriding options specified temporarily without rsetting the values in the helper instance. It is an associative array where each key corresponds to an option in the helper.

    Recognized options:

    • indent; indentation. Expects a String or an int value.

    • minDepth; minimum depth. Expcects an int or NULL (no minimum depth).

    • maxDepth; maximum depth. Expcects an int or NULL (no maximum depth).

    • ulClass; CSS class for ul element. Expects a String .

    • onlyActiveBranch; whether only active branch should be rendered. Expects a Boolean value.

    • renderParents; whether parents should be rendered if only rendering active branch. Expects a Boolean value.

    If an option is not given, the value set in the helper will be used.

  • renderPartial() is used for rendering the menu using a partial view script.

  • renderSubMenu() renders the deepest menu level of a container's active branch.

例39 Rendering a menu

This example shows how to render a menu from a container registered/found in the view helper. Notice how pages are filtered out based on visibility and ACL.

  1. In a view script or layout:
  2. <?php echo $this->navigation()->menu()->render() ?>
  3.  
  4. Or simply:
  5. <?php echo $this->navigation()->menu() ?>
  6.  
  7. Output:
  8. <ul class="navigation">
  9.     <li>
  10.         <a title="Go Home" href="/">Home</a>
  11.     </li>
  12.     <li class="active">
  13.         <a href="/products">Products</a>
  14.         <ul>
  15.             <li class="active">
  16.                 <a href="/products/server">Foo Server</a>
  17.                 <ul>
  18.                     <li class="active">
  19.                         <a href="/products/server/faq">FAQ</a>
  20.                     </li>
  21.                     <li>
  22.                         <a href="/products/server/editions">Editions</a>
  23.                     </li>
  24.                     <li>
  25.                         <a href="/products/server/requirements">System Requirements</a>
  26.                     </li>
  27.                 </ul>
  28.             </li>
  29.             <li>
  30.                 <a href="/products/studio">Foo Studio</a>
  31.                 <ul>
  32.                     <li>
  33.                         <a href="/products/studio/customers">Customer Stories</a>
  34.                     </li>
  35.                     <li>
  36.                         <a href="/prodcts/studio/support">Support</a>
  37.                     </li>
  38.                 </ul>
  39.             </li>
  40.         </ul>
  41.     </li>
  42.     <li>
  43.         <a title="About us" href="/company/about">Company</a>
  44.         <ul>
  45.             <li>
  46.                 <a href="/company/about/investors">Investor Relations</a>
  47.             </li>
  48.             <li>
  49.                 <a class="rss" href="/company/news">News</a>
  50.                 <ul>
  51.                     <li>
  52.                         <a href="/company/news/press">Press Releases</a>
  53.                     </li>
  54.                     <li>
  55.                         <a href="/archive">Archive</a>
  56.                     </li>
  57.                 </ul>
  58.             </li>
  59.         </ul>
  60.     </li>
  61.     <li>
  62.         <a href="/community">Community</a>
  63.         <ul>
  64.             <li>
  65.                 <a href="/community/account">My Account</a>
  66.             </li>
  67.             <li>
  68.                 <a class="external" href="http://forums.example.com/">Forums</a>
  69.             </li>
  70.         </ul>
  71.     </li>
  72. </ul>

例40 Calling renderMenu() directly

This example shows how to render a menu that is not registered in the view helper by calling the renderMenu() directly and specifying a few options.

  1. <?php
  2. // render only the 'Community' menu
  3. $community = $this->navigation()->findOneByLabel('Community');
  4. $options = array(
  5.     'indent'  => 16,
  6.     'ulClass' => 'community'
  7. );
  8. echo $this->navigation()
  9.           ->menu()
  10.           ->renderMenu($community, $options);
  11. ?>
  12. Output:
  13.                 <ul class="community">
  14.                     <li>
  15.                         <a href="/community/account">My Account</a>
  16.                     </li>
  17.                     <li>
  18.                         <a class="external" href="http://forums.example.com/">Forums</a>
  19.                     </li>
  20.                 </ul>

例41 Rendering the deepest active menu

This example shows how the renderSubMenu() will render the deepest sub menu of the active branch.

Calling renderSubMenu($container, $ulClass, $indent) is equivalent to calling renderMenu($container, $options) with the following options:

  1.     'ulClass'          => $ulClass,
  2.     'indent'           => $indent,
  3.     'minDepth'         => null,
  4.     'maxDepth'         => null,
  5.     'onlyActiveBranch' => true,
  6.     'renderParents'    => false
  7. );
  1. <?php
  2. echo $this->navigation()
  3.           ->menu()
  4.           ->renderSubMenu(null, 'sidebar', 4);
  5. ?>
  6.  
  7. The output will be the same if 'FAQ' or 'Foo Server' is active:
  8.     <ul class="sidebar">
  9.         <li class="active">
  10.             <a href="/products/server/faq">FAQ</a>
  11.         </li>
  12.         <li>
  13.             <a href="/products/server/editions">Editions</a>
  14.         </li>
  15.         <li>
  16.             <a href="/products/server/requirements">System Requirements</a>
  17.         </li>
  18.     </ul>

例42 Rendering a menu with maximum depth

  1. <?php
  2. echo $this->navigation()
  3.           ->menu()
  4.           ->setMaxDepth(1);
  5. ?>
  6.  
  7. Output:
  8. <ul class="navigation">
  9.     <li>
  10.         <a title="Go Home" href="/">Home</a>
  11.     </li>
  12.     <li class="active">
  13.         <a href="/products">Products</a>
  14.         <ul>
  15.             <li class="active">
  16.                 <a href="/products/server">Foo Server</a>
  17.             </li>
  18.             <li>
  19.                 <a href="/products/studio">Foo Studio</a>
  20.             </li>
  21.         </ul>
  22.     </li>
  23.     <li>
  24.         <a title="About us" href="/company/about">Company</a>
  25.         <ul>
  26.             <li>
  27.                 <a href="/company/about/investors">Investor Relations</a>
  28.             </li>
  29.             <li>
  30.                 <a class="rss" href="/company/news">News</a>
  31.             </li>
  32.         </ul>
  33.     </li>
  34.     <li>
  35.         <a href="/community">Community</a>
  36.         <ul>
  37.             <li>
  38.                 <a href="/community/account">My Account</a>
  39.             </li>
  40.             <li>
  41.                 <a class="external" href="http://forums.example.com/">Forums</a>
  42.             </li>
  43.         </ul>
  44.     </li>
  45. </ul>

例43 Rendering a menu with minimum depth

  1. <?php
  2. echo $this->navigation()
  3.           ->menu()
  4.           ->setMinDepth(1);
  5. ?>
  6.  
  7. Output:
  8. <ul class="navigation">
  9.     <li class="active">
  10.         <a href="/products/server">Foo Server</a>
  11.         <ul>
  12.             <li class="active">
  13.                 <a href="/products/server/faq">FAQ</a>
  14.             </li>
  15.             <li>
  16.                 <a href="/products/server/editions">Editions</a>
  17.             </li>
  18.             <li>
  19.                 <a href="/products/server/requirements">System Requirements</a>
  20.             </li>
  21.         </ul>
  22.     </li>
  23.     <li>
  24.         <a href="/products/studio">Foo Studio</a>
  25.         <ul>
  26.             <li>
  27.                 <a href="/products/studio/customers">Customer Stories</a>
  28.             </li>
  29.             <li>
  30.                 <a href="/prodcts/studio/support">Support</a>
  31.             </li>