Zend_View 抽象出 Zend_View_Interface,實作該介面即可整合第三方模板引擎(如 Smarty)。核心方法包括:getEngine()、setScriptPath()、assign()、render() 等。
zf_demo1/ ├── application/ │ ├── configs/application.ini │ ├── controllers/IndexController.php │ └── views/scripts/index/index.tpl ├── library/ │ ├── Lq/View/Smarty.php (介面實作) │ └── smartylib/ (Smarty 庫) └── public/index.php
require_once 'smartylib/Smarty.class.php';
class Lq_View_Smarty implements Zend_View_Interface {
protected $_smarty;
public function __construct($tmplPath = null, $extraParams = []) {
$this->_smarty = new Smarty();
if ($tmplPath) $this->setScriptPath($tmplPath);
foreach ($extraParams as $k => $v) $this->_smarty->$k = $v;
}
public function getEngine() { return $this->_smarty; }
public function setScriptPath($path) {
if (is_readable($path)) { $this->_smarty->template_dir = $path; return; }
throw new Exception('Invalid path');
}
public function getScriptPaths() { return [$this->_smarty->template_dir]; }
public function setBasePath($path, $prefix = 'Zend_View') { return $this->setScriptPath($path); }
public function addBasePath($path, $prefix = 'Zend_View') { return $this->setScriptPath($path); }
public function __set($key, $val) { $this->_smarty->assign($key, $val); }
public function __get($key) { return $this->_smarty->get_template_vars($key); }
public function __isset($key) { return null !== $this->_smarty->get_template_vars($key); }
public function __unset($key) { $this->_smarty->clear_assign($key); }
public function assign($spec, $val = null) {
is_array($spec) ? $this->_smarty->assign($spec) : $this->_smarty->assign($spec, $val);
}
public function clearVars() { $this->_smarty->clear_all_assign(); }
public function render($name) {
ob_start();
echo $this->_smarty->fetch($name);
return ob_get_clean();
}
}
[production] autoloadernamespaces.lq = "Lq_" pluginpaths.Lq_View_Smarty = "Lq/View/Smarty" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.params.displayExceptions = 1
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initSmarty() {
$smarty = new Lq_View_Smarty();
$smarty->setScriptPath(APPLICATION_PATH . '/views/scripts');
return $smarty;
}
}
class IndexController extends Zend_Controller_Action {
public function indexAction() {
$this->_helper->getHelper('viewRenderer')->setNoRender();
$this->view = $this->getInvokeArg('bootstrap')->getResource('smarty');
$this->view->book = 'Hello World!';
$this->view->author = 'by smarty';
$this->view->render('index/index.tpl');
}
}
{$book} {$author}
可修改 smartylib/Smarty.class.php 建構子設定編譯、快取、配置目錄等:
$this->setTemplateDir('/www/zf_demo1/temp/smarty/templates/')
->setCompileDir('/www/zf_demo1/temp/smarty/templates_c/')
->setCacheDir('/www/zf_demo1/temp/smarty/cache/')
->setConfigDir('/www/zf_demo1/temp/smarty/configs/');
更多 Zend Framework 相關教程請參考本站專題:《Zend FrameWork框架入門教程》、《php優秀開發框架總結》、《Yii框架入門及常用技巧總結》、《ThinkPHP入門教程》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》。