view_class.php
2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
/**
 * Tiny - A PHP Framework For Web Artisans
 * @author Tiny <tinylofty@gmail.com>
 * @copyright Copyright(c) 2010-2014 http://www.tinyrise.com All rights reserved
 * @version 1.0
 */
/**
 * 视图类
 * 
 * @author Tiny
 * @class View
 */
class View
{
	//url中接收view文件有参数名
	private $viewParam = 'view';
	//默认的视图文件
	private $defauleView = 'index';
	//view文件
	private $view;
	//viewPath
	private $viewPath;
	private $layout;
	private $tplfile;
    /**
     * 构造函数
     * 
     * @access public
     * @param mixed $tpl
     */
	public function __construct($tpl)
	{
		$this->tplfile = Tiny::app()->getRuntimePath().$tpl.'.php';
		if(!file_exists($this->tplfile) || filemtime($this->tplfile)<filemtime($tpl))
		{
			$file = new File($this->tplfile,'w+');
			$template = $file->getContents($tpl);
			$t = new Tag();
			$tem = $t->resolve($template);
			$file->write($tem);
		}
	}
    /**
     * 运行入口
     * 
     * @access public
     * @return mixed
     */
	public function run()
	{
		$this->resolveView($this->getRequestedView());
		$controller=$this->getController();
		if($this->layout!==null)
		{
			$layout=$controller->layout;
			$controller->layout=$this->layout;
		}
		if(!$event->handled)
		{
			if($this->renderAsText)
			{
				$text=file_get_contents($controller->getViewFile($this->view));
				$controller->renderText($text);
			}
			else
				$controller->render($this->view);
		}
		if($this->layout!==null)
			$controller->layout=$layout;
	}
    /**
     * 渲染视图
     * 
     * @access protected
     * @param mixed $viewPath
     * @return mixed
     */
	protected function resolveView($viewPath)
	{
		if(preg_match('/^\w[\w\.\-]*$/',$viewPath))
		{
			$view=strtr($viewPath,'.','/');
			if(!empty($this->basePath)) $view=$this->basePath.'/'.$view;
			if($this->getController()->getViewFile($view)!==false)
			{
				$this->view=$view;
				return;
			}
		}
	}
    /**
     * 取得请求视图文件
     * 
     * @access public
     * @return mixed
     */
	public function getRequestedView()
	{
		if($this->viewPath===null)
		{
			if(!is_null(Req::args($this->viewParam)))
				$this->viewPath=Req::args($this->viewParam);
			else
				$this->viewPath=$this->defaultView;
		}
		return $this->viewPath;
	}
    /**
     * 渲染数据
     * 
     * @access public
     * @param array $data
     * @return mixed
     */
	public function render($data=array())
	{
		extract($data);
		include ($this->tplfile);
	}
}
?>