也谈Zend构架与Smarty的集成配置
Zend架构是一个成熟、强大的PHP Web MVC的开发框架,而smarty是一个灵活、强大的模板引擎。如果将两者结合起来,将会使PHP的Web开发轻松不少,且上手也快。
对于Zend构架与Smarty的集成配置,网上也有不少文章说到,但我自己觉得都不够完整,且并不是真正、深入集成。我这里所说的方法,是彻底的集成,程序写法是Zend本身的带的view写法是一样的。
首先说一下总体目录结构:
其中,application目录中包括config目录、controllers目录、models目录等;cache目录用于smarty缓存;compile目录用于smarty编译目录;config目录放置smarty的配置;library目录放置Zend框架库及smarty库;public目录放置引导文件及js、css、images等公共文件;template目录放置.tpl模板文件。
首先修改配置文件来支持smarty模板库(就是application/configs/application.ini文件),添加如下内容:
smarty.class_path = "Smarty/Smarty.class.php" smarty.left_delimiter = "<*" smarty.right_delimiter = "*>" smarty.template_dir = APPLICATION_PATH "/../template" smarty.compile_dir = APPLICATION_PATH "/../compile" smarty.cache_dir = APPLICATION_PATH "/../cache" smarty.cache_lifetime = 600 smarty.caching = 0 smarty.config_dir = APPLICATION_PATH "/../config" |
第二,创建一个模板类文件Template,里面旋转初始smarty库的内容。这个文件里的类名我写为Zend_Templater,我把它放到library/Zend/下,这样它就会被自动加载:
<?php class Zend_Templater extends Zend_View_Abstract { protected $_path; protected $_engine; public function __construct() { $config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/application.ini', 'production'); require_once $config->smarty->class_path; $this->_engine = new Smarty(); $this->_engine->template_dir = $config->smarty->template_dir; $this->_engine->compile_dir = $config->smarty->compile_dir; $this->_engine->cache_dir = $config->smarty->cache_dir; $this->_engine->cache_lifetime = $config->smarty->cache_lifetime; $this->_engine->caching = $config->smarty->caching; $this->_engine->left_delimiter = $config->smarty->left_delimiter; $this->_engine->right_delimiter = $config->smarty->right_delimiter; $this->_engine->config_dir = $config->smarty->config_dir; } public function getEngine() { return $this->_engine; } public function __set($key, $val) { $this->_engine->assign($key, $val); } public function __get($key) { return $this->_engine->get_template_vars($key); } public function __isset($key) { return $this->_engine->get_template_vars($key) !== null; } public function __unset($key) { $this->_engine->clear_assign($key); } public function assign($spec, $value = null) { if (is_array($spec)) { $this->_engine->assign($spec); return; } $this->_engine->assign($spec, $value); } public function clearVars() { $this->_engine->clear_all_assign(); } public function render($name) { return $this->_engine->fetch(strtolower($name)); } public function _run() { } } ?> |
其实也可以不放置到Zend目录且支持自动加载此文章,请见另一篇文章让Zend框架自己加载自定义的类。
第三,修改引导文件,完成smarty与Zend的集成。修改Zend的引导文件index.php,添加支持smarty的视图类:
$vr = new Zend_Controller_Action_Helper_ViewRenderer(); $vr->setView(new Zend_Templater()); $vr->setViewSuffix('tpl'); Zend_Controller_Action_HelperBroker::addHelper($vr); |
到这里,已经完成Zend与smarty的集成。这样在controller文件中,可以如下的方式写代码:
$this->view->name = 'Zend与smarty的集成'; |
然后在你的tpl文件中,像如下的方式访问设置的变量:
<*if $name*> <*$name*> <*/if*> |
原创文章如转载,请注明:转载自张文杰的博客 [ http://zhangwenjie.net ]
本文链接地址:http://zhangwenjie.net/archives/355.html


