<?php
namespace KIF\Core;
use Smarty;

include KIF_PATH . "/smarty/Smarty.class.php";

use KIF\Core\Config;

/**
 * 定义MVC里的V,即View
 * @author gaoxiaogang@gmail.com
 */
class View extends Smarty
{
	/**
	 *
	 * 存放要自动注册的 函数 信息
	 * @var array
	 */
	static private $auto_registers = array();

	private $tpl_type ;  //静态文件的类型
	
	private $directory;  //模板子目录
	
	public function __construct($directory = '')
	{
		$this->left_delimiter = "<{";
		$this->right_delimiter = "}>";
		$this->directory = $directory;

		foreach (self::$auto_registers as $tmpV) {
			$this->register_function($tmpV['smarty_func'], $tmpV['php_func'], $tmpV['cacheable'], $tmpV['cache_attrs']);
		}
	}

	/**
	 *
	 * 类方法.通知模版引擎自动注册函数
	 * 目的:在使用项目处,方便的自动注册一些全局性的模版函数
	 * @param string $function 注册后,模版使用时的 函数名
	 * @param string $function_impl 要被注册的php函数名
	 * @param bookean $cacheable
	 * @param unknown_type $cache_attrs
	 * @author gxg@gaojie100.com
	 */
	static function auto_register_function($function, $function_impl, $cacheable=true, $cache_attrs=null) {
		self::$auto_registers[] = array(
			'smarty_func'	=> $function,
			'php_func'		=> $function_impl,
			'cacheable'		=> $cacheable,
			'cache_attrs'	=> $cache_attrs,
		);
	}

	/**
	 * 
	 * 渲染模版并打印出来
	 * @param string $tpl 模版文件名
	 * @param unknown_type $cache_id
	 * @param unknown_type $compile_id
	 * @return NULL 无返回值
	 */
	public function d($tpl, $cache_id = null, $compile_id = null)
	{
		$this->r($tpl, $cache_id , $compile_id ,true);
	}
	
	/**
	 * 
	 * 渲染模版。默认时返回内容
	 * @param string $tpl 模版文件名
	 * @param unknown_type $cache_id
	 * @param unknown_type $compile_id
	 * @param boolean $display 是否打印出来?
	 * @return string
	 */
	public function r($tpl, $cache_id = null, $compile_id = null, $display = false)
	{
		$smarty_config = Config::getInstance()->get('smarty');
		
		$this->template_dir = $smarty_config['template_dir'];
		$this->compile_dir = $smarty_config['compile_dir'];
		$this->tpl_type = $smarty_config['tpl_type'] ? $smarty_config['tpl_type'] : 'html';
		$content = $this->fetch($tpl . "." . $this->tpl_type, $cache_id , $compile_id , $display);
		return $content;
	}
}