類定義和構造函數
1.Smarty作為MVC架構中的試圖部分在Zend框架中要實現 Zend_VIEw_Abstract類
class Travello_View_Smarty extends Zend_VIEw_Abstract { private $_smarty = false; public function __construct($data = array()) { parent::__construct($data);
// 從對象倉庫中獲取配置對象 $config = Zend::registry('config'); $this->_smarty = new Smarty(); $this->_smarty->caching = $config->getSetting('smarty', 'caching'); $this->_smarty->cache_lifetime = $config->getSetting('smarty', 'cache_lifetime'); $this->_smarty->template_dir = $config->getSetting('smarty', 'template_dir'); $this->_smarty->compile_dir = $config->getSetting('smarty', 'compile_dir'); $this->_smarty->config_dir = $config->getSetting('smarty', 'config_dir'); $this->_smarty->cache_dir = $config->getSetting('smarty', 'cache_dir'); }
2.實現 _run() 方法
_run()是唯一的要在Zend_VIEw_Abstract子類中實現的方法.他在render()方法中自動調用.我的實現僅使用display()方法生成和輸出模板
protected function _run($template)
{
$this->_smarty->display($template);
}
3.重寫assign()方法
重寫Zend_VIEw_Abstract中的assign()方法.
public function assign($var) {
if (is_string($var)) {
$value = func_get_arg(1);
$this->_smarty->assign($var, $value); elseif (is_array($var)) {
foreach ($var as $key => $value) {
$this->_smarty->assign($key, $value); } else {
throw new Zend_VIEw_Exception('assign() expects a string or array, got ' . gettype($var));
}
}
4.重寫 escape()方法
public function escape($var) {
if (is_string($var)) {
return parent :: escape($var); elseif (is_array($var)) {
foreach ($var as $key => $value) {
$var[$key] = $this->escape($value); } else {
return $var; }