ビュースクリプトの中で、複雑な関数を繰り返し実行しなければならないこともあるでしょう
(例えば日付のフォーマット、フォーム要素の作成、リンクの作成など)。
このような作業を行うために、ヘルパークラスを使用できます。
ヘルパーの正体は、単なるクラスです。たとえば 'fooBar' という名前のヘルパーを使用するとしましょう。
デフォルトでは、クラス名の先頭には 'Zend_View_Helper_'
がつきます (ヘルパーのパスを設定する際に、これは独自のものに変更できます)。
そしてクラス名の最後の部分がヘルパーの名前となります。
このとき、単語の先頭は大文字にしなければなりません。つまり、
ヘルパーのクラス名は Zend_View_Helper_FooBar
となります。このクラスには、最低限ヘルパー名と同じ名前 (camelCase 形式にしたもの)
のメソッド fooBar() が含まれていなければなりません。
付属のヘルパー
Zend_View には、はじめからいくつかのヘルパークラスが付属しています。
これらのほとんどはフォーム要素の生成に関するもので、
適切なエスケープ処理を自動的に行います。
さらに、ルートにもとづいた URL と HTML の一覧を作成したり、
変数を宣言したりするものもあります。
現在付属しているヘルパーは、次のとおりです。
declareVars():
strictVars() を使用する際に同時に使用します。
このヘルパーを使用すると、テンプレート変数を宣言できます。
この変数は、すでにビュースクリプトで設定されているものでもいないものでもかまいません。
また、同時にデフォルト値も設定します。
このメソッドへの引数として配列を渡すとデフォルト値を設定します。
それ以外の場合は、もしその変数が存在しない場合は空文字列を設定します。
fieldset($name, $content, $attribs):
XHTML の fieldset を作成します。$attribs に
'legend' というキーが含まれる場合、その値をフィールドセットの説明として使用します。
フィールドセットで囲む内容は、このヘルパーに渡した
$content です。
form($name, $attribs, $content):
XHTML の form を作成します。すべての $attribs
はエスケープされ、form タグの XHTML 属性としてレンダリングされます。
$content が存在してその値が FALSE 以外の場合は、
その内容がフォームの開始タグと終了タグの間にレンダリングされます。
$content が FALSE (既定値) の場合は、
フォームの開始タグのみを作成します。
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),
// 'bar' および 'baz' でチェック状態と未チェック状態を表します。これはチェックされていません
echo $this->
formCheckbox('foo',
'baz',
null,
array('bar',
'baz'));
echo $this->
formCheckbox('foo',
null,
array('checked' =>
false),
どの場合についても、マークアップの先頭に 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" /> 要素を作成します。
'foo',
'bar',
'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 になります。
attribs に disable
を渡すと、結果を何も返しません。
-
formMultiCheckbox($name, $value, $attribs, $options,
$listsep): チェックボックスのリストを作成します。
$options は連想配列で、任意の深さにできます。
$value は単一の値か複数の値の配列で、これが
$options 配列のキーにマッチします。
$listsep は、デフォルトでは HTML の改行
("<br />") です。デフォルトでは、この要素は配列として扱われます。
つまり、すべてのチェックボックスは同じ名前となり、入力内容は配列形式で送信されます。
// リスト・セパレーター ($listsep) を使用:
echo $view->
formMultiCheckbox(
'foo',
2,
'class' => 'baz',
),
1 => 'One',
2 => 'Two',
3 => 'Three',
),
"</li>\n<li>"
);
/*
出力:
<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,
'label_placement' => 'prepend',
'label_class' => 'baz',
),
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) を使用
'foo',
2,
'class' => 'baz',
),
1 => 'One',
2 => 'Two',
3 => 'Three',
),
"</li>\n<li>"
);
/*
出力:
<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>
*/
// ラベル要素に対してオプションを使用:
'foo',
2,
'label_placement' => 'prepend',
'label_class' => 'baz',
),
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 は初期選択状態を設定します。
// オプション・グループを使用:
'foo',
2,
'class' => 'baz',
),
1 => 'One',
'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:
'foo[]',
2,
null,
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:
'foo',
1,
2,
),
'multiple' => true,
),
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)
// 出力: user/info/id/1
// URL オプションを設定:
array('controller' =>
'user',
'action' =>
'info',
'username' =>
'foobar')
);
// 出力: user/info/username/foobar
// ルートを使用:
$router->addRoute(
'user',
new Zend_Controller_Router_Route(
'user/:username',
'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
// エンコードを使用:
array('controller' =>
'user',
'action' =>
'info',
'username' =>
'John Doe'),
null,
true,
false
);
// 出力: user/info/username/John Doe
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
// 出力: 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');
// 出力: 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
は必須です。モジュールを省略した場合はデフォルトのモジュールを使用します。
Example #1 Action ビューヘルパーの基本的な使用法
たとえば CommentController に
listAction() というメソッドがあったとしましょう。
コメント一覧を取得するために現在のリクエストからこのメソッドを起動するには、
次のようにします。
<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'); ?>" />
Note:
単純にする目的で、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.
Note:
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."
Example #2 Registered instance
To use a registered instance, simply create an instance of
Zend_Currency and register it within
Zend_Registry using Zend_Currency as its
key.
// 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.
Example #3 Within the view
To use the fluent interface, create an instance of Zend_Currency,
call the helper without a parameter, and call the setCurrency()
method.
// 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.
// 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.
// 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ヘルパーは 一組の値を交互に切り替えるために使われます。
Example #6 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>
Example #7 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
ビューヘルパーは、反復処理可能なデータを渡して
その各要素に対してレンダリングを行うものです。
Note: PartialLoop カウンタ
PartialLoop ビューヘルパーは、変数を
partialCounter というビューに代入します。
これは、配列の現在の位置をビュースクリプトに渡します。
これを利用すると、たとえばテーブルの行の色を一行おきに入れ替えるなどが簡単にできます。
Example #8 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>
Note: モデルは何?
Partial ビューヘルパーが使用するモデルは、
次のいずれかとなります。
配列。
配列を渡す場合は、連想配列形式でなければなりません。
そのキーと値のペアがビューに渡され、
キーが変数名となります。
toArray() メソッドを実装したオブジェクト。
そのオブジェクトの toArray()
メソッドを実行した結果が、ビューオブジェクトに渡されます。
標準のオブジェクト。
それ以外のオブジェクトについては、
object_get_vars() の結果
(そのオブジェクトのすべての public プロパティ)
がビューオブジェクトに渡されます。
使用するモデルがオブジェクトである場合は、
それを変数の配列などに変換するのではなく
オブジェクトのまま 直接
partial スクリプトに渡したくなるものでしょう。
そのためには、しかるべきヘルパーでプロパティ
'objectKey' を設定します。
// オブジェクトを、変数 'model' として渡すよう通知します
$view->partial()->setObjectKey('model');
// partialLoop のオブジェクトを、最終的なビュースクリプト内で
// 変数 'model' として渡すよう通知します
$view->partialLoop()->setObjectKey('model');
このテクニックが特に役立つのは、
Zend_Db_Table_Rowset を
partialLoop() に渡すような場合です。
ビュースクリプト内で row オブジェクトに自由にアクセスでき、
そのメソッド (親の値を取得したり従属行を取得したりなど)
を自在に使えるようになります。
Example #9 PartialLoop による反復処理可能なモデルのレンダリング
一般に、ループ内で partial
を使用して特定のコンテンツを繰り返しレンダリングしたくなることもあるでしょう。
こうすることで、繰り返し表示される大量のコンテンツや複雑な表示ロジックを
ひとつにまとめることができます。
しかし、この方法はパフォーマンスに影響を及ぼします。
というのも、partial ヘルパーをループ内で毎回実行することになるからです。
PartialLoop ビューヘルパーは、
この問題を解決します。これを使用すると、反復処理可能な内容
(配列、あるいは Iterator を実装したオブジェクト)
をモデルに渡せるようになります。
そしてその各要素が partial スクリプトへモデルとして渡されます。
各要素の内容は、Partial
ビューヘルパーが受け付ける任意の形式のモデルとできます。
<?php // partialLoop.phtml ?>
<dt><?php
echo $this->
key ?></dt>
<dd><?php
echo $this->
value ?></dd>
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>
Example #10 他のモジュールの Partial のレンダリング
時には partial が別のモジュールに存在することもあるでしょう。
そのモジュールの名前がわかっていれば、モジュール名を
partial() あるいは partialLoop()
の 2 番目の引数として渡し、
$model を 3 番目の引数に移動させることができます。
たとえば、'list' モジュールにある pager というスクリプトを使用したい場合は、
次のようにします。
<?php echo $this->
partial('pager.phtml',
'list',
$pagerData) ?>
こうすると、特定の partial を他のモジュールで再利用できるようになります。
再利用可能な partial は、共有のビュースクリプトのパスに配置することをおすすめします。
Placeholder ヘルパー
Placeholder ビューヘルパーは、
ビュースクリプトとビューのインスタンスとの間でコンテンツを永続化させます。
それ以外の便利な機能としては次のようなものがあります。
たとえばコンテンツの集約、ビュースクリプトの内容をキャプチャして後で再利用、
コンテンツの前後へのテキストの追加 (そして集約したコンテンツ間のセパレータの追加)
などです。
Example #11 プレースホルダの基本的な使用法
プレースホルダの基本的な使用法は、ビューのデータを永続化させることです。
Placeholder ヘルパーを起動する際にプレースホルダ名を指定し、
ヘルパーはプレースホルダコンテナオブジェクトを返します。
これを処理するなり、単純に echo するなりして使用できます。
<?php $this->placeholder('foo')->set("Some text for later") ?>
<?php
echo $this->
placeholder('foo');
// 出力は "Some text for later" となります
?>
Example #12 プレースホルダによるコンテンツの集約
プレースホルダによるコンテンツの集約も、時には便利です。
たとえば、ビュースクリプトで変数の配列を保持し、
後で表示するためのメッセージを取得しておくと、
それをどのようにレンダリングするかを後で決めることができます。
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');
?>
Example #13 プレースホルダによるコンテンツのキャプチャ
時には、プレースホルダの中身を
テンプレートに渡しやすいようビュースクリプトで保持することもあるでしょう。
Placeholder ビューヘルパーは、
任意のコンテンツをキャプチャして後でレンダリングできます。
そのために使用する API は次のようなものです。
-
captureStart($type, $key) は、
コンテンツのキャプチャを開始します。
$type は、
Placeholder の定数 APPEND あるいは
SET のいずれかとなります。APPEND
を指定すると、キャプチャされたコンテンツが
プレースホルダ内の現在のコンテンツの末尾に追加されます。
SET の場合は、
キャプチャされたコンテンツをそれ単体でプレースホルダの値として使用します
(それまでに登録されていたコンテンツを上書きします)。
デフォルトの $type は
APPEND です。
$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 ヘルパー
の具象実装です。
Example #14 Doctype ヘルパーの基本的な使用法
doctype は、いつでも指定できます。
しかし、doctype によって出力を切りかえるヘルパーを使用する場合は
まず doctype を設定してからでないと動作しません。もっともシンプルな使用法は、
レイアウトスクリプトの先頭で指定と出力を同時に行うことでしょう。
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype('XHTML1_STRICT');
そして、それをレイアウトスクリプトの先頭で表示します。
<?php echo $this->
doctype() ?>
doctype を知りたくなったら、オブジェクトの
getDoctype() をコールします。
このオブジェクトは、ヘルパーを起動した際に取得できるものです。
$doctype = $view->doctype()->getDoctype();
?>
一般的な使用法としては、doctype が XHTML
か否かを調べるということがあります。それ用のメソッドとしては
isXhtml() があります。
if ($view->doctype()->isXhtml()) {
// 何かをします
}
doctype が HTML5 文書を表すかどうかチェックすることもできます。
if ($view->doctype()->isHtml5()) {
// 何かをします
}
Example #16 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.
Example #17 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" />
*/
Note:
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.
WarningUse 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.
Example #18 Advanced Usage of Gravatar View Helper
There are several ways to configure the returned gravatar. In most cases, you may either
pass an array of options as a second argument to the helper, or call methods on the
returned object in order to configure it.
-
The img_size option can be used to specify an alternate
height; alternately, call setImgSize().
-
The secure option can be used to force usage of SSL in
the returned image URI by passing a boolean true value (or
disabling SSL usage by passing false). Alternately, call
the setSecure() method. (By default, the setting
follows the same security as the current page request.)
-
To add attributes to the image, pass an array of key/value pairs as the
third argument to the helper, or call the
setAttribs() method.
// 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
ヘルパー の具象実装です。
Example #19 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() ?>
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
はその要素に使用したいクライアント側のスクリプトとなります。
Note: 条件コメントの設定
HeadScript
では、script タグを条件コメントで囲むことができます。
そうすれば、特定のブラウザでだけスクリプトを実行しないこともできます。
これを使用するには conditional タグを設定し、条件をメソッドコール時の
$attrs パラメータで渡します。
Example #22 Headscript で条件コメントを使う例
// スクリプトを追加します
$this->headScript()->appendFile(
'/js/prototype.js',
'text/javascript',
array('conditional' =>
'lt IE 7')
);
Note: 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.
Example #23 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'
のいずれかでなければなりません。
HeadScript
は append() や
offsetSet()、 prepend()、そして set()
をそれぞれオーバーライドして、上にあげた特別なメソッドを使用させるようにします。
内部的には、各項目を stdClass
のトークンとして保管し、
あとで itemToString() メソッドでシリアライズします。
これはスタック内の項目についてチェックを行い、
オプションでそれを修正したものを返します。
HeadScript
ヘルパーは、
Placeholder
ヘルパー の具象実装です。
Note: HTML Body スクリプトでの InlineScript の使用
HTML の body
部にスクリプトを埋め込みたい場合は、
HeadScript
の姉妹版である InlineScript
を使わなければなりません。
スクリプトをドキュメントの最後のほうに配置するようにすると、
ページの表示速度が向上します。特に、
サードパーティのアクセス解析用スクリプトを使用する場合などにこの効果が顕著にあらわれます。
Note: すべての属性はデフォルトで無効
デフォルトでは、HeadScript
がレンダリングする
<script>
の属性は W3C
に認められているものだけです。
'type' や 'charset'、'defer'、'language' そして 'src' が該当します。
しかし、Javascript のフレームワーク
(» Dojo など)
では独自の属性を用いることでその挙動を変更しています。
このような属性を許可するには、
setAllowArbitraryAttributes() メソッドを使用します。
$this->headScript()->setAllowArbitraryAttributes(true);
Example #24 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() ?>
Example #25 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>
要素に埋め込みます。
Note: 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 のすべてが使用可能です。
Note: 条件コメントの設定
HeadStyle では、script タグを条件コメントで囲むことができます。
そうすれば、特定のブラウザでだけスクリプトを実行しないこともできます。
これを使用するには conditional タグを設定し、条件をメソッドコール時の
$attributes パラメータで渡します。
Example #26 Headstyle で条件コメントを使う例
// スクリプトを追加します
$this->
headStyle()->
appendStyle($styles,
array('conditional' =>
'lt IE 7'));
HeadStyle はスタイル宣言のキャプチャも行います。
これは、宣言をプログラム上で作成してからどこか別の場所で使いたい場合に便利です。
使用法は、以下の例で示します。
headStyle() メソッドを使うと、宣言の要素を手っ取り早く追加できます。
シグネチャは
headStyle($content$placement = 'APPEND', $attributes = array())
です。$placement には 'APPEND'、'PREPEND' あるいは 'SET'
のいずれかを指定します。
HeadStyle は append() や
offsetSet()、 prepend()、そして set()
をそれぞれオーバーライドして、上にあげた特別なメソッドを使用させるようにします。
内部的には、各項目を stdClass のトークンとして保管し、
あとで itemToString() メソッドでシリアライズします。
これはスタック内の項目についてチェックを行い、
オプションでそれを修正したものを返します。
HeadStyle ヘルパーは、
Placeholder
ヘルパー の具象実装です。
Note: デフォルトで使用される 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.
Example #27 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() ?>
Example #28 HeadStyle ヘルパーによるスタイル宣言のキャプチャ
時には CSS のスタイル宣言をプログラムで生成しなければならないこともあるでしょう。
文字列の連結やヒアドキュメント等を使っても構いませんが、
ふつうにスタイルを作成してそれを PHP のタグに埋め込めればより簡単です。
HeadStyle は、スタックにキャプチャすることでこれを実現します。
<?php $this->headStyle()->captureStart() ?>
body {
background-color:
<?php echo $this->
bgColor ?>;
}
<?php $this->headStyle()->captureEnd() ?>
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.
Example #29 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 つのヘルパーの例だけを紹介します。
このヘルパーを使うと、Flash をページの中に簡単に埋め込めるようになります。
リソースの URI を引数として渡すだけの簡単な作業です。
<?php echo $this->
htmlFlash('/path/to/flash.swf');
?>
<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() ヘルパーで紹介します。
Example #31 追加属性を渡すことによるオブジェクトのカスタマイズ
オブジェクトヘルパーの最初の引数は常に必須です。
これは、埋め込みたいリソースの URI となります。
2 番目の引数は htmlObject() ヘルパーの場合のみ必須となります。
それ以外のヘルパーはこの引数の正確な値を既に知っているからです。
3 番目の引数には、object 要素の属性を渡します。
キー/値 のペア形式の配列のみを受け付けます。
属性の例としては、たとえば classid
や codebase などがあります。
4 番目の引数も同様に キー/値 のペア形式の配列のみを受け取り、
それを使用して <param>
要素を作成します。例を参照ください。
最後に、オプションでそのオブジェクトの追加コンテンツを指定できます。
これらすべての引数を使用した例をごらんください。
'/path/to/file.ext',
'mime/type',
'attr1' => 'aval1',
'attr2' => 'aval2'
),
'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() メソッドを使用します。
Note: HTML Body スクリプトでの InlineScript の使用法
InlineScript は、スクリプトを HTML の
body 部に埋め込みたいときに使用します。
スクリプトをドキュメントの最後のほうに配置するようにすると、
ページの表示速度が向上します。特に、
サードパーティのアクセス解析用スクリプトを使用する場合などにこの効果が顕著にあらわれます。
JS ライブラリの中には、 HTML の head
で読み込まなければならないものもあります。そのような場合は
HeadScript
を使用します。
RenderToPlaceholder Helper
Renders a template (view script) and stores the rendered output as a
placeholder variable for later use.
Note:
The helper uses the Placeholder helper
and his Capture methods.
Example #32 Basic Usage of RenderToPlaceholder
<?php
// View script (backlink.phtml):
'<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) ?>
Note: レイアウトの維持、および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 を設定します。
'enableJsonExprFinder' => true,
'keepLayouts' => true,
)) ?>
Note: 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().
Example #33 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.
Note:
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.
*/
'label' => 'Home',
'title' => 'Go Home',
'module' => 'default',
'controller' => 'index',
'action' => 'index',
'order' => -100 // make sure home is the first page
),
'label' => 'Special offer this week only!',
'module' => 'store',
'controller' => 'offer',
'action' => 'amazing',
'visible' => false // not visible
),
'label' => 'Products',
'module' => 'products',
'controller' => 'index',
'action' => 'index',
'label' => 'Foo Server',
'module' => 'products',
'controller' => 'server',
'action' => 'index',
'label' => 'FAQ',
'module' => 'products',
'controller' => 'server',
'action' => 'faq',
'canonical' => 'http://www.example.com/?page=faq',
'module' => 'products',
'controller' => 'server',
'action' => 'faq',
'params' =>
array('format' =>
'xml')
)
)
),
'label' => 'Editions',
'module' => 'products',
'controller' => 'server',
'action' => 'editions'
),
'label' => 'System Requirements',
'module' => 'products',
'controller' => 'server',
'action' => 'requirements'
)
)
),
'label' => 'Foo Studio',
'module' => 'products',
'controller' => 'studio',
'action' => 'index',
'label' => 'Customer Stories',
'module' => 'products',
'controller' => 'studio',
'action' => 'customers'
),
'label' => 'Support',
'module' => 'prodcts',
'controller' => 'studio',
'action' => 'support'
)
)
)
)
),
'label' => 'Company',
'title' => 'About us',
'module' => 'company',
'controller' => 'about',
'action' => 'index',
'label' => 'Investor Relations',
'module' => 'company',
'controller' => 'about',
'action' => 'investors'
),
'label' => 'News',
'class' => 'rss', // class
'module' => 'company',
'controller' => 'news',
'action' => 'index',
'label' => 'Press Releases',
'module' => 'company',
'controller' => 'news',
'action' => 'press'
),
'label' => 'Archive',
'route' => 'archive', // route
'module' => 'company',
'controller' => 'news',
'action' => 'archive'
)
)
)
)
),
'label' => 'Community',
'module' => 'community',
'controller' => 'index',
'action' => 'index',
'label' => 'My Account',
'module' => 'community',
'controller' => 'account',
'action' => 'index',
'resource' => 'mvc:community.account' // resource
),
'label' => 'Forums',
'uri' => 'http://forums.example.com/',
'class' => 'external' // class
)
)
),
'label' => 'Administration',
'module' => 'admin',
'controller' => 'index',
'action' => 'index',
'resource' => 'mvc:admin', // resource
'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',
'module' => 'company',
'controller' => 'news',
'action' => 'archive',
'year' =>
(int
) date('Y') -
1
),
)
);
// 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
' > '
.
-
{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.
Example #34 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> > <a href="/products/server">Foo Server</a> > FAQ
Example #35 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> > <a href="/products/server">Foo Server</a> > FAQ
Example #36 Customize breadcrumbs output
This example shows how to customze breadcrumbs output by
specifying various options.
In a view script or layout:
<?php
->breadcrumbs()
->setLinkLast(true) // link last page
->setMaxDepth(1) // stop at level 1
->setSeparator(' ▶' . PHP_EOL); // cool separator with newline
?>
Output:
<a href="/products">Products</a> ▶
<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.
Example #37 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.
$partial = ;
echo $this->
navigation()->
breadcrumbs()
->
setPartial(array('breadcrumbs.phtml',
'default'));
Contents of
application/modules/default/views/breadcrumbs.phtml
:
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').
Note:
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.
Example #38 Specify relations in pages
This example shows how to specify relations in pages.
$container =
new Zend_Navigation
(array(
'label' => 'Relations using strings',
'alternate' => 'http://www.example.org/'
),
'alternate' => 'http://www.example.net/'
)
),
'label' => 'Relations using arrays',
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
)
)
),
'label' => 'Relations using configs',
'alternate' =>
new Zend_Config
(array(
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
))
)
),
'label' => 'Relations using pages instance',
'alternate' => Zend_Navigation_Page::
factory(array(
'label' => 'Example.org',
'uri' => 'http://www.example.org/'
))
)
)
));
Example #39 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">
Example #40 Specify which relations to render
This example shows how to specify which relations to find
and render.
$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">
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)
.
Note:
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)
.
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.
Example #52 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):
->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.
->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>
Note: 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_Translate のインスタンスを使用する方法をおすすめします。
アダプタをレジストリに追加する際に、使用するロケールを選択できます。
Note:
ここで言語ではなくロケールと言っているのは、
言語には地域を含む可能性があるからです。
たとえば英語は様々な地域で話されています。
イギリス英語やアメリカ英語など複数の翻訳が存在します。
そこで、ここでは "言語" と言わずに "ロケール" としているのです。
登録済みのインスタンスを使用するには、まず Zend_Translate あるいは
Zend_Translate_Adapter のインスタンスを作成し、
それを Zend_Registry に登録します。登録する際のキーとして
Zend_Translate を使用します。
// サンプルアダプタ
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' =>
array('simple' =>
'einfach'),
'locale' => 'de'
)
);
Zend_Registry::set('Zend_Translate', $adapter);
// ビューの中で
echo $this->
translate('simple');
// これは 'einfach' を返します
流れるようなインターフェイスのほうがなじみがあるという場合は、
ビューの中でインスタンスを作成し、ヘルパーのインスタンスは後で作成することもできます。
流れるようなインターフェイスで Zend_Translate あるいは
Zend_Translate_Adapter のインスタンスを作成するには、
パラメータを指定せずにヘルパーをコールし、それから
setTranslator() メソッドをコールします。
// ビューの中で
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' =>
array('simple' =>
'einfach'),
'locale' => 'de'
)
);
$this->translate()->setTranslator($adapter)->translate('simple');
// これは 'einfach' を返します
ヘルパーを Zend_View なしで使用すると、
ヘルパーを直接使用することもできます。
// サンプルアダプタ
$adapter = new Zend_Translate(
'adapter' => 'array',
'content' =>
array('simple' =>
'einfach'),
'locale' => 'de'
)
);
// アダプタを初期化します
$translate = new Zend_View_Helper_Translate($adapter);
print $translate->
translate('simple');
// これは 'einfach' を返します
Zend_View は使わないけれど、
翻訳した結果がほしいという場合にこの方式を使用します。
これまで見てきたように、 translate() メソッドは翻訳を返します。
翻訳アダプタのメッセージ ID を指定してこれをコールします。
さらに、翻訳文字列の中のパラメータを置換することも可能です。
パラメータの値を指定する方法には二通りあります。
パラメータのリストを指定する方法か、あるいはパラメータの配列を指定する方法です。
たとえば次のようになります。
単一のパラメータを使用するには、単にそれをメソッドに追加します。
// ビューの中で
$date = "Monday";
$this->translate("Today is %1\$s", $date);
// これは 'Heute ist Monday' を返します
Note:
パラメータの値にテキストを使用する場合は、
このパラメータの値も翻訳しなければならないことに注意しましょう。
パラメータのリストを使用して、それをメソッドに追加することもできます。
// ビューの中で
$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' を返します
パラメータの配列を使用して、それをメソッドに追加することもできます。
// ビューの中で
$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' を返します
翻訳のロケールを変更しなければならないこともあるでしょう。
翻訳単位で動的に変更することもできますが、
静的に変更してそれ以降のすべての翻訳に適用させることもできます。
そして、パラメータリスト型あるいはパラメータ配列型のどちらの形式でもそれを使用できます。
どひらの形式の場合も、ロケールは最後のパラメータとして指定します。
// ビューの中で
$date =
array("Monday",
"April",
"11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it');
この例は、指定したメッセージ ID に対応するイタリア語の翻訳を返します。
しかし、イタリア語を返すのはこのときだけです。
次の翻訳では、アダプタに設定されているロケールを使用します。
通常は、使用したいロケールを翻訳アダプタに設定してからレジストリに追加します。
しかし、ロケールの設定をヘルパー内で行うこともできます。
// ビューの中で
$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() もあります。
Example #61 現在設定されているロケールの取得
// ビューの中で
$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.