-
Notifications
You must be signed in to change notification settings - Fork 3
/
Repository.php
118 lines (107 loc) · 2.44 KB
/
Repository.php
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
<?php
/**
* Repository for GDS Demo
*
* @author Tom Walder
*/
namespace GDS\Demo;
use GDS\Schema;
use GDS\Store;
class Repository
{
/**
* Memcache instance
*
* @var \Memcached|null
*/
private $obj_cache = NULL;
/**
* GDS Store instance
*
* @var Store|null
*/
private $obj_store = NULL;
/**
* @return \Memcached|null
*/
private function getCache()
{
if(NULL === $this->obj_cache) {
$this->obj_cache = new \Memcached();
}
return $this->obj_cache;
}
/**
* Get the most recent posts. From memcache ideally.
*
* @return array
*/
public function getRecentPosts()
{
$arr_posts = $this->getCache()->get('recent');
if(is_array($arr_posts)) {
return $arr_posts;
} else {
return $this->updateCache();
}
}
/**
* Update the cache from Datastore
*
* @return array
*/
private function updateCache()
{
$obj_store = $this->getStore();
$arr_posts = $obj_store->query("SELECT * FROM Guestbook ORDER BY posted DESC")->fetchPage(POST_LIMIT);
$this->getCache()->set('recent', $arr_posts);
return $arr_posts;
}
/**
* Insert the entity (plus limit the data to the same values as the form)
*
* @param $str_name
* @param $str_message
* @param $str_ip
*/
public function createPost($str_name, $str_message, $str_ip)
{
$obj_store = $this->getStore();
$obj_store->upsert($obj_store->createEntity([
'posted' => date('Y-m-d H:i:s'),
'name' => $str_name,
'message' => $str_message,
'ip' => $str_ip
]));
// Update the cache
$this->updateCache();
}
/**
* Configure and return a Store
*
* @return Store
*/
private function getStore()
{
if(NULL === $this->obj_store) {
$this->obj_store = new Store($this->makeSchema());
}
return $this->obj_store;
}
/**
* Build a schema for Guest book entries
*
* the posted datetime as an indexed field
*
* @return Schema
*/
private function makeSchema()
{
return (new Schema('Guestbook'))
->addDatetime('posted')
->addString('name', FALSE)
->addString('message', FALSE)
->addString('ip')
;
}
}