PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/cache/engines/WaxCacheMemcache.php

https://gitlab.com/sheldonels/phpwax
PHP | 80 lines | 57 code | 13 blank | 10 comment | 11 complexity | d76bd903aad1e256bf50c6a8c86c8586 MD5 | raw file
  1. <?php
  2. /**
  3. * @package PHP-Wax
  4. */
  5. /**
  6. * Engine for caching of data / objects to memcache.
  7. * @package PHP-Wax
  8. */
  9. class WaxCacheMemcache implements CacheEngine{
  10. public $key = false;
  11. public $server = "localhost";
  12. public $port = "11211";
  13. public $memcache = false;
  14. public $lifetime = 3600;
  15. public static $connection = false;
  16. public function __construct($key, $options=array()) {
  17. $this->key = $key;
  18. $this->memcache = new Memcache;
  19. foreach($options as $k=>$option) $this->$k = $option;
  20. try {
  21. set_error_handler(function(){
  22. WaxCacheMemcache::$connection = false;
  23. });
  24. $con = $this->memcache->connect($this->server, $this->port);
  25. if($con) self::$connection = true;
  26. set_error_handler('throw_wxerror', 247 );
  27. } catch (Exception $e) {}
  28. }
  29. public function get() {
  30. //if(!self::$connection) return false;
  31. if($this->is_namespaced()) return $this->memcache->get($this->namespaced_key());
  32. return $this->memcache->get($this->key);
  33. }
  34. public function set($value) {
  35. //if(!self::$connection) return false;
  36. if($this->is_namespaced()) return $this->memcache->set($this->namespaced_key(), $value,0, $this->lifetime);
  37. else return $this->memcache->set($this->key, $value, 0,$this->lifetime);
  38. }
  39. public function expire($query=false) {
  40. if(!$query) $this->memcache->delete($this->key,0);
  41. else $this->memcache->increment($query);
  42. }
  43. public function expire_namespace($key){
  44. $key = $this->namespaced_key();
  45. $this->expire($key);
  46. }
  47. public function key_path($full_key) {
  48. if(strpos($full_key, "/")) {
  49. $path = substr($full_key, 0, strrpos($full_key, "/")+1);
  50. return $path;
  51. } else return "";
  52. }
  53. public function key_name($full_key) {
  54. if(strpos($full_key, "/")) {
  55. return substr(strrchr($full_key, "/"),1);
  56. } else return $full_key;
  57. }
  58. public function is_namespaced() {
  59. return strlen($this->key_path($this->key));
  60. }
  61. public function namespaced_key() {
  62. $ns_key = $this->memcache->get($this->key_path($this->key));
  63. // if not set, initialize it
  64. if($ns_key===false) $this->memcache->set($this->key_path($this->key), rand(1, 10000));
  65. return $ns_key."_".$this->key_name($this->key);
  66. }
  67. }