070be1fc266b3e18900e7c1a09fa3117196f8f43
[monitor.git] / www / database.php
1
2 <?php 
3
4 include 'monitorconfig.php';
5 define("PICKLE_PATH", MONITOR_DATA_ROOTWEB);
6
7 class Pickle
8 {
9         public function load($name)
10         {
11                 if ( ! $this->exists("production." . $name) )
12                 {
13                         print "Exception: No such file %s" . $name . "\n";
14                         return NULL;
15                 }
16                 $name = "production." . $name;
17                 $fname = $this->__file($name);
18                 $o = unserialize(file_get_contents($fname));
19
20                 return $o;
21         }
22         public function dump($name, $obj)
23         {
24                 if ( ! file_exists(PICKLE_PATH) )
25                 {
26                         if ( ! mkdir(PICKLE_PATH, 0777, True) )
27                         {
28                                 print "Exception: Unable to create directory :" . PICKLE_PATH . "\n";
29                         }
30                 }
31                 $name = "production." . $name;
32                 $fname = $this->__file($name);
33
34                 return file_put_contents($fname, serialize($obj));
35         }
36         private function __file($name)
37         {
38                 return sprintf("%s/%s.phpserial", PICKLE_PATH, $name);
39         }
40
41         public function exists($name)
42         {
43                 return file_exists($this->__file($name));
44         }
45
46         public function remove($name)
47         {
48                 return unlink($this->__file($name));
49         }
50
51         public function if_cached_else($cond, $name, $function)
52         {
53                 if ( $cond and $this->exists("production.%s" % $name) )
54                 {
55                         $o = $this->load($name);
56                 } else {
57                         $o = $function();
58                         if ($cond)
59                         {
60                                 $this->dump($name, $o); # cache the object using 'name'
61                         }
62                 }
63                 return o;
64         }
65 }
66
67 ?>