PageRenderTime 52ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/memcache/memcached.php

https://github.com/sezuan/core
PHP | 76 lines | 54 code | 10 blank | 12 comment | 7 complexity | 6a559a182b90b1893cd3e27a03f9453b MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\Memcache;
  9. class Memcached extends Cache {
  10. /**
  11. * @var \Memcached $cache
  12. */
  13. private static $cache = null;
  14. public function __construct($prefix = '') {
  15. parent::__construct($prefix);
  16. if (is_null(self::$cache)) {
  17. self::$cache = new \Memcached();
  18. list($host, $port) = \OC_Config::getValue('memcached_server', array('localhost', 11211));
  19. self::$cache->addServer($host, $port);
  20. }
  21. }
  22. /**
  23. * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
  24. */
  25. protected function getNameSpace() {
  26. return $this->prefix;
  27. }
  28. public function get($key) {
  29. $result = self::$cache->get($this->getNamespace() . $key);
  30. if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
  31. return null;
  32. } else {
  33. return $result;
  34. }
  35. }
  36. public function set($key, $value, $ttl = 0) {
  37. if ($ttl > 0) {
  38. return self::$cache->set($this->getNamespace() . $key, $value, $ttl);
  39. } else {
  40. return self::$cache->set($this->getNamespace() . $key, $value);
  41. }
  42. }
  43. public function hasKey($key) {
  44. self::$cache->get($this->getNamespace() . $key);
  45. return self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND;
  46. }
  47. public function remove($key) {
  48. return self::$cache->delete($this->getNamespace() . $key);
  49. }
  50. public function clear($prefix = '') {
  51. $prefix = $this->getNamespace() . $prefix;
  52. $allKeys = self::$cache->getAllKeys();
  53. $keys = array();
  54. $prefixLength = strlen($prefix);
  55. foreach ($allKeys as $key) {
  56. if (substr($key, 0, $prefixLength) === $prefix) {
  57. $keys[] = $key;
  58. }
  59. }
  60. self::$cache->deleteMulti($keys);
  61. return true;
  62. }
  63. static public function isAvailable() {
  64. return extension_loaded('memcached');
  65. }
  66. }