MicroPHP 实战中级篇

集成Smarty

虽然我个人觉得Smarty之类的模板就是花瓶,但是很多人还是喜欢这类模板风格。

下面就介绍怎么集成Smarty。示例下载

原理很简单:

1.定义自己的控制器父类CommonController.class.php放在library里面。

2.CommonController重写父类WoniuController的view方法。

3.需要Smarty功能的控制器继承CommonController即可。

CommonController代码如下:

<?php
class CommonController extends WoniuController {
    private $smarty;
    private $tpl_ext = '.tpl';
    public function __construct() {
        parent::__construct();
        $this->helper('smarty/Smarty.class');
        $smarty = new Smarty;
        $view_dir = realpath(dirname(__FILE__) . '/../views');
        $cache_dir = realpath(dirname(__FILE__) . '/../cache/smarty');
        //$smarty->force_compile = true;
        $smarty->debugging = true;
        $smarty->caching = true;
        $smarty->cache_lifetime = 120;
        $smarty->setTemplateDir($view_dir);
        $smarty->setCompileDir($cache_dir . '/templates_c/');
        $smarty->setConfigDir($cache_dir . '/configs/');
        $smarty->setCacheDir($cache_dir . '/cache/');
        $this->smarty = &$smarty;
    }
    public function view($view_name, $data = null, $return = false) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $this->smarty->assign($key, $value);
            }
        }
        if ($return) {
            return $this->smarty->fetch($view_name . $this->tpl_ext);
        } else {
            $this->smarty->display($view_name . $this->tpl_ext);
        }
    }

}
上面只是个示例,可以根据自己情况在构造方法里面详细配置Smarty。