-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathMemCached.php
115 lines (103 loc) · 2.54 KB
/
MemCached.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
<?php
namespace Kirby\Cache;
use Memcached as MemcachedExt;
/**
* Memcached Driver
*
* @package Kirby Cache
* @author Bastian Allgeier <[email protected]>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class MemCached extends Cache
{
/**
* Store for the memcache connection
*/
protected MemcachedExt $connection;
/**
* Stores whether the connection was successful
*/
protected bool $enabled;
/**
* Sets all parameters which are needed to connect to Memcached
*
* @param array $options 'host' (default: localhost)
* 'port' (default: 11211)
* 'prefix' (default: null)
*/
public function __construct(
array $options = []
) {
parent::__construct([
'host' => 'localhost',
'port' => 11211,
'prefix' => null,
...$options
]);
$this->connection = new MemcachedExt();
$this->enabled = $this->connection->addServer(
$this->options['host'],
$this->options['port']
);
}
/**
* Returns whether the cache is ready to
* store values
*/
public function enabled(): bool
{
return $this->enabled;
}
/**
* Flushes the entire cache and returns
* whether the operation was successful;
* WARNING: Memcached only supports flushing the whole cache at once!
*/
public function flush(): bool
{
return $this->connection->flush();
}
/**
* Whether the cache has any entry,
* irrespective whether the entries have expired or not
*/
public function isEmpty(): bool
{
return count($this->connection->getAllKeys()) === 0;
}
/**
* Removes an item from the cache and returns
* whether the operation was successful
*/
public function remove(string $key): bool
{
return $this->connection->delete($this->key($key));
}
/**
* Internal method to retrieve the raw cache value;
* needs to return a Value object or null if not found
*/
public function retrieve(string $key): Value|null
{
$value = $this->connection->get($this->key($key));
return Value::fromJson($value);
}
/**
* Writes an item to the cache for a given number of minutes and
* returns whether the operation was successful
*
* <code>
* // put an item in the cache for 15 minutes
* $cache->set('value', 'my value', 15);
* </code>
*/
public function set(string $key, $value, int $minutes = 0): bool
{
$key = $this->key($key);
$value = (new Value($value, $minutes))->toJson();
$expires = $this->expiration($minutes);
return $this->connection->set($key, $value, $expires);
}
}