1 <?php
2 class Controller {
3
4 public static $root;
5 public static $instance;
6
7 function __construct() {
8 set_exception_handler(array("Controller","exception_handle"));
9 self::$instance = $this;
10 self::$root = str_replace("\\","/",dirname(__FILE__))."/";
11 require(self::$root."../nm-settings.php");
12 require(self::$root."model.class.php");
13 $this->model = new Model;
14 }
15
16 function evaluate($matches) {
17 if(preg_match("/\s*import\s*:\s*/",$matches[1]) != false) {
18 $filename = preg_replace("/\s*import\s*:\s*/","",$matches[1]);
19 return $this->compile(file_get_contents(self::$root."templates/$filename.template.html"));
20 } else {
21 @eval("\$var = \$this->model->$matches[1];");
22 return isset($var) ? $var : "";
23 }
24 }
25
26 function compile($code) {
27 return preg_replace_callback("/\{!(\S*)\}/",array( &$this, 'evaluate'),$code);
28 }
29
30 function display($template,$cache=false,$expiry=300) {
31 $page = self::$root."cache/".md5($template.$_SERVER['SCRIPT_NAME']).".cache";
32 if($cache == true && file_exists($page) && (time()-$expiry) < filemtime($page)) {
33 include($page);
34 } else {
35 $content = $this->compile(file_get_contents(self::$root."templates/$template.template.html"));
36 echo $content;
37 if($cache == true) $this->write_cache($content,$page);
38 }
39 }
40
41 function write_cache($content,$page) {
42 file_put_contents($page,$content);
43 }
44
45 function assign($name,$value) {
46 $this->model->{$name} = $value;
47 }
48
49 function map($data) {
50 foreach($data as $var=>$value)
51 $this->assign($var,$value);
52 }
53
54 function load($name,$safename=NULL) {
55 $safename = (is_null($safename)) ? strtolower($name) : $safename;
56 require("proxy/".$name.".class.php");
57 eval("\$this->model->$safename = new $name;");
58 }
59
60 function inc($name) {
61 require("proxy/".$name.".class.php");
62 }
63
64 function getInstance() {
65 if(Controller::$instance === null) Controller::$instance = new Controller;
66 return Controller::$instance;
67 }
68
69 static function exception_handle($exception) {
70 ob_end_clean();
71 $app = Controller::$instance;
72 $app->assign("error",$exception->getMessage());
73 $app->display("error");
74 die();
75 }
76 }
77 ?>