Implements: Kohana_Cache_Arithmetic | Cache_Arithmetic
Kohana Cache Memcached driver. Provides a memcached based driver for the Kohana Cache library.
Below is an example of a memcached server configuration.
return [
// Default group
'default' => [
// Using Memcached driver
'driver' => 'memcached',
// Available server definitions
'servers' => [
// First memcached server
[
'host' => 'localhost',
'port' => 11211,
'weight' => 1,
'options' => []
],
// Second memcached server
[
'host' => '192.168.1.5',
'port' => 22122,
'options' => [
Memcached::OPT_COMPRESSION => false,
]
]
]
],
];
In cases where only one cache group is required, if the group is named
default
there is no need to pass the group name when instantiating a cache
instance.
Below are the settings available to a memcached driver.
Name | Required | Description |
---|---|---|
driver | YES | (string) The driver type to use |
default_expire | NO | (integer) The default expiration value |
servers | YES | (array) Associative array of server details, must include a host key. (See Memcached server configuration below) |
The following settings should be used when defining each memcached server.
Name | Required | Description |
---|---|---|
host | YES | (string) The host of the memcached server, i.e. localhost; or 127.0.0.1; or memcached.domain.tld |
port | NO | (integer) The port on which memcached is running. Set this parameter to 0 when using UNIX domain sockets. Default to 11211 |
weight | NO | (integer) The weight of the server relative to the total weight of all the servers in the pool. This controls the probability of the server being selected for operations. Default to 1 |
options | NO | (array) An associative array of options where the key is the option to set and the value is the new value for the option. Default to array() |
Class declared in MODPATH/cache/classes/Cache/Memcached.php on line 3.
integer 2592000
integer 3600
string
$defaultdefault driver to use
string(4) "file"
Kohana_Cache
$instancesinstances
array(0)
Config
$_configarray(0)
array
$defaultConfigThe default configuration for the memcached server.
array(0)
Memcached
$memcachedMemcached resource.
NULL
array
$optionsMemcached options.
array(0)
Decrement a given value by the step value supplied. Useful for shared counters and other persistent integer based tracking.
string
$id
required - Id of cache entry to decrement. int
$step
= integer 1 - Step value to decrement by. int
bool
public function decrement($id, $step = 1)
{
return $this->memcached->decrement($id, $step);
}
Delete a cache entry based on id.
// Delete the 'foo' cache entry immediately.
Cache::instance('memcached')->delete('foo');
// Delete the 'bar' cache entry after 30 seconds.
Cache::instance('memcached')->delete('bar', 30);
string
$id
required - Id of entry to delete. int
$time
= integer 0 - The amount of time the server will wait to delete the entry. bool
public function delete($id, $time = 0)
{
return $this->memcached->delete($this->_sanitize_id($id), $time);
}
Delete all cache entries.
Beware of using this method when using shared memory cache systems, as it will wipe every entry within the system for all clients.
// Delete all cache entries in the default group.
Cache::instance('memcached')->delete_all();
bool
public function delete_all()
{
return $this->memcached->flush();
}
Retrieve a cached value entry by id.
// Retrieve cache entry from memcached group.
$data = Cache::instance('memcached')->get('foo');
// Retrieve cache entry from memcached group and return 'bar' if miss.
$data = Cache::instance('memcached')->get('foo', 'bar');
string
$id
required - Id of cache to entry. string
$default
= NULL - Default value to return if cache miss. mixed
public function get($id, $default = null)
{
// Get the value from Memcached.
$value = $this->memcached->get($this->_sanitize_id($id));
// If the value wasn't found, normalise it.
if ($value === false) {
$value = null === $default ? null : $default;
}
// Return the value.
return $value;
}
Increment a given value by the step value supplied. Useful for shared counters and other persistent integer based tracking.
string
$id
required - Id of cache entry to increment. int
$step
= integer 1 - Step value to increment by. int
bool
public function increment($id, $step = 1)
{
return $this->memcached->increment($id, $step);
}
Set a value to cache with id and lifetime.
$data = 'bar';
// Set 'bar' to 'foo' in memcached group for 10 minutes.
if (Cache::instance('memcached')->set('foo', $data, 600)) {
// Cache was set successfully.
return true;
}
string
$id
required - Id of cache entry. mixed
$data
required - Data to set to cache. int
$lifetime
= NULL - Lifetime in seconds, maximum value 2592000. bool
public function set($id, $data, $lifetime = null)
{
// If lifetime is null, set to the default expiry.
if ($lifetime === null) {
$lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE);
}
// If the lifetime is greater than the ceiling.
if ($lifetime > Cache_Memcached::CACHE_CEILING) {
// Set the lifetime to maximum cache time.
$lifetime = Cache_Memcached::CACHE_CEILING + time();
}
// Else if the lifetime is greater than zero.
elseif ($lifetime > 0) {
$lifetime += time();
}
// Else
else {
// Normalise the lifetime.
$lifetime = 0;
}
// Set the data to memcached.
return $this->memcached->set($this->_sanitize_id($id), $data, $lifetime);
}
Overload the __clone() method to prevent cloning
void
final public function __clone()
{
throw new Cache_Exception('Cloning of Kohana_Cache objects is forbidden');
}
Getter and setter for the configuration. If no argument provided, the current configuration is returned. Otherwise the configuration is set to this class.
// Overwrite all configuration
$cache->config(['driver' => 'memcache', '...']);
// Set a new configuration setting
$cache->config('servers', ['foo' => 'bar', '...']);
// Get a configuration setting
$servers = $cache->config('servers);
mixed
$key
= NULL - Key to set to array, either array or config path mixed
$value
= NULL - Value to associate with key mixed
public function config($key = null, $value = null)
{
if ($key === null)
return $this->_config;
if (is_array($key)) {
$this->_config = $key;
} else {
if ($value === null)
return Arr::get($this->_config, $key);
$this->_config[$key] = $value;
}
return $this;
}
Creates a singleton of a Kohana Cache group. If no group is supplied the default cache group is used.
// Create an instance of the default group
$default_group = Cache::instance();
// Create an instance of a group
$foo_group = Cache::instance('foo');
// Access an instantiated group directly
$foo_group = Cache::$instances['default'];
string
$group
= NULL - The name of the cache group to use [Optional] Cache
public static function instance($group = null)
{
// If there is no group supplied
if ($group === null) {
// Use the default setting
$group = Cache::$default;
}
if (isset(Cache::$instances[$group])) {
// Return the current group if initiated already
return Cache::$instances[$group];
}
$config = Kohana::$config->load('cache');
if (!$config->offsetExists($group)) {
throw new Cache_Exception('Failed to load Kohana Cache group: :group', [':group' => $group]);
}
$config = $config->get($group);
// Create a new cache type instance
$cache_class = 'Cache_' . ucfirst($config['driver']);
Cache::$instances[$group] = new $cache_class($config);
// Return the instance
return Cache::$instances[$group];
}
Construct the memcached cache driver. This method cannot be invoked
externally. The file cache driver must be instantiated using the
Cache::instance()
method.
array
$config
required - Configuration protected function __construct(array $config)
{
// Check for the memcached extention.
if (!extension_loaded('memcached')) {
throw new Cache_Exception('Memcached PHP extention not loaded');
}
parent::__construct($config);
// Setup Memcached.
$this->memcached = new Memcached;
// Load servers from configuration.
$servers = Arr::get($this->_config, 'servers', null);
if (!$servers) {
// Throw an exception if no server found.
throw new Cache_Exception('No Memcached servers defined in configuration');
}
// Setup default server configuration.
$this->defaultConfig = [
'host' => 'localhost',
'port' => 11211,
'weight' => 1,
'options' => []
];
// Add the memcached servers to the pool.
foreach ($servers as $server) {
// Merge the defined config with defaults.
$server += $this->defaultConfig;
if (!$this->memcached->addServer($server['host'], $server['port'], $server['weight'])) {
throw new Cache_Exception('Memcached could not connect to host \':host\' using port \':port\'', [
':host' => $server['host'],
':port' => $server['port']
]);
}
// Set options.
if ($server['options']) {
$this->memcached->setOptions($server['options']);
}
}
}
Replaces troublesome characters with underscores.
// Sanitize a cache id
$id = $this->_sanitize_id($id);
string
$id
required - Id of cache to sanitize string
protected function _sanitize_id($id)
{
// Change slashes and spaces to underscores
return str_replace(['/', '\\', ' '], '_', $id);
}