2009年2月25日星期三

Smarty and Zend_View integrantion

聚合使用 smarty

<?php
require_once ('Zend/View/Abstract.php');
class SmartyView extends Zend_View_Abstract
{
protected $_smarty;

public function __construct($config = array())
{
$this->_smarty = new Smarty();

if(!isset($config['compileDir']))
throw new Exception('compileDir is not set for '.get_class($this));
else
$this->_smarty->compile_dir = $config['compileDir'];

if(isset($config['configDir']))
$this->_smarty->config_dir = $config['configDir'];

if(isset($config['pluginsDir']))
$this->_smarty->plugins_dir[] = $config['pluginsDir'];

parent::__construct($config);
}

public function __set($key,$val)
{
parent::__set($key, $val);
$this->_smarty->assign($key,$val);
}

public function __isset($key)
{
$var = $this->_smarty->get_template_vars($key);
if($var)
return true;

return false;
}

public function __unset($key)
{
parent::__unset($key);
$this->_smarty->clear_assign($key);
}

public function assign($spec,$value = null)
{
if($value === null)
$this->_smarty->assign($spec);
else
$this->_smarty->assign($spec,$value);
}


public function clearVars()
{
$this->_smarty->clear_all_assign();
}

protected function _run()
{
$this->strictVars(true);

//why 'this'?
//to emulate standard zend view functionality
//doesn't mess up smarty in any way
$this->_smarty->assign_by_ref('this',$this);

$fileFullname = func_get_arg(0);
$templateDirs = $this->getScriptPaths();

//TODO: find more effective way to get correct template dir
$templateDir = $templateDirs[0];
$file = $fileFullname;
foreach ($templateDirs as $dir) {
if (preg_match("|^$dir|", $fileFullname)) {
$templateDir = $dir;
$file = substr($fileFullname,strlen($templateDir));
break;
}
}
//$file = substr(func_get_arg(0),strlen($templateDir));
//var_dump($templateDir, $file);
$this->_smarty->template_dir = $templateDir;
$this->_smarty->compile_id = $templateDir;

echo $this->_smarty->fetch($file);
}
}


初始化脚本中设置 view

//Create the view and set the compile dir to template_c
$view = new SmartyView(array(
'compileDir' => './template_c'
));

//Create a new ViewRenderer helper and assign our newly
//created SmartyView object as the view instance
$viewHelper = new Zend_Controller_Action_Helper_ViewRenderer($view);
$viewHelper->setViewSuffix('tpl');

//Save the helper to the HelperBroker
Zend_Controller_Action_HelperBroker::addHelper($viewHelper);

没有评论: