ビューヘルパー

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

ヘルパーの正体は、単なるクラスです。たとえば '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 が存在しなかった場合は、 渡された値をチェック状態の値とみなします。 チェックボックスをレンダリングする前に hidden 入力要素をレンダリングすることにより、 unchecked 値を実装します。

    $options は配列でなければなりません。 数値添字形式の配列の場合は、最初の要素がチェック状態の値となり、 その次の要素が未チェック状態の値となります。 3 番目以降の要素の内容は無視されます。 キー 'checked' および 'unChecked' を持つ連想配列を指定することもできます。 unchecked 値に対して hidden フィールドをレンダリングすることを防ぐには、 キー 'disableHidden' を true に設定できます。

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

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

    // '1' および '0' でチェック状態と未チェック状態を表します。これはチェックされていません
    echo $this->formCheckbox('foo');
    
    // '1' および '0' でチェック状態と未チェック状態を表します。これはチェックされています
    echo $this->formCheckbox('foo', null, array('checked' => true));
    
    // 'bar' および '0' でチェック状態と未チェック状態を表します。これはチェックされていません
    echo $this->formCheckbox('foo', 'bar');
    
    // 'bar' および '0' でチェック状態と未チェック状態を表します。これはチェックされています
    echo $this->formCheckbox('foo', 'bar', array('checked' => true));
    
    // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    echo $this->formCheckbox('foo', null, null, array('bar', 'baz'));
    
    // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    echo $this->formCheckbox('foo', null, null, array(
        'checked' => 'bar',
        'unChecked' => 'baz'
    ));
    
    // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされています
    echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz'));
    echo $this->formCheckbox('foo',
                             null,
                             array('checked' => true),
                             array('bar', 'baz'));
    
    // 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
    echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz'));
    echo $this->formCheckbox('foo',
                             null,
                             array('checked' => false),
                             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" /> 要素を作成します。

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

    echo $this->formImage(
        'foo',
        'bar',
        array(
            'src' => 'images/button.png',
            'alt' => 'Button',
        )
    );
    // 出力: <input type="image" name="foo" id="foo" src="images/button.png" value="bar" alt="Button" />
    
  • formLabel($name, $value, $attribs): <label> 要素を作成します。for 属性の値は $name に、そしてラベルのテキストは $value になります。 attribsdisable を渡すと、結果を何も返しません。

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

    // リスト・セパレーター ($listsep) を使用:
    
    echo '<ul><li>';
    echo $view->formMultiCheckbox(
        'foo',
        2,
        array(
            'class' => 'baz',
        ),
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        ),
        "</li>\n<li>"
    );
    echo '</li></ul>';
    
    /*
    出力:
    <ul>
        <li>
            <label for="foo-1">
                <input type="checkbox" name="foo[]" id="foo-1" value="1" class="baz" />One
            </label>
        </li>
        <li>
            <label for="foo-2">
                <input type="checkbox" name="foo[]" id="foo-2" value="2" checked="checked" class="baz" />Two
            </label>
        </li>
        <li>
            <label for="foo-3">
                <input type="checkbox" name="foo[]" id="foo-3" value="3" class="baz" />Three</label>
            </li>
        </ul>
    */
    
    // ラベル要素に対してオプションを使用:
    echo $this->formMultiCheckbox(
        'foo',
        2,
        array(
            'label_placement' => 'prepend',
            'label_class'     => 'baz',
        ),
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        )
    );
    
    /*
    出力:
    <label class="baz" for="foo-1">
        One<input type="checkbox" name="foo[]" id="foo-1" value="1" />
    </label>
    <br />
    <label class="baz" for="foo-2">
        Two<input type="checkbox" name="foo[]" id="foo-2" value="2" checked="checked" />
    </label>
    <br />
    <label class="baz" for="foo-3">
        Three<input type="checkbox" name="foo[]" id="foo-3" value="3" />
    </label>
    */
    
  • formNote($name, $value = null): 単純なテキスト・ノートを作成。例えば、 Zend_Form オブジェクトの見出しに対する要素として。

    echo $this->formNote(null, 'This is an example text.');
    // 出力: This is an example text.
    
  • formPassword($name, $value, $attribs): <input type="password" /> 要素を作成します。

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

    // リスト・セパレーター ($listsep) を使用
    
    echo '<ul><li>';
    echo $this->formRadio(
        'foo',
        2,
        array(
            'class' => 'baz',
        ),
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        ),
        "</li>\n<li>"
    );
    echo '</li></ul>';
    
    /*
    出力:
    <ul>
        <li>
            <label for="foo-1">
                <input type="radio" name="foo" id="foo-1" value="1" class="baz" />One
            </label>
        </li>
        <li>
            <label for="foo-2">
                <input type="radio" name="foo" id="foo-2" value="2" checked="checked" class="baz" />Two
            </label>
        </li>
        <li>
            <label for="foo-3">
                <input type="radio" name="foo" id="foo-3" value="3" class="baz" />Three
            </label>
        </li>
    </ul>
    */
    
    // ラベル要素に対してオプションを使用:
    
    echo $this->formRadio(
        'foo',
        2,
        array(
            'label_placement' => 'prepend',
            'label_class'     => 'baz',
        ),
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        )
    );
    
    /*
    出力:
    <label class="baz" for="foo-1">
        One<input type="radio" name="foo" id="foo-1" value="1" />
    </label>
    <br />
    <label class="baz" for="foo-2">
        Two<input type="radio" name="foo" id="foo-2" value="2" checked="checked" />
    </label>
    <br />
    <label class="baz" for="foo-3">
        Three<input type="radio" name="foo" id="foo-3" value="3" />
    </label>
    */
    
  • formReset($name, $value, $attribs): <input type="reset" /> 要素を作成します。

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

    // オプション・グループを使用:
    
    echo $view->formSelect(
        'foo',
        2,
        array(
            'class' => 'baz',
        ),
        array(
            1     => 'One',
            'Two' => array(
                '2.1' => 'One',
                '2.2' => 'Two',
                '2.3' => 'Three',
            ),
            3     => 'Three',
        )
    );
    
    /*
    出力:
    <select name="foo" id="foo" class="baz">
        <option value="1" label="One">One</option>
        <optgroup id="foo-optgroup-Two" label="Two">
            <option value="2.1" label="One">One</option>
            <option value="2.2" label="Two">Two</option>
            <option value="2.3" label="Three">Three</option>
        </optgroup>
        <option value="3" label="Three">Three</option>
    </select>
    */
    
    // 'multiple' オプションの例その1:
    
    echo $this->formSelect(
        'foo[]',
        2,
        null,
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        )
    );
    
    /*
    出力:
    <select name="foo[]" id="foo" multiple="multiple">
        <option value="1" label="One">One</option>
        <option value="2" label="Two" selected="selected">Two</option>
        <option value="3" label="Three">Three</option>
    </select>
    */
    
    // 'multiple' オプションの例その2:
    
    echo $this->formSelect(
        'foo',
        array(
            1,
            2,
        ),
        array(
            'multiple' => true,
        ),
        array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
        )
    );
    
    /*
    出力:
    <select name="foo[]" id="foo" multiple="multiple">
        <option value="1" label="One" selected="selected">One</option>
        <option value="2" label="Two" selected="selected">Two</option>
        <option value="3" label="Three">Three</option>
    </select>
    */
    
  • formSubmit($name, $value, $attribs): <input type="submit" /> 要素を作成します。

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

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

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

    // オプション無しで使用: (現行のリクエスト: user/id/1)
    echo $this->url();
    // 出力: user/info/id/1
    
    // URL オプションを設定:
    echo $this->url(
        array('controller' => 'user', 'action' => 'info', 'username' => 'foobar')
    );
    // 出力: user/info/username/foobar
    
    // ルートを使用:
    $router->addRoute(
        'user',
        new Zend_Controller_Router_Route(
            'user/:username',
            array(
                'controller' => 'user',
                'action'     => 'info',
            )
        )
    );
    
    echo $this->url(array('name' => 'foobar'), 'user');
    // 出力: user/foobar
    
    // リセットを使用: (現行のリクエスト: user/id/1)
    echo $this->url(array('controller' => 'user', 'action' => 'info'), null, false);
    // 出力: user/info/id/1
    
    echo $this->url(array('controller' => 'user', 'action' => 'info'), null, true);
    // 出力: user/info
    
    // エンコードを使用:
    echo $this->url(
        array('controller' => 'user', 'action' => 'info', 'username' => 'John Doe'), null, true, false
    );
    // 出力: user/info/username/John Doe
    
    echo $this->url(
        array('controller' => 'user', 'action' => 'info', 'username' => 'John Doe'), null, true, false
    );
    // 出力: user/info/username/John+Doe
    
  • serverUrl($requestUri = null): 現行のサーバーの URL、および任意でリクエスト URI を返すヘルパー。

    // この例の現行のサーバー URL: http://www.example.com/foo.html
    
    echo $this->serverUrl();
    // 出力: http://www.example.com
    
    echo $this->serverUrl(true);
    // 出力: http://www.example.com/foo.html
    
    echo $this->serverUrl('/foo/bar');
    // 出力: http://www.example.com/foo/bar
    
    echo $this->serverUrl()->getHost();
    // 出力: www.example.com
    
    echo $this->serverUrl()->getScheme();
    // 出力: http
    
    $this->serverUrl()->setHost('www.foo.com');
    $this->serverUrl()->setScheme('https');
    echo $this->serverUrl();
    // 出力: https://www.foo.com
    
  • htmlList($items, $ordered, $attribs, $escape): $items で渡した内容をもとに 順序つきリストあるいは順序なしリストを作成します。 $items が多次元配列の場合は、入れ子状のリストとなります。 $escape フラグを TRUE (既定値) にすると、 各項目はビューオブジェクトに登録されているエスケープ方式でエスケープされます。 リスト内でマークアップを行いたい場合は FALSE を渡します。

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

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

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

<form action="action.php" method="post">
    <p><label>メールアドレス:
        <input type="text" name="email" value="you@example.com" size="32" />
    </label></p>
    <p><label>国:
        <select name="country">
            <option value="us" selected="selected">United States</option>
            <option value="il">Israel</option>
            <option value="de">Germany</option>
        </select>
    </label></p>
    <p><label>メールを受け取りますか?
        <input type="hidden" name="opt_in" value="no" />
        <input type="checkbox" name="opt_in" value="yes" checked="checked" />
    </label></p>
</form>

Action ビューヘルパー

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

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

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

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

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

<div id="sidebar right">
    <div class="item">
        <?php echo $this->action('list',
                                 'comment',
                                 null,
                                 array('count' => 10)); ?>
    </div>
</div>

BaseUrl ヘルパー

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

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

/*
 * 下記では、page/application の基底URLが "/mypage" であると仮定します。
 */

/*
 * 出力:
 * <base href="/mypage/" />
 */
<base href="<?php echo $this->baseUrl(); ?>" />

/*
 * 出力:
 * <link rel="stylesheet" type="text/css" href="/mypage/css/base.css" />
 */
<link rel="stylesheet" type="text/css"
     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."

例949 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.

// our example currency
$currency = new Zend_Currency('de_AT');
Zend_Registry::set('Zend_Currency', $currency);

// within your view
echo $this->currency(1234.56);
// 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.

例950 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.

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

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

例951 Direct usage

// our example currency
$currency = new Zend_Currency('de_AT');

// initiate the helper
$helper = new Zend_View_Helper_Currency($currency);
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.

例952 Direct usage

// our example currency
$currency = new Zend_Currency('de_AT');

// initiate the helper
$helper = new Zend_View_Helper_Currency($currency);
echo $helper->currency(1234.56); // this returns '€ 1.234,56'
echo $helper->currency(1234.56, array('precision' => 1));
// this returns '€ 1.234,6'

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

Cycle ヘルパー

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

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

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

<?php foreach ($this->books as $book):?>
  <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
                                                            "#FFFFFF"))
                                              ->next()?>">
  <td><?php echo $this->escape($book['author']) ?></td>
</tr>
<?php endforeach;?>

// 後方への移動は関数に指示して割り当てます。
$this->cycle()->assign(array("#F0F0F0","#FFFFFF"));
$this->cycle()->prev();
?>

出力

<tr style="background-color:'#F0F0F0'">
   <td>First</td>
</tr>
<tr style="background-color:'#FFFFFF'">
   <td>Second</td>
</tr>

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

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


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

Partial ヘルパー

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

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

PartialLoop カウンタ

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

例955 Partial の基本的な使用法

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

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

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

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

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

<ul>
    <li>From: Team Framework</li>
    <li>Subject: view partials</li>
</ul>

モデルは何?

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

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

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

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

使用するモデルがオブジェクトである場合は、 それを変数の配列などに変換するのではなく オブジェクトのまま 直接 partial スクリプトに渡したくなるものでしょう。 そのためには、しかるべきヘルパーでプロパティ 'objectKey' を設定します。

// オブジェクトを、変数 'model' として渡すよう通知します
$view->partial()->setObjectKey('model');

// partialLoop のオブジェクトを、最終的なビュースクリプト内で
// 変数 'model' として渡すよう通知します
$view->partialLoop()->setObjectKey('model');

このテクニックが特に役立つのは、 Zend_Db_Table_RowsetpartialLoop() に渡すような場合です。 ビュースクリプト内で row オブジェクトに自由にアクセスでき、 そのメソッド (親の値を取得したり従属行を取得したりなど) を自在に使えるようになります。

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

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

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

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

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

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

$model = array(
    array('key' => 'Mammal', 'value' => 'Camel'),
    array('key' => 'Bird', 'value' => 'Penguin'),
    array('key' => 'Reptile', 'value' => 'Asp'),
    array('key' => 'Fish', 'value' => 'Flounder'),
);

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

<dl>
<?php echo $this->partialLoop('partialLoop.phtml', $model) ?>
</dl>
<dl>
    <dt>Mammal</dt>
    <dd>Camel</dd>

    <dt>Bird</dt>
    <dd>Penguin</dd>

    <dt>Reptile</dt>
    <dd>Asp</dd>

    <dt>Fish</dt>
    <dd>Flounder</dd>
</dl>

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

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

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

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

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


Placeholder ヘルパー

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

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

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

<?php $this->placeholder('foo')->set("Some text for later") ?>

<?php
    echo $this->placeholder('foo');
    // 出力は "Some text for later" となります
?>

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

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

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

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

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

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

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

<!-- 最初のビュースクリプト -->
<?php $this->placeholder('foo')->exchangeArray($this->data) ?>
<!-- 後で使用するビュースクリプト -->
<?php
$this->placeholder('foo')->setPrefix("<ul>\n    <li>")
                         ->setSeparator("</li><li>\n")
                         ->setIndent(4)
                         ->setPostfix("</li></ul>\n");
?>

<?php
    echo $this->placeholder('foo');
    // 順序なしリストをきれいに字下げして出力します
?>

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

<?php $this->placeholder('foo')->bar = $this->data ?>
<?php echo $this->placeholder('foo')->bar ?>

<?php
$foo = $this->placeholder('foo');
echo $foo['bar'];
?>

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

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

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

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

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

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

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

<!-- デフォルトのキャプチャは追記モードです -->
<?php $this->placeholder('foo')->captureStart();
foreach ($this->data as $datum): ?>
<div class="foo">
    <h2><?php echo $datum->title ?></h2>
    <p><?php echo $datum->content ?></p>
</div>
<?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>

<?php echo $this->placeholder('foo') ?>
<!-- 特定のキーにキャプチャします -->
<?php $this->placeholder('foo')->captureStart('SET', 'data');
foreach ($this->data as $datum): ?>
<div class="foo">
    <h2><?php echo $datum->title ?></h2>
    <p><?php echo $datum->content ?></p>
</div>
 <?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>

<?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 ヘルパー の具象実装です。

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

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

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

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

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

例962 Doctype の取得

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

$doctype = $view->doctype()->getDoctype();
?>

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

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

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

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

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

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

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

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

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

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

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

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

Gravatar View Helper

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

例964 Basic Usage of Gravatar View Helper

// From a view script (using XHTML DOCTYPE):
echo $this->gravatar('example@example.com');

/* results in the following output:
    <img src="http://www.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=80&d=mm&r=g" />
 */

注記

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.

例965 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.

// Within the view script (using HTML DOCTYPE)
echo $this->gravatar('example@example.com',
    array('imgSize' => 90, 'defaultImg' => 'monsterid', 'secure' => true),
    array('class' => 'avatar', 'title' => 'Title for this image')
);
    
// Or use mutator methods
$this->gravatar()
     ->setEmail('example@example.com')
     ->setImgSize(90)
     ->setDefaultImg(Zend_View_Helper_Gravatar::DEFAULT_MONSTERID)
     ->setSecure(true)
     ->setAttribs(array('class' => 'avatar', 'title' => 'Title for this image'));

/* Both generate the following output:
<img class="avatar" title="Title for this image"
    src="https://secure.gravatar.com/avatar/23463b99b62a72f26ed677cc556c44e8?s=90&d=monsterid&r=g" >
 */

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.

HeadLink ヘルパー

注意:このドキュメントでは、英語版のリビジョン 19438 の更新内容をスキップしています。

HTML<link> 要素は複数使用することができ、 スタイルシートやフィード、favicon、トラックバック などのさまざまなリソースへのリンクを表します。 HeadLink ヘルパーは、 シンプルなインターフェイスでこれらの要素を作成し、 後でそれを取得してレイアウトスクリプトで出力することができます。

HeadLink ヘルパーには、 スタイルシートへのリンクをスタックに追加するメソッドがあります。

  • appendStylesheet($href, $media, $conditionalStylesheet, $extras)

  • offsetSetStylesheet($index, $href, $media, $conditionalStylesheet, $extras)

  • prependStylesheet($href, $media, $conditionalStylesheet, $extras)

  • setStylesheet($href, $media, $conditionalStylesheet, $extras)

$media のデフォルトは 'screen' ですが、 有効な media 形式なら何にでもすることができます。 $conditionalStylesheet は文字列あるいは FALSE で、 レンダリング時に使用します。 特定のプラットフォームでスタイルシートの読み込みをやめたい場合などに、 特別なコメントを使用できるようになります。 $extras は、そのタグに追加したい特別な値の配列です。

さらに、HeadLink ヘルパーには、スタックに 'alternate' リンクを追加するメソッドもあります。

  • appendAlternate($href, $type, $title, $extras)

  • offsetSetAlternate($index, $href, $type, $title, $extras)

  • prependAlternate($href, $type, $title, $extras)

  • setAlternate($href, $type, $title, $extras)

headLink() ヘルパーメソッドは、 <link> 要素に必要なすべての属性を指定することができ、 その位置も指定することができます。 たとえば、新たな要素がこれまでのものを上書きする、 あるいはスタックの先頭に追加する、スタックの末尾に追加するなどを指定します。

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

例966 HeadLink ヘルパーの基本的な使用法

headLink は、いつでも指定することができます。 一般的には、グローバルなリンクはレイアウトスクリプトで指定して、 アプリケーション固有のリンクはアプリケーションのビュースクリプトで指定することになります。 レイアウトスクリプトでは、<head> セクションの中でヘルパーを出力することになります。

<?php // ビュースクリプトのリンクを設定します
$this->headLink()->appendStylesheet('/styles/basic.css')
                 ->headLink(array('rel' => 'icon',
                                  'href' => '/img/favicon.ico'),
                                  'PREPEND')
                 ->prependStylesheet('/styles/moz.css',
                                     'screen',
                                     true,
                                     array('id' => 'my_stylesheet'));
?>
<?php // リンクをレンダリングします ?>
<?php echo $this->headLink() ?>

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 ヘルパー の具象実装です。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

$this->doctype(Zend_View_Helper_Doctype::XHTML1_RDFA);
$this->headMeta()->setProperty('og:title', 'my article title');
$this->headMeta()->setProperty('og:type', 'article');
echo $this->headMeta();

//出力です。
//   <meta property="og:title" content="my article title" />
//   <meta property="og:type" content="article" />

HeadScript ヘルパー

注意:このドキュメントでは、英語版のリビジョン 19437 の更新内容をスキップしています。

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 パラメータで渡します。

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

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

Preventing HTML style comments or CDATA wrapping of scripts

By default HeadScript will wrap scripts with HTML comments or it wraps scripts with XHTML cdata. This behavior can be problematic when you intend to use the script tag in an alternative way by setting the type to something other then 'text/javascript'. To prevent such escaping, pass an noescape with a value of true as part of the $attrs parameter in the method calls.

例970 headScript で jQuery テンプレートを作成

// jquery テンプレート
$template = '<div class="book">{{:title}}</div>';
$this->headScript()->appendScript(
    $template,
    'text/x-jquery-tmpl',
    array('id='tmpl-book', 'noescape' => true)
);

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() メソッドを使用します。

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

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

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

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

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

// スクリプトの順番を指定します

// 特定の位置を指定し、確実に最後に読み込まれるようにします
$this->headScript()->offsetSetFile(100, '/js/myfuncs.js');

// scriptaculous のエフェクトを使用します (次のインデックスである 101 に追加されます)
$this->headScript()->appendFile('/js/scriptaculous.js');

// でも、もととなる prototype スクリプトは常に最初に読み込まれるようにします
$this->headScript()->prependFile('/js/prototype.js');

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

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

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

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

<?php $this->headScript()->captureStart() ?>
var action = '<?php echo $this->baseUrl ?>';
$('foo_form').action = action;
<?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 パラメータで渡します。

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

// スクリプトを追加します
$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 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.

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

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

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

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

// スタイルの順番を指定します

// 特定の位置に置きます
$this->headStyle()->offsetSetStyle(100, $customStyles);

// 最後に置きます
$this->headStyle()->appendStyle($finalStyles);

// 先頭に置きます
$this->headStyle()->prependStyle($firstStyles);

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

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

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

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

<?php $this->headStyle()->captureStart() ?>
body {
    background-color: <?php echo $this->bgColor ?>;
}
<?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.

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

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

// コントローラとアクションの名前を title 部に設定します
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->headTitle($request->getActionName())
     ->headTitle($request->getControllerName());

// サイト名を title に設定します。これはレイアウトスクリプトで行うことになるでしょう
$this->headTitle('Zend Framework');

// 各部分を区切る文字列を設定します
$this->headTitle()->setSeparator(' / ');

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

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

HTML オブジェクトヘルパー

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

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

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

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

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

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

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

例977 Flash ヘルパー

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

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

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

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

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

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

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

echo $this->htmlObject(
    '/path/to/file.ext',
    'mime/type',
    array(
        'attr1' => 'aval1',
        'attr2' => 'aval2'
    ),
    array(
        'param1' => 'pval1',
        'param2' => 'pval2'
    ),
    'some content'
);

/*
出力は次のようになります

<object data="/path/to/file.ext" type="mime/type"
    attr1="aval1" attr2="aval2">
    <param name="param1" value="pval1" />
    <param name="param2" value="pval2" />
    some content
</object>
*/

InlineScript ヘルパー

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

HTML Body スクリプトでの InlineScript の使用法

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

JS ライブラリの中には、 HTMLhead で読み込まなければならないものもあります。そのような場合は HeadScript を使用します。

RenderToPlaceholder Helper

Renders a template (view script) and stores the rendered output as a placeholder variable for later use.

注記

The helper uses the Placeholder helper and his Capture methods.

例979 Basic Usage of RenderToPlaceholder

<?php
// View script (backlink.phtml):
echo sprintf(
    '<p class="older"><a href="%s">Older posts</a></p>',
    $this->url(array('controller' => 'index', 'action' => 'index'))
)
?>

<?php
// Usage:
$this->renderToPlaceholder('backlink.phtml', 'link');
?>

<?php
echo $this->placeholder('link');
// Output: <p class="older"><a href="index/index">Older posts</a></p>
?>

JSON ヘルパー

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

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

Content-Type: application/json

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

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

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

レイアウトの維持、およびZend_Json_Expr によるエンコードの有効化

JSON ヘルパーの各メソッドには、オプションで 2 番目の引数を指定できます。 この 2 番目の引数は、レイアウト機能の有効/無効を指定する boolean フラグか あるいは Zend_Json::encode() に渡して内部的なデータのエンコードに使用するオプションの配列となります。

レイアウトを維持するには、2 番目のパラメータを TRUE としなければなりません。 2 番目のパラメータを配列ににする場合にレイアウトを維持するには、配列に keepLayouts というキーを含め、その値を TRUE にします。

// 2 番目の引数に true を指定するとレイアウトが有効になります
echo $this->json($this->data, true);

// あるいは、キー "keepLayouts" に true を指定します
echo $this->json($this->data, array('keepLayouts' => true));

Zend_Json::encode() は、ネイティブ JSON 式を Zend_Json_Expr オブジェクトを使用してエンコードできます。 このオプションはデフォルトでは無効になっています。 有効にするには、enableJsonExprFinder オプションに TRUE を設定します。

<?php echo $this->json($this->data, array(
    'enableJsonExprFinder' => true, 
    'keepLayouts'          => true,
)) ?>

Sending pre-encoded JSON

By default, the JSON helper will JSON-encode the data provided to the helper's first parameter. If you wish to pass in data which has already been encoded into JSON, the third parameter needs to be set to boolean FALSE. When the second parameter is an array, disabling JSON encoding can be achived by including a encodeData key with the value of boolean FALSE:

// Boolean false as third argument disables internal JSON encoding of data
echo $this->json($this->data, false, false);

// Or boolean false as "encodeData" key:
echo $this->json($this->data, array('encodeData' => false));

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().

例980 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.

$this->navigation()->addPage(array(
    'type' => 'uri',
    '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.

/*
 * Navigation container (config/array)

 * Each element in the array will be passed to
 * Zend_Navigation_Page::factory() when constructing
 * the navigation container below.
 */
$pages = array(
    array(
        'label'      => 'Home',
        'title'      => 'Go Home',
        'module'     => 'default',
        'controller' => 'index',
        'action'     => 'index',
        'order'      => -100 // make sure home is the first page
    ),
    array(
        'label'      => 'Special offer this week only!',
        'module'     => 'store',
        'controller' => 'offer',
        'action'     => 'amazing',
        'visible'    => false // not visible
    ),
    array(
        'label'      => 'Products',
        'module'     => 'products',
        'controller' => 'index',
        'action'     => 'index',
        'pages'      => array(
            array(
                'label'      => 'Foo Server',
                'module'     => 'products',
                'controller' => 'server',
                'action'     => 'index',
                'pages'      => array(
                    array(
                        'label'      => 'FAQ',
                        'module'     => 'products',
                        'controller' => 'server',
                        'action'     => 'faq',
                        'rel'        => array(
                            'canonical' => 'http://www.example.com/?page=faq',
                            'alternate' => array(
                                'module'     => 'products',
                                'controller' => 'server',
                                'action'     => 'faq',
                                'params'     => array('format' => 'xml')
                            )
                        )
                    ),
                    array(
                        'label'      => 'Editions',
                        'module'     => 'products',
                        'controller' => 'server',
                        'action'     => 'editions'
                    ),
                    array(
                        'label'      => 'System Requirements',
                        'module'     => 'products',
                        'controller' => 'server',
                        'action'     => 'requirements'
                    )
                )
            ),
            array(
                'label'      => 'Foo Studio',
                'module'     => 'products',
                'controller' => 'studio',
                'action'     => 'index',
                'pages'      => array(
                    array(
                        'label'      => 'Customer Stories',
                        'module'     => 'products',
                        'controller' => 'studio',
                        'action'     => 'customers'
                    ),
                    array(
                        'label'      => 'Support',
                        'module'     => 'prodcts',
                        'controller' => 'studio',
                        'action'     => 'support'
                    )
                )
            )
        )
    ),
    array(
        'label'      => 'Company',
        'title'      => 'About us',
        'module'     => 'company',
        'controller' => 'about',
        'action'     => 'index',
        'pages'      => array(
            array(
                'label'      => 'Investor Relations',
                'module'     => 'company',
                'controller' => 'about',
                'action'     => 'investors'
            ),
            array(
                'label'      => 'News',
                'class'      => 'rss', // class
                'module'     => 'company',
                'controller' => 'news',
                'action'     => 'index',
                'pages'      => array(
                    array(
                        'label'      => 'Press Releases',
                        'module'     => 'company',
                        'controller' => 'news',
                        'action'     => 'press'
                    ),
                    array(
                        'label'      => 'Archive',
                        'route'      => 'archive', // route
                        'module'     => 'company',
                        'controller' => 'news',
                        'action'     => 'archive'
                    )
                )
            )
        )
    ),
    array(
        'label'      => 'Community',
        'module'     => 'community',
        'controller' => 'index',
        'action'     => 'index',
        'pages'      => array(
            array(
                'label'      => 'My Account',
                'module'     => 'community',
                'controller' => 'account',
                'action'     => 'index',
                'resource'   => 'mvc:community.account' // resource
            ),
            array(
                'label' => 'Forums',
                'uri'   => 'http://forums.example.com/',
                'class' => 'external' // class
            )
        )
    ),
    array(
        'label'      => 'Administration',
        'module'     => 'admin',
        'controller' => 'index',
        'action'     => 'index',
        'resource'   => 'mvc:admin', // resource
        'pages'      => array(
            array(
                'label'      => 'Write new article',
                'module'     => 'admin',
                'controller' => 'post',
                'aciton'     => 'write'
            )
        )
    )
);

// Create container from array
$container = new Zend_Navigation($pages);

// Store the container in the proxy helper:
$view->getHelper('navigation')->setContainer($container);

// ...or simply:
$view->navigation($container);

// ...or store it in the reigstry:
Zend_Registry::set('Zend_Navigation', $container);

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

// Setup router (default routes and 'archive' route):
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->addDefaultRoutes();
$router->addRoute(
    'archive',
    new Zend_Controller_Router_Route(
        '/archive/:year',
        array(
            'module'     => 'company',
            'controller' => 'news',
            'action'     => 'archive',
            'year'       => (int) date('Y') - 1
        ),
        array('year' => '\d+')
    )
);

// Setup ACL:
$acl = new Zend_Acl();
$acl->addRole(new Zend_Acl_Role('member'));
$acl->addRole(new Zend_Acl_Role('admin'));
$acl->add(new Zend_Acl_Resource('mvc:admin'));
$acl->add(new Zend_Acl_Resource('mvc:community.account'));
$acl->allow('member', 'mvc:community.account');
$acl->allow('admin', null);

// Store ACL and role in the proxy helper:
$view->navigation()->setAcl($acl)->setRole('member');

// ...or set default ACL and role statically:
Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
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.

例981 Rendering breadcrumbs

This example shows how to render breadcrumbs with default settings.

In a view script or layout:
<?php echo $this->navigation()->breadcrumbs(); ?>

The two calls above take advantage of the magic __toString() method,
and are equivalent to:
<?php echo $this->navigation()->breadcrumbs()->render(); ?>

Output:
<a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

例982 Specifying indentation

This example shows how to render breadcrumbs with initial indentation.

Rendering with 8 spaces indentation:
<?php echo $this->navigation()->breadcrumbs()->setIndent(8);?>

Output:
        <a href="/products">Products</a> &gt; <a href="/products/server">Foo Server</a> &gt; FAQ

例983 Customize breadcrumbs output

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

In a view script or layout:

<?php
echo $this->navigation()
          ->breadcrumbs()
          ->setLinkLast(true)                   // link last page
          ->setMaxDepth(1)                      // stop at level 1
          ->setSeparator(' &#9654;' . PHP_EOL); // cool separator with newline
?>

Output:
<a href="/products">Products</a> &#9654;
<a href="/products/server">Foo Server</a>

/////////////////////////////////////////////////////

Setting minimum depth required to render breadcrumbs:

<?php
$this->navigation()->breadcrumbs()->setMinDepth(10);
echo $this->navigation()->breadcrumbs();
?>

Output:
Nothing, because the deepest active page is not at level 10 or deeper.

例984 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:

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

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

echo implode(', ', array_map(
        function ($a) { return $a->getLabel(); },
        $this->pages));

Output:

Products, Foo Server, FAQ

Links Helper

The links helper is used for rendering HTML LINK elements. Links are used for describing document relationships of the currently active page. Read more about links and link types at Document relationships: the LINK element (HTML4 W3C Rec.) and Link types (HTML4 W3C Rec.) in the HTML4 W3C Recommendation.

There are two types of relations; forward and reverse, indicated by the keyords 'rel' and 'rev'. Most methods in the helper will take a $rel param, which must be either 'rel' or 'rev'. Most methods also take a $type param, which is used for specifying the link type (e.g. alternate, start, next, prev, chapter, etc).

Relationships can be added to page objects manually, or found by traversing the container registered in the helper. The method findRelation($page, $rel, $type) will first try to find the given $rel of $type from the $page by calling $page->findRel($type) or $page->findRel($type). If the $page has a relation that can be converted to a page instance, that relation will be used. If the $page instance doesn't have the specified $type, the helper will look for a method in the helper named search$rel$type (e.g. searchRelNext() or searchRevAlternate()). If such a method exists, it will be used for determining the $page's relation by traversing the container.

Not all relations can be determined by traversing the container. These are the relations that will be found by searching:

  • searchRelStart(), forward 'start' relation: the first page in the container.

  • searchRelNext(), forward 'next' relation; finds the next page in the container, i.e. the page after the active page.

  • searchRelPrev(), forward 'prev' relation; finds the previous page, i.e. the page before the active page.

  • searchRelChapter(), forward 'chapter' relations; finds all pages on level 0 except the 'start' relation or the active page if it's on level 0.

  • searchRelSection(), forward 'section' relations; finds all child pages of the active page if the active page is on level 0 (a 'chapter').

  • searchRelSubsection(), forward 'subsection' relations; finds all child pages of the active page if the active pages is on level 1 (a 'section').

  • searchRevSection(), reverse 'section' relation; finds the parent of the active page if the active page is on level 1 (a 'section').

  • searchRevSubsection(), reverse 'subsection' relation; finds the parent of the active page if the active page is on level 2 (a 'subsection').

注記

When looking for relations in the page instance ($page->getRel($type) or $page->getRev($type)), the helper accepts the values of type String, Array, Zend_Config, or Zend_Navigation_Page. If a string is found, it will be converted to a Zend_Navigation_Page_Uri. If an array or a config is found, it will be converted to one or several page instances. If the first key of the array/config is numeric, it will be considered to contain several pages, and each element will be passed to the page factory. If the first key is not numeric, the array/config will be passed to the page factory directly, and a single page will be returned.

The helper also supports magic methods for finding relations. E.g. to find forward alternate relations, call $helper->findRelAlternate($page), and to find reverse section relations, call $helper->findRevSection($page). Those calls correspond to $helper->findRelation($page, 'rel', 'alternate'); and $helper->findRelation($page, 'rev', 'section'); respectively.

To customize which relations should be rendered, the helper uses a render flag. The render flag is an integer value, and will be used in a bitwse and (&) operation against the helper's render constants to determine if the relation that belongs to the render constant should be rendered.

See the example below for more information.

  • Zend_View_Helper_Navigation_Links::RENDER_ALTERNATE

  • Zend_View_Helper_Navigation_Links::RENDER_STYLESHEET

  • Zend_View_Helper_Navigation_Links::RENDER_START

  • Zend_View_Helper_Navigation_Links::RENDER_NEXT

  • Zend_View_Helper_Navigation_Links::RENDER_PREV

  • Zend_View_Helper_Navigation_Links::RENDER_CONTENTS

  • Zend_View_Helper_Navigation_Links::RENDER_INDEX

  • Zend_View_Helper_Navigation_Links::RENDER_GLOSSARY

  • Zend_View_Helper_Navigation_Links::RENDER_COPYRIGHT

  • Zend_View_Helper_Navigation_Links::RENDER_CHAPTER

  • Zend_View_Helper_Navigation_Links::RENDER_SECTION

  • Zend_View_Helper_Navigation_Links::RENDER_SUBSECTION

  • Zend_View_Helper_Navigation_Links::RENDER_APPENDIX

  • Zend_View_Helper_Navigation_Links::RENDER_HELP

  • Zend_View_Helper_Navigation_Links::RENDER_BOOKMARK

  • Zend_View_Helper_Navigation_Links::RENDER_CUSTOM

  • Zend_View_Helper_Navigation_Links::RENDER_ALL

The constants from RENDER_ALTERNATE to RENDER_BOOKMARK denote standard HTML link types. RENDER_CUSTOM denotes non-standard relations that specified in pages. RENDER_ALL denotes standard and non-standard relations.

Methods in the links helper:

  • {get|set}RenderFlag() gets/sets the render flag. Default is RENDER_ALL. See examples below on how to set the render flag.

  • findAllRelations() finds all relations of all types for a given page.

  • findRelation() finds all relations of a given type from a given page.

  • searchRel{Start|Next|Prev|Chapter|Section|Subsection}() traverses a container to find forward relations to the start page, the next page, the previous page, chapters, sections, and subsections.

  • searchRev{Section|Subsection}() traverses a container to find reverse relations to sections or subsections.

  • renderLink() renders a single link element.

例985 Specify relations in pages

This example shows how to specify relations in pages.

$container = new Zend_Navigation(array(
    array(
        'label' => 'Relations using strings',
        'rel'   => array(
            'alternate' => 'http://www.example.org/'
        ),
        'rev'   => array(
            'alternate' => 'http://www.example.net/'
        )
    ),
    array(
        'label' => 'Relations using arrays',
        'rel'   => array(
            'alternate' => array(
                'label' => 'Example.org',
                'uri'   => 'http://www.example.org/'
            )
        )
    ),
    array(
        'label' => 'Relations using configs',
        'rel'   => array(
            'alternate' => new Zend_Config(array(
                'label' => 'Example.org',
                'uri'   => 'http://www.example.org/'
            ))
        )
    ),
    array(
        'label' => 'Relations using pages instance',
        'rel'   => array(
            'alternate' => Zend_Navigation_Page::factory(array(
                'label' => 'Example.org',
                'uri'   => 'http://www.example.org/'
            ))
        )
    )
));

例986 Default rendering of links

This example shows how to render a menu from a container registered/found in the view helper.

In a view script or layout:
<?php echo $this->view->navigation()->links(); ?>

Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="chapter" href="/products" title="Products">
<link rel="chapter" href="/company/about" title="Company">
<link rel="chapter" href="/community" title="Community">
<link rel="canonical" href="http://www.example.com/?page=server-faq">
<link rev="subsection" href="/products/server" title="Foo Server">

例987 Specify which relations to render

This example shows how to specify which relations to find and render.

Render only start, next, and prev:
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_START |
                       Zend_View_Helper_Navigation_Links::RENDER_NEXT |
                       Zend_View_Helper_Navigation_Links::RENDER_PREV);

Output:
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
Render only native link types:
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
                       Zend_View_Helper_Navigation_Links::RENDER_CUSTOM);

Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="chapter" href="/products" title="Products">
<link rel="chapter" href="/company/about" title="Company">
<link rel="chapter" href="/community" title="Community">
<link rev="subsection" href="/products/server" title="Foo Server">
Render all but chapter:
$helper->setRenderFlag(Zend_View_Helper_Navigation_Links::RENDER_ALL ^
                       Zend_View_Helper_Navigation_Links::RENDER_CHAPTER);

Output:
<link rel="alternate" href="/products/server/faq/format/xml">
<link rel="start" href="/" title="Home">
<link rel="next" href="/products/server/editions" title="Editions">
<link rel="prev" href="/products/server" title="Foo Server">
<link rel="canonical" href="http://www.example.com/?page=server-faq">
<link rev="subsection" href="/products/server" title="Foo Server">

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}ActiveClass() gets/sets the CSS class for the active elements when rendering.

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

  • {get|set}ExpandSiblingNodesOfActiveBranch() gets/sets a flag specifying whether the sibling nodes of all nodes in the active branch should also be expanded and 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.

    • activeClass; CSS class for for the active elements when rendering. Expects a String.

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

    • expandSiblingNodesOfActiveBranch; whether the sibling nodes of nodes in the active branch should be expanded and 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.

例988 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.

In a view script or layout:
<?php echo $this->navigation()->menu()->render() ?>

Or simply:
<?php echo $this->navigation()->menu() ?>

Output:
<ul class="navigation">
    <li>
        <a title="Go Home" href="/">Home</a>
    </li>
    <li class="active">
        <a href="/products">Products</a>
        <ul>
            <li class="active">
                <a href="/products/server">Foo Server</a>
                <ul>
                    <li class="active">
                        <a href="/products/server/faq">FAQ</a>
                    </li>
                    <li>
                        <a href="/products/server/editions">Editions</a>
                    </li>
                    <li>
                        <a href="/products/server/requirements">System Requirements</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="/products/studio">Foo Studio</a>
                <ul>
                    <li>
                        <a href="/products/studio/customers">Customer Stories</a>
                    </li>
                    <li>
                        <a href="/prodcts/studio/support">Support</a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        <a title="About us" href="/company/about">Company</a>
        <ul>
            <li>
                <a href="/company/about/investors">Investor Relations</a>
            </li>
            <li>
                <a class="rss" href="/company/news">News</a>
                <ul>
                    <li>
                        <a href="/company/news/press">Press Releases</a>
                    </li>
                    <li>
                        <a href="/archive">Archive</a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        <a href="/community">Community</a>
        <ul>
            <li>
                <a href="/community/account">My Account</a>
            </li>
            <li>
                <a class="external" href="http://forums.example.com/">Forums</a>
            </li>
        </ul>
    </li>
</ul>

例989 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.

<?php
// render only the 'Community' menu
$community = $this->navigation()->findOneByLabel('Community');
$options = array(
    'indent'  => 16,
    'ulClass' => 'community'
);
echo $this->navigation()
          ->menu()
          ->renderMenu($community, $options);
?>
Output:
                <ul class="community">
                    <li>
                        <a href="/community/account">My Account</a>
                    </li>
                    <li>
                        <a class="external" href="http://forums.example.com/">Forums</a>
                    </li>
                </ul>

例990 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:

array(
    'ulClass'          => $ulClass,
    'indent'           => $indent,
    'minDepth'         => null,
    'maxDepth'         => null,
    'onlyActiveBranch' => true,
    'renderParents'    => false
);
<?php
echo $this->navigation()
          ->menu()
          ->renderSubMenu(null, 'sidebar', 4);
?>

The output will be the same if 'FAQ' or 'Foo Server' is active:
    <ul class="sidebar">
        <li class="active">
            <a href="/products/server/faq">FAQ</a>
        </li>
        <li>
            <a href="/products/server/editions">Editions</a>
        </li>
        <li>
            <a href="/products/server/requirements">System Requirements</a>
        </li>
    </ul>

例991 Rendering a menu with maximum depth

<?php
echo $this->navigation()
          ->menu()
          ->setMaxDepth(1);
?>

Output:
<ul class="navigation">
    <li>
        <a title="Go Home" href="/">Home</a>
    </li>
    <li class="active">
        <a href="/products">Products</a>
        <ul>
            <li class="active">
                <a href="/products/server">Foo Server</a>
            </li>
            <li>
                <a href="/products/studio">Foo Studio</a>
            </li>
        </ul>
    </li>
    <li>
        <a title="About us" href="/company/about">Company</a>
        <ul>
            <li>
                <a href="/company/about/investors">Investor Relations</a>
            </li>
            <li>
                <a class="rss" href="/company/news">News</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="/community">Community</a>
        <ul>
            <li>
                <a href="/community/account">My Account</a>
            </li>
            <li>
                <a class="external" href="http://forums.example.com/">Forums</a>
            </li>
        </ul>
    </li>
</ul>

例992 Rendering a menu with minimum depth

<?php
echo $this->navigation()
          ->menu()
          ->setMinDepth(1);
?>

Output:
<ul class="navigation">
    <li class="active">
        <a href="/products/server">Foo Server</a>
        <ul>
            <li class="active">
                <a href="/products/server/faq">FAQ</a>
            </li>
            <li>
                <a href="/products/server/editions">Editions</a>
            </li>
            <li>
                <a href="/products/server/requirements">System Requirements</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="/products/studio">Foo Studio</a>
        <ul>
            <li>
                <a href="/products/studio/customers">Customer Stories</a>
            </li>
            <li>
                <a href="/prodcts/studio/support">Support</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="/company/about/investors">Investor Relations</a>
    </li>
    <li>
        <a class="rss" href="/company/news">News</a>
        <ul>
            <li>
                <a href="/company/news/press">Press Releases</a>
            </li>
            <li>
                <a href="/archive">Archive</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="/community/account">My Account</a>
    </li>
    <li>
        <a class="external" href="http://forums.example.com/">Forums</a>
    </li>
</ul>

例993 Rendering only the active branch of a menu

<?php
echo $this->navigation()
          ->menu()
          ->setOnlyActiveBranch(true);
?>

Output:
<ul class="navigation">
    <li class="active">
        <a href="/products">Products</a>
        <ul>
            <li class="active">
                <a href="/products/server">Foo Server</a>
                <ul>
                    <li class="active">
                        <a href="/products/server/faq">FAQ</a>
                    </li>
                    <li>
                        <a href="/products/server/editions">Editions</a>
                    </li>
                    <li>
                        <a href="/products/server/requirements">System Requirements</a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

例994 Rendering only the active branch of a menu with minimum depth

<?php
echo $this->navigation()
          ->menu()
          ->setOnlyActiveBranch(true)
          ->setMinDepth(1);
?>

Output:
<ul class="navigation">
    <li class="active">
        <a href="/products/server">Foo Server</a>
        <ul>
            <li class="active">
                <a href="/products/server/faq">FAQ</a>
            </li>
            <li>
                <a href="/products/server/editions">Editions</a>
            </li>
            <li>
                <a href="/products/server/requirements">System Requirements</a>
            </li>
        </ul>
    </li>
</ul>

例995 Rendering only the active branch of a menu with maximum depth

<?php
echo $this->navigation()
          ->menu()
          ->setOnlyActiveBranch(true)
          ->setMaxDepth(1);
?>

Output:
<ul class="navigation">
    <li class="active">
        <a href="/products">Products</a>
        <ul>
            <li class="active">
                <a href="/products/server">Foo Server</a>
            </li>
            <li>
                <a href="/products/studio">Foo Studio</a>
            </li>
        </ul>
    </li>
</ul>

例996 Rendering only the active branch of a menu with maximum depth and no parents

<?php
echo $this->navigation()
          ->menu()
          ->setOnlyActiveBranch(true)
          ->setRenderParents(false)
          ->setMaxDepth(1);
?>

Output:
<ul class="navigation">
    <li class="active">
        <a href="/products/server">Foo Server</a>
    </li>
    <li>
        <a href="/products/studio">Foo Studio</a>
    </li>
</ul>

例997 Rendering a custom menu using a partial view script

This example shows how to render a custom menu 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 assign the container to the view with the key container.

In a layout:

$partial = array('menu.phtml', 'default');
$this->navigation()->menu()->setPartial($partial);
echo $this->navigation()->menu()->render();

In application/modules/default/views/menu.phtml:

foreach ($this->container as $page) {
    echo $this->navigation()->menu()->htmlify($page), PHP_EOL;
}

Output:

<a title="Go Home" href="/">Home</a>
<a href="/products">Products</a>
<a title="About us" href="/company/about">Company</a>
<a href="/community">Community</a>

例998 Rendering only the active branch and all siblings of the active branch

echo $this->navigation()
          ->menu()
          ->setExpandSiblingNodesOfActiveBranch(true);

Output:

<ul class="navigation">
    <li>
        <a title="Go Home" href="/">Home</a>
    </li>
    <li class="active">
        <a href="/products">Products</a>
        <ul>
            <li class="active">
                <a href="/products/server">Foo Server</a>
                <ul>
                    <li class="active">
                        <a href="/products/server/faq">FAQ</a>
                    </li>
                    <li>
                        <a href="/products/server/editions">Editions</a>
                    </li>
                    <li>
                        <a href="/products/server/requirements">System Requirements</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="/products/studio">Foo Studio</a>
            </li>
        </ul>
    </li>
    <li>
        <a title="About us" href="/company/about">Company</a>
    </li>
    <li>
        <a href="/community">Community</a>
    </li>
</ul>

Sitemap Helper

The Sitemap helper is used for generating XML sitemaps, as defined by the Sitemaps XML format. Read more about Sitemaps on Wikpedia.

By default, the sitemap helper uses sitemap validators to validate each element that is rendered. This can be disabled by calling $helper->setUseSitemapValidators(false).

注記

If you disable sitemap validators, the custom properties (see table) are not validated at all.

The sitemap helper also supports Sitemap XSD Schema validation of the generated sitemap. This is disabled by default, since it will require a request to the Schema file. It can be enabled with $helper->setUseSchemaValidation(true).

表171 Sitemap XML elements

Element Description
loc Absolute URL to page. An absolute URL will be generated by the helper.
lastmod

The date of last modification of the file, in W3C Datetime format. This time portion can be omitted if desired, and only use YYYY-MM-DD.

The helper will try to retrieve the lastmod value from the page's custom property lastmod if it is set in the page. If the value is not a valid date, it is ignored.

changefreq

How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are:

  • always

  • hourly

  • daily

  • weekly

  • monthly

  • yearly

  • never

The helper will try to retrieve the changefreq value from the page's custom property changefreq if it is set in the page. If the value is not valid, it is ignored.

priority

The priority of this URL relative to other URLs on your site. Valid values range from 0.0 to 1.0.

The helper will try to retrieve the priority value from the page's custom property priority if it is set in the page. If the value is not valid, it is ignored.


Methods in the sitemap helper:

  • {get|set}FormatOutput() gets/sets a flag indicating whether XML output should be formatted. This corresponds to the formatOutput property of the native DOMDocument class. Read more at PHP: DOMDocument - Manual. Default is FALSE.

  • {get|set}UseXmlDeclaration() gets/sets a flag indicating whether the XML declaration should be included when rendering. Default is TRUE.

  • {get|set}UseSitemapValidators() gets/sets a flag indicating whether sitemap validators should be used when generating the DOM sitemap. Default is TRUE.

  • {get|set}UseSchemaValidation() gets/sets a flag indicating whether the helper should use XML Schema validation when generating the DOM sitemap. Default is FALSE. If TRUE.

  • {get|set}ServerUrl() gets/sets server URL that will be prepended to non-absolute URLs in the url() method. If no server URL is specified, it will be determined by the helper.

  • url() is used to generate absolute URLs to pages.

  • getDomSitemap() generates a DOMDocument from a given container.

例999 Rendering an XML sitemap

This example shows how to render an XML sitemap based on the setup we did further up.

// In a view script or layout:

// format output
$this->navigation()
      ->sitemap()
      ->setFormatOutput(true); // default is false

// other possible methods:
// ->setUseXmlDeclaration(false); // default is true
// ->setServerUrl('http://my.otherhost.com');
// default is to detect automatically

// print sitemap
echo $this->navigation()->sitemap();

Notice how pages that are invisible or pages with ACL roles incompatible with the view helper are filtered out:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/</loc>
  </url>
  <url>
    <loc>http://www.example.com/products</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/faq</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/editions</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/requirements</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/studio</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/studio/customers</loc>
  </url>
  <url>
    <loc>http://www.example.com/prodcts/studio/support</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about/investors</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/news</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/news/press</loc>
  </url>
  <url>
    <loc>http://www.example.com/archive</loc>
  </url>
  <url>
    <loc>http://www.example.com/community</loc>
  </url>
  <url>
    <loc>http://www.example.com/community/account</loc>
  </url>
  <url>
    <loc>http://forums.example.com/</loc>
  </url>
</urlset>

Render the sitemap using no ACL role (should filter out /community/account):

echo $this->navigation()
          ->sitemap()
          ->setFormatOutput(true)
          ->setRole();
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/</loc>
  </url>
  <url>
    <loc>http://www.example.com/products</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/faq</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/editions</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server/requirements</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/studio</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/studio/customers</loc>
  </url>
  <url>
    <loc>http://www.example.com/prodcts/studio/support</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about/investors</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/news</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/news/press</loc>
  </url>
  <url>
    <loc>http://www.example.com/archive</loc>
  </url>
  <url>
    <loc>http://www.example.com/community</loc>
  </url>
  <url>
    <loc>http://forums.example.com/</loc>
  </url>
</urlset>

Render the sitemap using a maximum depth of 1.

echo $this->navigation()
          ->sitemap()
          ->setFormatOutput(true)
          ->setMaxDepth(1);
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/</loc>
  </url>
  <url>
    <loc>http://www.example.com/products</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/server</loc>
  </url>
  <url>
    <loc>http://www.example.com/products/studio</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/about/investors</loc>
  </url>
  <url>
    <loc>http://www.example.com/company/news</loc>
  </url>
  <url>
    <loc>http://www.example.com/community</loc>
  </url>
  <url>
    <loc>http://www.example.com/community/account</loc>
  </url>
  <url>
    <loc>http://forums.example.com/</loc>
  </url>
</urlset>

UTF-8 encoding used by default

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 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 the Dojo 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.

Navigation Helper

The Navigation helper is a proxy helper that relays calls to other navigational helpers. It can be considered an entry point to all navigation-related view tasks. The aforementioned navigational helpers are in the namespace Zend_View_Helper_Navigation, and would thus require the path Zend/View/Helper/Navigation to be added as a helper path to the view. With the proxy helper residing in the Zend_View_Helper namespace, it will always be available, without the need to add any helper paths to the view.

The Navigation helper finds other helpers that implement the Zend_View_Helper_Navigation_Helper interface, which means custom view helpers can also be proxied. This would, however, require that the custom helper path is added to the view.

When proxying to other helpers, the Navigation helper can inject its container, ACL/role, and translator. This means that you won't have to explicitly set all three in all navigational helpers, nor resort to injecting by means of Zend_Registry or static methods.

  • findHelper() finds the given helper, verifies that it is a navigational helper, and injects container, ACL/role and translator.

  • {get|set}InjectContainer() gets/sets a flag indicating whether the container should be injected to proxied helpers. Default is TRUE.

  • {get|set}InjectAcl() gets/sets a flag indicating whether the ACL/role should be injected to proxied helpers. Default is TRUE.

  • {get|set}InjectTranslator() gets/sets a flag indicating whether the translator should be injected to proxied helpers. Default is TRUE.

  • {get|set}DefaultProxy() gets/sets the default proxy. Default is 'menu'.

  • render() proxies to the render method of the default proxy.

翻訳ヘルパー

ウェブサイトを複数言語で提供することもよくあります。 サイト上のコンテンツを翻訳するには、 Zend_Translate を使用します。 Zend_Translate をビューと統合するために使用するのが Translate ビューヘルパーです。

これ以降のすべての例では、単純は配列翻訳アダプタを使用します。 もちろん Zend_Translate の任意のインスタンスやお好みの Zend_Translate_Adapter のサブクラスを使うことも可能です。 Translate ビューヘルパーのインスタンスを作成するにはいくつかの方法があります。

  • 事前に Zend_Registry に登録済みのインスタンスを使用する

  • 流れるようなインターフェイスで後から追加する

  • クラスのインスタンスの作成時に直接指定する

登録済みの Zend_Translate のインスタンスを使用する方法をおすすめします。 アダプタをレジストリに追加する際に、使用するロケールを選択できます。

注記

ここで言語ではなくロケールと言っているのは、 言語には地域を含む可能性があるからです。 たとえば英語は様々な地域で話されています。 イギリス英語やアメリカ英語など複数の翻訳が存在します。 そこで、ここでは "言語" と言わずに "ロケール" としているのです。

例1000 登録済みのインスタンス

登録済みのインスタンスを使用するには、まず Zend_Translate あるいは Zend_Translate_Adapter のインスタンスを作成し、 それを Zend_Registry に登録します。登録する際のキーとして Zend_Translate を使用します。

// サンプルアダプタ
$adapter = new Zend_Translate(
    array(
        'adapter' => 'array',
        'content' => array('simple' => 'einfach'),
        'locale'  => 'de'
    )
);
Zend_Registry::set('Zend_Translate', $adapter);

// ビューの中で
echo $this->translate('simple');
// これは 'einfach' を返します

流れるようなインターフェイスのほうがなじみがあるという場合は、 ビューの中でインスタンスを作成し、ヘルパーのインスタンスは後で作成することもできます。

例1001 ビューの中で

流れるようなインターフェイスで Zend_Translate あるいは Zend_Translate_Adapter のインスタンスを作成するには、 パラメータを指定せずにヘルパーをコールし、それから setTranslator() メソッドをコールします。

// ビューの中で
$adapter = new Zend_Translate(
    array(
        'adapter' => 'array',
        'content' => array('simple' => 'einfach'),
        'locale'  => 'de'
    )
);
$this->translate()->setTranslator($adapter)->translate('simple');
// これは 'einfach' を返します

ヘルパーを Zend_View なしで使用すると、 ヘルパーを直接使用することもできます。

例1002 直接使用する方法

// サンプルアダプタ
$adapter = new Zend_Translate(
    array(
        'adapter' => 'array',
        'content' => array('simple' => 'einfach'),
        'locale'  => 'de'
    )
);

// アダプタを初期化します
$translate = new Zend_View_Helper_Translate($adapter);
print $translate->translate('simple'); // これは 'einfach' を返します

Zend_View は使わないけれど、 翻訳した結果がほしいという場合にこの方式を使用します。


これまで見てきたように、translate() メソッドは翻訳を返します。 翻訳アダプタのメッセージ ID を指定してこれをコールします。 さらに、翻訳文字列の中のパラメータを置換することも可能です。 パラメータの値を指定する方法には二通りあります。 パラメータのリストを指定する方法か、あるいはパラメータの配列を指定する方法です。 たとえば次のようになります。

例1003 単一のパラメータ

単一のパラメータを使用するには、単にそれをメソッドに追加します。

// ビューの中で
$date = "Monday";
$this->translate("Today is %1\$s", $date);
// これは 'Heute ist Monday' を返します

注記

パラメータの値にテキストを使用する場合は、 このパラメータの値も翻訳しなければならないことに注意しましょう。

例1004 パラメータのリスト

パラメータのリストを使用して、それをメソッドに追加することもできます。

// ビューの中で
$date = "Monday";
$month = "April";
$time = "11:20:55";
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s",
                 $date,
                 $month,
                 $time);
// これは 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55' を返します

例1005 パラメータの配列

パラメータの配列を使用して、それをメソッドに追加することもできます。

// ビューの中で
$date = array("Monday", "April", "11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
// これは 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55' を返します

翻訳のロケールを変更しなければならないこともあるでしょう。 翻訳単位で動的に変更することもできますが、 静的に変更してそれ以降のすべての翻訳に適用させることもできます。 そして、パラメータリスト型あるいはパラメータ配列型のどちらの形式でもそれを使用できます。 どひらの形式の場合も、ロケールは最後のパラメータとして指定します。

例1006 ロケールの動的な変更

// ビューの中で
$date = array("Monday", "April", "11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it');

この例は、指定したメッセージ ID に対応するイタリア語の翻訳を返します。 しかし、イタリア語を返すのはこのときだけです。 次の翻訳では、アダプタに設定されているロケールを使用します。 通常は、使用したいロケールを翻訳アダプタに設定してからレジストリに追加します。 しかし、ロケールの設定をヘルパー内で行うこともできます。

例1007 ロケールの静的な変更

// ビューの中で
$date = array("Monday", "April", "11:20:55");
$this->translate()->setLocale('it');
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);

上の例では新しいデフォルトロケールとして 'it' を設定しており、これ以降の翻訳ではこのロケールを使用します。

もちろん、現在設定されているロケールを取得するためのメソッド getLocale() もあります。

例1008 現在設定されているロケールの取得

// ビューの中で
$date = array("Monday", "April", "11:20:55");

// これまでの例で設定されているデフォルトロケールである 'de' を返します
$this->translate()->getLocale();

$this->translate()->setLocale('it');
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);

// 新たに設定されたデフォルトロケールである 'it' を返します
$this->translate()->getLocale();

UserAgent View Helper

Overview

This view helper provides the ability to inject and later retrieve a Zend_Http_UserAgent instance for use in branching display logic based on device capabilities.

Quick Start

In most cases, you can simply retrieve the User-Agent and related device by calling the helper. If the UserAgent was configured in the bootstrap, that instance will be injected already in the helper; otherwise, it will instantiate one for you.

<?php if ($this->userAgent()->getDevice()->hasFlash()): ?>
    <object ...></object>
<?php endif ?>

If you initialize the UserAgent object manually, you can still inject it into the helper, in one of two ways.

// Pull the helper from the view, and inject:
$helper = $view->getHelper('userAgent');
$helper->setUserAgent($userAgent);

// Pass the UserAgent to the helper:
$view->userAgent($userAgent);
Available Methods
userAgent( Zend_Http_UserAgent $userAgent = null );

Use this method to set or retrieve the UserAgent instance. Passing an instance will set it; passing no arguments will retrieve it. If no previous instance has been registered, one will be lazy-loaded using defaults.

setUserAgent( Zend_Http_UserAgent $userAgent );

If you have an instance of the helper -- for instance, by calling the view object's getHelper() method -- you may use this method to set the UserAgent instance.

getUserAgent();

Retrieves the UserAgent instance; if none is registered, it will lazy-load one using default values.

ヘルパーのパス

ビュースクリプトと同様、 Zend_View がヘルパークラスを探すパスをコントローラから積み重ねて指定できます。 デフォルトでは、Zend_View は "Zend/View/Helper/*" からヘルパークラスを探します。 Zend_View に別の場所を探すように指定するには setHelperPath() および addHelperPath() メソッドを使用します。 さらに、クラスプレフィックスを指定することもできます。 これにより、ヘルパークラスに名前空間を設定できるようになります。 デフォルトでクラスプレフィックスを指定しなかった場合は、 'Zend_View_Helper_' であると見なされます。

$view = new Zend_View();

// パスを /path/to/more/helpers 、プレフィックスを 'My_View_Helper' と設定します
$view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');

addHelperPath() メソッドを使用すると、検索パスを「積み重ねる」 ことができます。これを使用すると、Zend_View は一番最後に追加されたパスからヘルパークラスを探し始めます。 これにより、付属しているヘルパーの内容を上書きしたり、 新しいヘルパーを追加したりすることができるようになります。

$view = new Zend_View();
// /path/to/some/helpers をクラスプレフィックス 'My_View_Helper' で追加します
$view->addHelperPath('/path/to/some/helpers', 'My_View_Helper');
// /other/path/to/helpers をクラスプレフィックス 'Your_View_Helper' で追加します
$view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');

// $this->helperName() をコールすると、Zend_View は
// まず最初に "/path/to/some/helpers/HelperName" で
// "Your_View_Helper_HelperName" という名前のクラスを探し、
// 次に "/other/path/to/helpers/HelperName.php" で
// "My_View_Helper_HelperName" という名前のクラスを探し、
// そして最後に "Zend/View/Helpers/HelperName.php" で
// "Zend_View_Helper_HelperName" という名前のクラスを探します。

独自のヘルパーを書く

独自のヘルパーを書くのは簡単です。以下の規則に従ってください。

  • 絶対条件というわけではありませんが、ヘルパーを作成する際には Zend_View_Helper_Interface を実装するか Zend_View_Helper_Abstract を継承することを推奨します。 1.6.0 以降、これらには setView() メソッドが定義されています。 しかし、将来のリリースでは Strategy パターンを実装することを検討しており、 以下に示す命名規約の多くを単純化する予定です。 今のうちにこのようにしておくと、 将来のバージョンでもあなたの書いたコードがそのまま動くようになるでしょう。

  • クラス名は、少なくとも最後はヘルパーの名前と同じである必要があります。 MixedCaps 方式を使用します。たとえば "specialPurpose" という名前のヘルパーを作成した場合は、そのクラス名には 最低限 "SpecialPurpose" が含まれている必要があります。 このクラス名にプレフィックスを指定できます。 プレフィックスの一部に 'View_Helper' を含めることを推奨します。たとえば "My_View_Helper_SpecialPurpose" のようになります (addHelperPath()setHelperPath() にはプレフィックスを指定する必要があります。 最後のアンダースコアは含めても含めなくてもかまいません)。

  • クラスは、ヘルパーと同じ名前の public メソッドを持っている必要があります。 テンプレートが "$this->specialPurpose()" をコールした際に、 このメソッドがコールされます。"specialPurpose" ヘルパーの例では、 "public function specialPurpose()" というメソッドが必要です。

  • 一般に、クラスでは echo や print その他の出力を行ってはいけません。 その代わりに、print あるいは echo される内容を返します。 返り値は、適切にエスケープしなければなりません。

  • クラスは、ヘルパークラスと同じ名前のファイルに作成しなければなりません。 再び "specialPurpose" ヘルパーを例にとると、ファイル名は "SpecialPurpose.php" でなければなりません。

指定したヘルパーパスのどこかにヘルパークラスのファイルを配置すると、 Zend_View は自動的にそれを読み込んでインスタンスを作成し、 必要に応じて実行します。

SpecialPurpose ヘルパーのコードの例を示します。

class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
{
    protected $_count = 0;
    public function specialPurpose()
    {
        $this->_count++;
        $output = "'The Jerk' を {$this->_count} 回見ました。";
        return htmlspecialchars($output);
    }
}

そして、ビュースクリプト内で SpecialPurpose ヘルパーを必要なだけコールします。いちどインスタンスが作成された後は、 Zend_View インスタンスの中でそれが持続します。

// ビュースクリプト内では、$this は Zend_View インスタンスを指すことを覚えておきましょう。
echo $this->specialPurpose();
echo $this->specialPurpose();
echo $this->specialPurpose();

出力結果は、次のようになります。

'The Jerk' を 1 回見ました。
'The Jerk' を 2 回見ました。
'The Jerk' を 3 回見ました。

時には Zend_View オブジェクトを使用したくなることもあるでしょう。 たとえば登録されているエンコーディングを使用する必要があったり、 ヘルパー内で別のビュースクリプトをレンダリングしたくなったりといった場合です。 ビューオブジェクトにアクセスするには、ヘルパークラス内で次のような setView($view) メソッドを定義しなければなりません。

class My_View_Helper_ScriptPath
{
    public $view;

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }

    public function scriptPath($script)
    {
        return $this->view->getScriptPath($script);
    }
}

ヘルパークラスで setView() メソッドを定義しておくと、 最初にインスタンスが作成される際に自動的にこのメソッドがコールされ、 現在のビューオブジェクトが引数として渡されます。 渡されたオブジェクトをクラス内でどのように管理するかは特に決まっていません。 お好みの方法で管理してください。

Zend_View_Helper_Abstract を継承する場合は、 このメソッドはすでに定義済みであるため定義する必要はありません。

実在するヘルパーを登録

時には、ビュー・ヘルパーをインスタンス化して、それからビューで登録すると便利です。 バージョン 1.10.0 時点で、これは registerHelper() メソッドを用いると可能です。 それは2つの引数を期待します。それは、ヘルパー・オブジェクトと登録される名前です。

$helper = new My_Helper_Foo();
// ...何らかの構成または依存性注入を行います...

$view->registerHelper($helper, 'foo');

ヘルパーに setView() メソッドがあると、 ビュー・オブジェクトはこれを呼び出して、登録時に自分自身をヘルパーに注入します。

ヘルパー名はメソッドと一致しなければいけません

registerHelper() の2番目の引数はヘルパー名です。 対応するメソッド名がヘルパー内に存在しなければいけません。 さもなければ、ヘルパー起動時に Zend_View が存在しないメソッドを呼び出して 致命的な PHP エラーを引き起こします。