|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace BFW\Memcache; |
|
4
|
|
|
|
|
5
|
|
|
use \Exception; |
|
6
|
|
|
|
|
7
|
|
|
class Memcached extends \Memcached |
|
8
|
|
|
{ |
|
9
|
|
|
use \BFW\Traits\Memcache; |
|
10
|
|
|
|
|
11
|
|
|
protected $app; |
|
12
|
|
|
|
|
13
|
|
|
protected $config; |
|
14
|
|
|
|
|
15
|
|
|
public function __construct(\BFW\Application $app) |
|
16
|
|
|
{ |
|
17
|
|
|
$this->app = $app; |
|
18
|
|
|
$this->config = $this->app->getConfig('memcached'); |
|
19
|
|
|
|
|
20
|
|
|
if(!empty($this->config['persistentId'])) { |
|
21
|
|
|
parent::__construct($this->config['persistentId']); |
|
22
|
|
|
} else { |
|
23
|
|
|
parent::__construct(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
$this->connectToServers(); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
protected function connectToServers() |
|
30
|
|
|
{ |
|
31
|
|
|
$addServers = []; |
|
32
|
|
|
$serversList = $this->generateServerList(); |
|
33
|
|
|
|
|
34
|
|
|
foreach ($this->config['server'] as $server) { |
|
35
|
|
|
$host = isset($server['host']) ? $server['host'] : null; |
|
36
|
|
|
$port = isset($server['port']) ? $server['port'] : null; |
|
37
|
|
|
$weight = isset($server['weight']) ? $server['weight'] : 0; |
|
38
|
|
|
|
|
39
|
|
|
//not check if port = (int) 0; Doc said to define to 0 for socket. |
|
40
|
|
|
if (empty($host) || $port === null) { |
|
41
|
|
|
continue; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
//It should not be to readd the server |
|
45
|
|
|
//(for persistent mode particulary) |
|
46
|
|
|
if(in_array($host.':'.$port, $serversList)) { |
|
47
|
|
|
continue; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$addServers[] = [$host, $port, $weight]; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
$this->addServers($addServers); |
|
54
|
|
|
$this->testConnect(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* addServer not created the connection. It's created at the first call |
|
59
|
|
|
* to the memcached servers. |
|
60
|
|
|
*/ |
|
61
|
|
|
protected function testConnect() |
|
62
|
|
|
{ |
|
63
|
|
|
$stats = $this->getStats(); |
|
64
|
|
|
|
|
65
|
|
|
foreach ($stats as $serverName => $serverStat) { |
|
66
|
|
|
if ($serverStat['uptime'] < 1) { |
|
67
|
|
|
throw new Exception( |
|
68
|
|
|
'Memcached server '.$serverName.' not connected' |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
protected function generateServerList() |
|
75
|
|
|
{ |
|
76
|
|
|
$serversList = $this->getServerList(); |
|
77
|
|
|
$servers = []; |
|
78
|
|
|
|
|
79
|
|
|
foreach ($serversList as $serverInfos) { |
|
80
|
|
|
$servers[] = $serverInfos['host'].':'.$serverInfos['port']; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
return $servers; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|