1 <?php
2 3 4 5 6 7
8
9 namespace Cross\Cache\Driver;
10
11 use Cross\Exception\CoreException;
12 use Exception;
13 use Memcache;
14
15 16 17 18 19
20 class MemcacheDriver
21 {
22 23 24
25 public $link;
26
27 28 29 30 31
32 protected $defaultOptions = array(
33 'persistent' => true,
34 'weight' => 1,
35 'timeout' => 1,
36 'retry_interval' => 15,
37 'status' => true,
38 'failure_callback' => null
39 );
40
41 42 43 44 45 46
47 function __construct(array $option)
48 {
49 if (!extension_loaded('memcache')) {
50 throw new CoreException('Not support memcache extension !');
51 }
52
53 if (!isset($option['host'])) {
54 $option['host'] = '127.0.0.1';
55 }
56
57 if (!isset($option['port'])) {
58 $option['port'] = 11211;
59 }
60
61 if (!isset($option['timeout'])) {
62 $option['timeout'] = 1;
63 }
64
65 try {
66 $mc = new Memcache();
67
68 if (false !== strpos($option['host'], '|')) {
69 $opt = &$this->defaultOptions;
70 foreach ($opt as $k => &$v) {
71 if (isset($option[$k])) {
72 $v = $option[$k];
73 }
74 }
75
76 $serverList = explode('|', $option['host']);
77 foreach ($serverList as $server) {
78 $host = $server;
79 $port = $option['port'];
80 if (false !== strpos($server, ':')) {
81 list($host, $port) = explode(':', $server);
82 }
83
84 $host = trim($host);
85 $port = trim($port);
86 $mc->addServer($host, $port, $opt['persistent'], $opt['weight'], $opt['timeout'],
87 $opt['retry_interval'], $opt['status'], $opt['failure_callback']);
88 }
89 } else {
90 $mc->connect($option['host'], $option['port'], $option['timeout']);
91 }
92
93 $this->link = $mc;
94 } catch (Exception $e) {
95 throw new CoreException($e->getMessage());
96 }
97 }
98
99 100 101 102 103 104 105
106 function get($key, &$flag = 0)
107 {
108 return $this->link->get($key, $flag);
109 }
110
111 112 113 114 115 116 117
118 public function __call($method, $argv)
119 {
120 $result = null;
121 if (method_exists($this->link, $method)) {
122 $result = ($argv == null)
123 ? $this->link->$method()
124 : call_user_func_array(array($this->link, $method), $argv);
125 }
126
127 return $result;
128 }
129 }
130