Completed
Push — 6.0 ( d6c8d7...cb8a0b )
by liu
05:58
created

Memcached::set()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 17
ccs 0
cts 10
cp 0
crap 12
rs 9.9666
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
12
namespace think\cache\driver;
13
14
use think\cache\Driver;
15
16
/**
17
 * Memcached缓存类
18
 */
19
class Memcached extends Driver
20
{
21
    /**
22
     * 配置参数
23
     * @var array
24
     */
25
    protected $options = [
26
        'host'       => '127.0.0.1',
27
        'port'       => 11211,
28
        'expire'     => 0,
29
        'timeout'    => 0, // 超时时间(单位:毫秒)
30
        'prefix'     => '',
31
        'username'   => '', //账号
32
        'password'   => '', //密码
33
        'option'     => [],
34
        'tag_prefix' => 'tag:',
35
        'serialize'  => [],
36
    ];
37
38
    /**
39
     * 架构函数
40
     * @access public
41
     * @param  array $options 缓存参数
42
     */
43
    public function __construct(array $options = [])
44
    {
45
        if (!extension_loaded('memcached')) {
46
            throw new \BadFunctionCallException('not support: memcached');
47
        }
48
49
        if (!empty($options)) {
50
            $this->options = array_merge($this->options, $options);
51
        }
52
53
        $this->handler = new \Memcached;
54
55
        if (!empty($this->options['option'])) {
56
            $this->handler->setOptions($this->options['option']);
57
        }
58
59
        // 设置连接超时时间(单位:毫秒)
60
        if ($this->options['timeout'] > 0) {
61
            $this->handler->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->options['timeout']);
62
        }
63
64
        // 支持集群
65
        $hosts = (array) $this->options['host'];
66
        $ports = (array) $this->options['port'];
67
        if (empty($ports[0])) {
68
            $ports[0] = 11211;
69
        }
70
71
        // 建立连接
72
        $servers = [];
73
        foreach ($hosts as $i => $host) {
74
            $servers[] = [$host, $ports[$i] ?? $ports[0], 1];
75
        }
76
77
        $this->handler->addServers($servers);
78
79
        if ('' != $this->options['username']) {
80
            $this->handler->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
81
            $this->handler->setSaslAuthData($this->options['username'], $this->options['password']);
82
        }
83
    }
84
85
    /**
86
     * 判断缓存
87
     * @access public
88
     * @param  string $name 缓存变量名
89
     * @return bool
90
     */
91
    public function has($name): bool
92
    {
93
        $key = $this->getCacheKey($name);
94
95
        return $this->handler->get($key) ? true : false;
96
    }
97
98
    /**
99
     * 读取缓存
100
     * @access public
101
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
102
     * @param  mixed  $default 默认值
103
     * @return mixed
104
     */
105
    public function get($name, $default = false)
106
    {
107
        $this->readTimes++;
108
109
        $result = $this->handler->get($this->getCacheKey($name));
110
111
        return false !== $result ? $this->unserialize($result) : $default;
112
    }
113
114
    /**
115
     * 写入缓存
116
     * @access public
117
     * @param  string            $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
118
     * @param  mixed             $value  存储数据
119
     * @param  integer|\DateTime $expire  有效时间(秒)
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
120
     * @return bool
121
     */
122
    public function set($name, $value, $expire = null): bool
123
    {
124
        $this->writeTimes++;
125
126
        if (is_null($expire)) {
127
            $expire = $this->options['expire'];
128
        }
129
130
        $key    = $this->getCacheKey($name);
131
        $expire = $this->getExpireTime($expire);
132
        $value  = $this->serialize($value);
133
134
        if ($this->handler->set($key, $value, $expire)) {
135
            return true;
136
        }
137
138
        return false;
139
    }
140
141
    /**
142
     * 自增缓存(针对数值缓存)
143
     * @access public
144
     * @param  string $name 缓存变量名
145
     * @param  int    $step 步长
146
     * @return false|int
147
     */
148
    public function inc(string $name, int $step = 1)
149
    {
150
        $this->writeTimes++;
151
152
        $key = $this->getCacheKey($name);
153
154
        if ($this->handler->get($key)) {
155
            return $this->handler->increment($key, $step);
156
        }
157
158
        return $this->handler->set($key, $step);
159
    }
160
161
    /**
162
     * 自减缓存(针对数值缓存)
163
     * @access public
164
     * @param  string $name 缓存变量名
165
     * @param  int    $step 步长
166
     * @return false|int
167
     */
168
    public function dec(string $name, int $step = 1)
169
    {
170
        $this->writeTimes++;
171
172
        $key   = $this->getCacheKey($name);
173
        $value = $this->handler->get($key) - $step;
174
        $res   = $this->handler->set($key, $value);
175
176
        return !$res ? false : $value;
177
    }
178
179
    /**
180
     * 删除缓存
181
     * @access public
182
     * @param  string       $name 缓存变量名
183
     * @param  bool|false   $ttl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
184
     * @return bool
185
     */
186
    public function delete($name, $ttl = false): bool
187
    {
188
        $this->writeTimes++;
189
190
        $key = $this->getCacheKey($name);
191
192
        return false === $ttl ?
193
        $this->handler->delete($key) :
194
        $this->handler->delete($key, $ttl);
195
    }
196
197
    /**
198
     * 清除缓存
199
     * @access public
200
     * @return bool
201
     */
202
    public function clear(): bool
203
    {
204
        $this->writeTimes++;
205
206
        return $this->handler->flush();
207
    }
208
209
    /**
210
     * 删除缓存标签
211
     * @access public
212
     * @param  array $keys 缓存标识列表
213
     * @return void
214
     */
215
    public function clearTag(array $keys): void
216
    {
217
        $this->handler->deleteMulti($keys);
218
    }
219
220
}
221