1<?php 2namespace DALMP\Cache; 3 4/** 5 * Memcache 6 * 7 * @author Nicolas Embriz <nbari@dalmp.com> 8 * @package DALMP 9 * @license BSD License 10 * @version 3.0.3 11 */ 12class Memcache implements CacheInterface 13{ 14 private $host = '127.0.0.1'; 15 private $port = 11211; 16 private $timeout = 1; 17 private $compress = false; 18 protected $cache; 19 20 /** 21 * Constructor 22 * 23 * @param string $host 24 * @param int $port 25 * @param int $timeout 26 * @param int $compress 27 */ 28 public function __construct() 29 { 30 $args = func_get_args(); 31 32 if ($args) { 33 $this->host = isset($args[0]) ? $args[0] : '127.0.0.1'; 34 $this->port = isset($args[1]) ? (int) $args[1] : 11211; 35 $this->timeout = isset($args[2]) ? (int) $args[2] : 1; 36 if (isset($args[3])) { 37 $this->compress = MEMCACHE_COMPRESSED; 38 } 39 } 40 } 41 42 /** 43 * Store data at the server 44 * 45 * @param string $key 46 * @param string $value 47 * @param int $expire time in seconds(default is 0 meaning unlimited) 48 */ 49 public function Set($key, $value, $expire = 0) 50 { 51 if ($this->connect()) { 52 ($this->compress === false) && $this->cache->setCompressThreshold(0); 53 54 return $this->cache->set($key, $value, $this->compress, $expire); 55 } else { 56 return false; 57 } 58 } 59 60 /** 61 * Retrieve item from the server 62 * 63 * @param string $key 64 */ 65 public function Get($key) 66 { 67 return $this->connect() ? $this->cache->get($key) : false; 68 } 69 70 /** 71 * Delete item from the server 72 * 73 * @param string $key 74 */ 75 public function Delete($key) 76 { 77 return $this->connect() ? $this->cache->delete($key) : false; 78 } 79 80 /** 81 * Flush cache 82 */ 83 public function Flush() 84 { 85 return $this->connect() ? $this->cache->flush() : false; 86 } 87 88 /** 89 * Get cache stats 90 */ 91 public function Stats() 92 { 93 return $this->connect() ? $this->cache->getStats() : false; 94 } 95 96 /** 97 * X execute/call custom methods 98 * 99 * @return cache object 100 */ 101 public function X() 102 { 103 return $this->connect() ? $this->cache : false; 104 } 105 106 /** 107 * try to establish a connection 108 */ 109 private function connect() 110 { 111 if ($this->cache instanceof MemCache) { 112 return true; 113 } else { 114 if (!extension_loaded('memcache')) { 115 throw new \Exception(__CLASS__ . 'Memcache PECL extension not loaded! - http://pecl.php.net/package/memcache'); 116 } 117 118 $memcache = new \Memcache(); 119 120 /** 121 * if a / found try to connect via socket 122 */ 123 if (strpos($this->host, '/') !== false) { 124 return $this->cache = $memcache->connect($this->host) ? $memcache : false; 125 } else { 126 return $this->cache = $memcache->connect($this->host, $this->port, $this->timeout) ? $memcache : false; 127 } 128 } 129 } 130 131} 132