1: <?php
2: /**
3: * Memcache storage engine for cache
4: *
5: *
6: * PHP 5
7: *
8: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
9: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
10: *
11: * Licensed under The MIT License
12: * Redistributions of files must retain the above copyright notice.
13: *
14: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
15: * @link http://cakephp.org CakePHP(tm) Project
16: * @package Cake.Cache.Engine
17: * @since CakePHP(tm) v 1.2.0.4933
18: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
19: */
20:
21: /**
22: * Memcache storage engine for cache. Memcache has some limitations in the amount of
23: * control you have over expire times far in the future. See MemcacheEngine::write() for
24: * more information.
25: *
26: * @package Cake.Cache.Engine
27: */
28: class MemcacheEngine extends CacheEngine {
29:
30: /**
31: * Contains the compiled group names
32: * (prefixed witht the global configuration prefix)
33: *
34: * @var array
35: **/
36: protected $_compiledGroupNames = array();
37:
38: /**
39: * Memcache wrapper.
40: *
41: * @var Memcache
42: */
43: protected $_Memcache = null;
44:
45: /**
46: * Settings
47: *
48: * - servers = string or array of memcache servers, default => 127.0.0.1. If an
49: * array MemcacheEngine will use them as a pool.
50: * - compress = boolean, default => false
51: *
52: * @var array
53: */
54: public $settings = array();
55:
56: /**
57: * Initialize the Cache Engine
58: *
59: * Called automatically by the cache frontend
60: * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
61: *
62: * @param array $settings array of setting for the engine
63: * @return boolean True if the engine has been successfully initialized, false if not
64: */
65: public function init($settings = array()) {
66: if (!class_exists('Memcache')) {
67: return false;
68: }
69: if (!isset($settings['prefix'])) {
70: $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
71: }
72: $settings += array(
73: 'engine' => 'Memcache',
74: 'servers' => array('127.0.0.1'),
75: 'compress' => false,
76: 'persistent' => true
77: );
78: parent::init($settings);
79:
80: if ($this->settings['compress']) {
81: $this->settings['compress'] = MEMCACHE_COMPRESSED;
82: }
83: if (is_string($this->settings['servers'])) {
84: $this->settings['servers'] = array($this->settings['servers']);
85: }
86: if (!isset($this->_Memcache)) {
87: $return = false;
88: $this->_Memcache = new Memcache();
89: foreach ($this->settings['servers'] as $server) {
90: list($host, $port) = $this->_parseServerString($server);
91: if ($this->_Memcache->addServer($host, $port, $this->settings['persistent'])) {
92: $return = true;
93: }
94: }
95: return $return;
96: }
97: return true;
98: }
99:
100: /**
101: * Parses the server address into the host/port. Handles both IPv6 and IPv4
102: * addresses and Unix sockets
103: *
104: * @param string $server The server address string.
105: * @return array Array containing host, port
106: */
107: protected function _parseServerString($server) {
108: if ($server[0] == 'u') {
109: return array($server, 0);
110: }
111: if (substr($server, 0, 1) == '[') {
112: $position = strpos($server, ']:');
113: if ($position !== false) {
114: $position++;
115: }
116: } else {
117: $position = strpos($server, ':');
118: }
119: $port = 11211;
120: $host = $server;
121: if ($position !== false) {
122: $host = substr($server, 0, $position);
123: $port = substr($server, $position + 1);
124: }
125: return array($host, $port);
126: }
127:
128: /**
129: * Write data for key into cache. When using memcache as your cache engine
130: * remember that the Memcache pecl extension does not support cache expiry times greater
131: * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
132: *
133: * @param string $key Identifier for the data
134: * @param mixed $value Data to be cached
135: * @param integer $duration How long to cache the data, in seconds
136: * @return boolean True if the data was successfully cached, false on failure
137: * @see http://php.net/manual/en/memcache.set.php
138: */
139: public function write($key, $value, $duration) {
140: if ($duration > 30 * DAY) {
141: $duration = 0;
142: }
143: return $this->_Memcache->set($key, $value, $this->settings['compress'], $duration);
144: }
145:
146: /**
147: * Read a key from the cache
148: *
149: * @param string $key Identifier for the data
150: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
151: */
152: public function read($key) {
153: return $this->_Memcache->get($key);
154: }
155:
156: /**
157: * Increments the value of an integer cached key
158: *
159: * @param string $key Identifier for the data
160: * @param integer $offset How much to increment
161: * @return New incremented value, false otherwise
162: * @throws CacheException when you try to increment with compress = true
163: */
164: public function increment($key, $offset = 1) {
165: if ($this->settings['compress']) {
166: throw new CacheException(
167: __d('cake_dev', 'Method increment() not implemented for compressed cache in %s', __CLASS__)
168: );
169: }
170: return $this->_Memcache->increment($key, $offset);
171: }
172:
173: /**
174: * Decrements the value of an integer cached key
175: *
176: * @param string $key Identifier for the data
177: * @param integer $offset How much to subtract
178: * @return New decremented value, false otherwise
179: * @throws CacheException when you try to decrement with compress = true
180: */
181: public function decrement($key, $offset = 1) {
182: if ($this->settings['compress']) {
183: throw new CacheException(
184: __d('cake_dev', 'Method decrement() not implemented for compressed cache in %s', __CLASS__)
185: );
186: }
187: return $this->_Memcache->decrement($key, $offset);
188: }
189:
190: /**
191: * Delete a key from the cache
192: *
193: * @param string $key Identifier for the data
194: * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
195: */
196: public function delete($key) {
197: return $this->_Memcache->delete($key);
198: }
199:
200: /**
201: * Delete all keys from the cache
202: *
203: * @param boolean $check
204: * @return boolean True if the cache was successfully cleared, false otherwise
205: */
206: public function clear($check) {
207: if ($check) {
208: return true;
209: }
210: foreach ($this->_Memcache->getExtendedStats('slabs') as $slabs) {
211: foreach (array_keys($slabs) as $slabId) {
212: if (!is_numeric($slabId)) {
213: continue;
214: }
215:
216: foreach ($this->_Memcache->getExtendedStats('cachedump', $slabId) as $stats) {
217: if (!is_array($stats)) {
218: continue;
219: }
220: foreach (array_keys($stats) as $key) {
221: if (strpos($key, $this->settings['prefix']) === 0) {
222: $this->_Memcache->delete($key);
223: }
224: }
225: }
226: }
227: }
228: return true;
229: }
230:
231: /**
232: * Connects to a server in connection pool
233: *
234: * @param string $host host ip address or name
235: * @param integer $port Server port
236: * @return boolean True if memcache server was connected
237: */
238: public function connect($host, $port = 11211) {
239: if ($this->_Memcache->getServerStatus($host, $port) === 0) {
240: if ($this->_Memcache->connect($host, $port)) {
241: return true;
242: }
243: return false;
244: }
245: return true;
246: }
247:
248: /**
249: * Returns the `group value` for each of the configured groups
250: * If the group initial value was not found, then it initializes
251: * the group accordingly.
252: *
253: * @return array
254: **/
255: public function groups() {
256: if (empty($this->_compiledGroupNames)) {
257: foreach ($this->settings['groups'] as $group) {
258: $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
259: }
260: }
261:
262: $groups = $this->_Memcache->get($this->_compiledGroupNames);
263: if (count($groups) !== count($this->settings['groups'])) {
264: foreach ($this->_compiledGroupNames as $group) {
265: if (!isset($groups[$group])) {
266: $this->_Memcache->set($group, 1, false, 0);
267: $groups[$group] = 1;
268: }
269: }
270: ksort($groups);
271: }
272:
273: $result = array();
274: $groups = array_values($groups);
275: foreach ($this->settings['groups'] as $i => $group) {
276: $result[] = $group . $groups[$i];
277: }
278:
279: return $result;
280: }
281:
282: /**
283: * Increments the group value to simulate deletion of all keys under a group
284: * old values will remain in storage until they expire.
285: *
286: * @return boolean success
287: **/
288: public function clearGroup($group) {
289: return (bool)$this->_Memcache->increment($this->settings['prefix'] . $group);
290: }
291: }
292: