ShmCache.php
1.65 KB
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
<?php
namespace common\components\caching;
use yii\caching\Cache;
use yii\base\InvalidConfigException;
class ShmCache extends Cache
{
//memory size bytes,default 10MB
public $memSize = 10485760;
protected $shm;
/**
* Initializes this application component.
* It checks if extension required is loaded.
*/
public function init()
{
parent::init();
if (!extension_loaded('sysvshm')) {
throw new InvalidConfigException("ShmCache requires PHP sysvshm extension to be loaded.");
}
$key = ftok(__FILE__, 'p');
$this->shm = shm_attach($key,10000);
}
public function exists($key)
{
$key = $this->buildKey($key);
return shm_has_var($this->shm,$key);
}
protected function getValue($key)
{
return @shm_get_var($this->shm,$key);
}
protected function getValues($keys)
{
$results = [];
foreach ($keys as $key) {
$results[$key] = @shm_get_var($this->shm,$key);
}
return $results;
}
protected function setValue($key, $value, $duration)
{
return shm_put_var($this->shm,$key,$value);
}
protected function addValue($key, $value, $duration)
{
return shm_has_var($this->shm,$key) ? false : shm_put_var($this->shm,$key,$value);
}
protected function deleteValue($key)
{
return @shm_remove_var($this->shm,$key);
}
protected function flushValues()
{
return shm_remove($this->shm);
}
public function buildKey($key)
{
return crc32(parent::buildKey($key));
}
}