namespace Ace; use Illuminate/Cache/StoreInterface; use Illuminate/Cache/TaggableStore;
class AceMemcachedStore extends TaggableStore implements StoreInterface {
protected $memcached; protected $prefix;
public function __construct($space, $prefix = '') { $this- memcached = /Alibaba::Cache($space); $this- prefix = strlen($prefix) 0 $prefix.':' : ''; }
/** * Retrieve an item from the cache by key. * * @param string $key * @return mixed */ public function get($key) { $value = $this- memcached- get($this- prefix.$key); if(is_bool($value) && $value === false) { return null; } return $value; }
/** * Store an item in the cache for a given number of minutes. * * @param string $key * @param mixed $value * @param int $minutes * @return boolean */ public function put($key, $value, $minutes) { return $this- memcached- set($this- prefix.$key, $value, $minutes); }
/** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return boolean */ public function increment($key, $value = 1) { return $this- memcached- increment($this- prefix.$key, $value); }
/** * Decrement the value of an item in the cache. * * @param string $key * @param mixed $value * @return boolean */ public function decrement($key, $value = 1) { return $this- memcached- decrement($this- prefix.$key, $value); }
/** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return boolean */ public function forever($key, $value) { return $this- memcached- set($key, $value, 0); }
/** * Remove an item from the cache. * * @param string $key * @return boolean */ public function forget($key) { return $this- memcached- delete($this- prefix.$key); }
/** * Remove all items from the cache. * * @return void */ public function flush() { //$this- memcached- flush(); return false; }
public function getMemcached() { return $this- memcached; } /** * Get the cache key prefix. * * @return string */ public function getPrefix() { return $this- prefix; } } 这段代码比较简单,不过要特别注意一下 get($key) 方法的实现。标准 memcached 以及 ACE 的缓存对象的 get 方法都是key有效时返回对应的缓存值,否则返回false,而在 Laravel 4 中,是通过检测 get 方法返回的是否 null 来做判断,所以这里需要处理一下,返回缓存值或者null。AceMemcachedStore类已经创建好了,接下来在 bootstrap/start.php 文件中扩展 Cache:打开 bootstrap/start.php, 添加以下代码: 复制代码 代码如下: // 扩展名为 ace 的缓存驱动 Cache::extend('ace', function($app) { // 从 app/config/cache.php 文件中读取 "ace" 的值 $space = $app['config']['cache.ace'];