<?php
abstract class Action extends Base {
	protected $data = array(); // 数据信息,传递给视图
	public function __construct($action = '') {
		if ($action) $this -> action = $action; //当前方法
		$this -> forward = trim(R('forward')); //前往
		$this -> referer = isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:''; //来源
		$this -> isSubmit = isset($_POST['submit'])?true:isset($_GET['submit'])?true:false; //是否提交
		// 控制器初始化
		if (method_exists($this, '_initialize')) $this -> _initialize();
	}
	protected function assign($key, $value) {
		$this -> data[$key] = $value;
	}
	// 获取模板执行结果
	protected function fetch($tpl, $isKeep = false) {
		ob_start();
		$this -> display($tpl, $isKeep);
		$data = ob_get_contents();
		ob_clean();
		return $data;
	}
	// 生成视图, $tpl 模板, $isKeep 是否保留数据
	protected function display($tpl, $isKeep = false) {
		if (R('m')) $m = strtolower(R('m')); // 可以在程序中再次指定
		if (isset($this -> data['extract'])) {
			extract($this -> data['extract'], EXTR_SKIP);
			if (!$isKeep) unset($this -> data['extract']);
		}
		if (!empty($this -> data)) {
			extract($this -> data, EXTR_OVERWRITE);
			if (!$isKeep) $this -> data = array();
		}
		if (empty($config)) $config = C(); //可以由$this -> assign('config', $config)指定
		$charset = C('APP_CHARSET', 1);
		$referer = $this -> referer; //来源
		$forward = $this -> forward; //前往
		$a = preg_replace("/[A-Z]/", "_\\0", $this -> action);
		$a = strtolower(trim($a, '_')); //等同于URL参数a
		$c = strtolower(substr(get_class($this), 0, -6)); //当前控制器
		if (empty($catid)) $catid = 0;
		include App :: tpl($tpl);
	}
	// 提示框
	protected function showMsg($msg, $url = 'back', $delay = 2000) {
		if ($url) {
			$msg .= '<script type="text/javascript">';
			if ($url == 'back') $url = 'javascript:history.go(-1);';
			elseif ($url == 'close') $url = 'javascript:window.close();';
			elseif ($url == 'reload') $url = 'javascript:location.reload();';
			if ($delay > 0) $msg .= 'setTimeout("document.location=\'' . $url . '\'", ' . $delay . ');';
			else $msg .= 'document.location="' . $url . '";';
			$msg .= '</script>';
		}
		$this -> assign('msg', $msg);
		$this -> assign('url', $url);
		$this -> display('showmsg');
		exit;
	}
}