summaryrefslogtreecommitdiffstats
path: root/system/classes/view.php
blob: 8dbb85e2864d15dde9903f1cf9afc7fd72de1e1c (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
<?php

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

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

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

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

    /**
     * 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 {$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);
		$out = ob_get_contents();
		ob_end_clean();
		return $out;
	}

    /**
     * Constructs the view
     * 
     * @param string   $name The name of the template to use
     * @return View    
     * @access public    
     * @throws Exception If specified template is not found
     * @static 
     */
	public static function get($name){
		$view = new View();
		$view->name = $name;
		$file = Misc::find_file('views', $name);
		
		if ($file == false)
			throw new Exception("View {$name} not found.");
			
		$view->path=$file;
		return $view;
	}
}