summaryrefslogtreecommitdiffstats
path: root/system/classes/view.php
blob: 49e9661a979e33eba54efab0bfa73bcb3deb549e (plain)
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
<?php

/**
 * Manages passing variables to templates and rendering them
 * @package Core
 */
class View
{

	/**
	 * Full path to template file
	 * @var string
	 * @access private
	 */
	protected $path;

	/**
	 * The name of the view.
	 * @var string
	 * @access public
	 */
	public $name;

	/**
	 * Stores all the variables passed to the view
	 * @var array
	 * @access protected
	 */
	protected $_data = array();

	/**
	 * File extension of the templates
	 * @var string
	 * @access protected
	 */
	protected $_extension = 'php';

	/**
	 * Constructs the view
	 *
	 * @param string   $name The name of the template to use
	 * @return View
	 * @throws Exception If specified template is not found
	 * @access protected
	 */
	protected function __construct($name)
	{
		$this->name = $name;
		$file = Misc::find_file('views', $name, $this->_extension);

		if ($file == false)
			throw new Exception("View {$name} not found.");

		$this->path = $file;
	}

	/**
	 * Manages storing the data passed to the view as properties
	 *
	 * @param string $key Property name
	 * @param string $val Property value
	 * @return void
	 * @access public
	 */
	public function __set($key, $val)
	{
		$this->_data[$key] = $val;
	}

	/**
	 * Manages accessing passed data as properties
	 *
	 * @param string   $key Property name
	 * @return mixed	Property value
	 * @access public
	 * @throws Exception If the property is not found
	 */
	public function __get($key)
	{
		if (isset($this->_data[$key]))
			return $this->_data[$key];
		throw new Exception("Value {$key} not set for view {$this->name}");
	}

	/**
	 * Renders the template, all dynamically set properties
	 * will be available inside the view file as variables.
	 * Example:
	 * <code>
	 * $view = View::get('frontpage');
	 * $view->title = "Page title";
	 * echo $view->render();
	 * </code>
	 *
	 * @return string Rendered template
	 * @access public
	 */
	public function render()
	{
		extract($this->_data);
		ob_start();
		include($this->path);
		return ob_get_clean();
	}

	/**
	 * Shorthand for constructing a view.
	 *
	 * @param string   $name The name of the template to use
	 * @return View
	 * @throws Exception If specified template is not found
	 * @static
	 * @access public
	 */
	public static function get($name)
	{
		$class = get_called_class();
		return new $class($name);
	}

}