6.9視圖助手(Helper)
視圖指令碼裡經常有一些繁雜的事情,比如格式化日期、產生表單元素等等。這些可以用助手幫我們來完成。
助手類其實是一些以Zend_View_Helper_開頭的類,類名的最後一段是助手的名字,助手的名字必須是首字母大寫的,該類必須至少有一個以助手名字命名的方法。助手名通常是駝峰式命名,即它不會是大寫字母開頭的。類名是混合大小寫字格式。方法名也是駝峰式命名。
預設的助手的路徑通常指向Zend/View/Helper。即使用setHelperPath()方法重新指定了路徑,該路徑也會保持以使預設的助手能夠工作。
6.9.1ZF內建的助手
範例程式碼:
<?php
echo $this->form(’frm1′, array(’action’=>’action.php’, ‘method’=>’post’), false) .”/n”;
echo $this->formHidden(’id’, ’submited’);
$content = ‘Your Name:’ . $this->formText(’name’, ”, array(’size’ => 20)) .’<br>’;
$content .= ‘Password:’ . $this->formPassword(’pass’, ”, array(’size’ => 20));
echo $this->fieldset(’flst’, $content, array(’legend’=>’Name:’, ’style’=>’width:200pt’)) .’<br>’;
echo $this->formLabel(’email’, ‘Your Email:’);
echo $this->formText(’email’, ‘you@example.com’, array(’size’ => 32)) .’<br>’;
echo ‘Your Country:’;
echo $this->formSelect(’country’, ‘us’, null, $this->countries) .’<br>’;
echo ‘Would you like to opt in?’;
echo $this->formCheckbox(’opt_in’, ‘yes’, null, array(’yes’, ‘no’)) .’<br>’;
echo ‘Choose them:’;
echo $this->formMultiCheckbox(’chkbox’, ‘A’, null, array(’A'=>’valA’,'B’=>’valB’,'C’=>’valC’,'D’=>’valD’), ‘<br>’) .’<br>’;
echo ‘Choose one:’;
echo $this->formRadio(’radio’, ‘A’, null, array(’A'=>’valA’,'B’=>’valB’,'C’=>’valC’,'D’=>’valD’), ”) .’<br>’;
echo $this->htmlList($this->countries) .’<br>’;
echo $this->url(array(’k1′=>’v1′,’k2′=>’v2′,’k3′=>’v3′)) .’<br>’;
echo $this->formTextarea(’ta’, ”, array(’rows’=>’5′,’cols’=>’25′)) .’<br>’;
echo $this->formFile(’file’, ”, array()) .’<br>’;
echo $this->formButton(’btn’, ‘BUTTON’, array(’onClick’=>”));
echo $this->formSubmit(’OK’, ‘OK’);
echo $this->formReset(’reset’, ‘Reset’);
?>
6.9.2動作(Action)助手
允許我們在視圖指令碼裡執行某個控制器裡的動作方法。
樣本:
<div id=”sidebar right”>
<div class=”item”>
<?= $this->action(’assign1′, ‘Book’); ?>
</div>
</div>
6.9.3地區(Partial)助手
地區助手的基本用法是在它自己的視圖範圍內解析另一個模板的片段,類似視圖指令碼嵌套調用。
地區助手的基本用法:
樣本:
booklist.php檔案包含指令碼片段:
<?php
if ($this->books):
?>
<table border=1>
<tr>
<th>作者</th>
<th>書名</th>
</tr>
<?php
foreach ($this->books as $key => $val):
?>
<tr>
<td><?php echo $this->escape($val[’author’]) ?></td>
<td><?php echo $this->escape($val[’title’]) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
else:
?>
<p>There are no books to display.</p>
<?php
endif;
?>
在另一個視圖指令碼通過Partial助手調用booklist.php檔案:
<?= $this->partial(’booklist.php’, array(
‘books’ => array(
array(’author’=>’zhangqing’,'title’=>’《book for php》’),
array(’author’=>’zhangking’,'title’=>’《book for JSP》’),
array(’author’=>’zhanghing’,'title’=>’《book for ASP.NET》’),
)));
?>
<?php echo str_repeat(’-', 60). ‘<br>’; ?>
<?php
$model = array(
array(’key’ => ‘Mammal’, ‘value’ => ‘Camel’),
array(’key’ => ‘Bird’, ‘value’ => ‘Penguin’),
array(’key’ => ‘Reptile’, ‘value’ => ‘Asp’),
array(’key’ => ‘Fish’, ‘value’ => ‘Flounder’),
);
?>
<dl>
<?= $this->partialLoop(’partialLoop.phtml’, $model) ?>
</dl>
使用 PartialLoop 來解析可迭代的(Iterable)的模型
樣本:
<?php
$model = array(
array(’key’ => ‘Mammal’, ‘value’ => ‘Camel’),
array(’key’ => ‘Bird’, ‘value’ => ‘Penguin’),
array(’key’ => ‘Reptile’, ‘value’ => ‘Asp’),
array(’key’ => ‘Fish’, ‘value’ => ‘Flounder’),
);
?>
<dl>
<?= $this->partialLoop(’partialLoop.phtml’, $model) ?>
</dl>
以上代碼中partialLoop 調用了以下partialLoop.phtml的內容:
<dt><?= $this->key ?></dt>
<dd><?= $this->value ?></dd>
6.9.4佔位(Placeholder)助手
樣本:
<?= $this->doctype(’XHTML1_STRICT’) ?>
<?php
// setting meta keywords
$this->headMeta()->appendName(’keywords’, ‘framework php productivity’);
$this->headMeta()->appendHttpEquiv(’expires’, ‘Wed, 26 Feb 1997 08:21:57 GMT’)
->appendHttpEquiv(’pragma’, ‘no-cache’)
->appendHttpEquiv(’Cache-Control’, ‘no-cache’);
$this->headMeta()->appendHttpEquiv(’Content-Type’, ‘text/html; charset=UTF-8′)
->appendHttpEquiv(’Content-Language’, ‘en-US’);
$this->headMeta()->appendHttpEquiv(’Refresh’, ‘3;URL=http://www.some.org/some.html’);
echo $this->headMeta();
$this->headScript()->appendFile(’/js/prototype.js’)
->appendScript(’xx.js’);
// Putting scripts in order
// place at a particular offset to ensure loaded last
$this->headScript()->offsetSetScript(100, ‘/js/myfuncs.js’);
// use scriptaculous effects (append uses next index, 101)
$this->headScript()->appendScript(’/js/scriptaculous.js’);
// but always have base prototype script load first:
$this->headScript()->prependScript(’/js/prototype.js’);
echo $this->headScript();
// setting links in a view script:
$this->headLink()->appendStylesheet(’/styles/basic.css’)
->headLink(array(’rel’ => ‘favicon’, ‘href’ => ‘/img/favicon.ico’), ‘PREPEND’)
->prependStylesheet(’/styles/moz.css’, ’screen’, true);
// rendering the links:
echo $this->headLink();
?>
<?php
$this->placeholder(’foo’)->setPrefix(”<ul>/n<li>”)
->setSeparator(”</li><li>/n”)
->setIndent(4)
->setPostfix(”</li></ul>/n”);
$this->placeholder(’foo’)->set(”Some text for later-1″);
$this->placeholder(’foo’)->bar = “Some text for later-2″;
echo $this->placeholder(’foo’);
$foo = $this->placeholder(’foo’);
echo $foo[0] .’<br>’;
echo $foo[’bar’] .’<br>’;
?>
<!– Default capture: append –>
<?php
$this->placeholder(’hoo’)->captureStart();
foreach ($this->data as $datum)
{
?>
<div class=”hoo”>
<h2><?= $datum[’title’] ?></h2>
<p><?= $datum[’content’] ?></p>
</div>
<?php
}
$this->placeholder(’hoo’)->captureEnd();
?>
<?php
echo $this->placeholder(’hoo’)
?>
<!– Capture to key –>
<?php
$this->placeholder(’woo’)->captureStart(’SET’, ‘data’);
foreach ($this->data as $datum):
?>
<div class=”woo”>
<h2><?= $datum[’title’] ?></h2>
<p><?= $datum[’content’] ?></p>
</div>
<?php
endforeach;
$this->placeholder(’woo’)->captureEnd();
?>
<?php
echo $this->placeholder(’woo’)->data;
?>
6.9.4自訂助手
編寫及調用自訂助手的方法:
The class name must, at the very minimum, end with the helper name itself, using MixedCaps. E.g., if you were writing a helper called “specialPurpose”, the class name would minimally need to be “SpecialPurpose”. You may, and should, give the class name a prefix, and it is recommended that you use ‘View_Helper’ as part of that prefix: “My_View_Helper_SpecialPurpose”. (You will need to pass in the prefix, with or without the trailing underscore, to addHelperPath() or setHelperPath()).
The class must have a public method that matches the helper name; this is the method that will be called when your template calls “$this->specialPurpose()”. In our “specialPurpose” helper example, the required method declaration would be “public function specialPurpose()”.
In general, the class should not echo or print or otherwise generate output. Instead, it should return values to be printed or echoed. The returned values should be escaped appropriately.
The class must be in a file named after the helper class. Again using our “specialPurpose” helper example, the file has to be named “SpecialPurpose.php”.
Place the helper class file somewhere in your helper path stack, and Zend_View will automatically load, instantiate, persist, and execute it for you.
樣本:
<?php
//Custom Helper “myFieldset”
echo $this->myFieldset(’This my custom Helper.’).’<br>’;
echo $this->myFieldset(’This my custom Helper.’).’<br>’;
echo $this->myFieldset(’This my custom Helper.’).’<br>’;
?>
調用代碼:
function customhelperAction()
{
$view = new Zend_View();
$view->setScriptPath(’views’);
$view->setHelperPath(’views/helpers’, ‘My_View_Helper’);
echo $view->render(’my_custom_helper.php’);
}
作者:張慶(網眼) 2008-7-28
來自“網眼視界”:http://blog.why100000.com
“十萬個為什麼”電腦學習網:http://www.why100000.com