Class Kohana_Cache_Memcached

Kohana_Cache_Memcached

extends Cache
extends Kohana_Cache

Kohana_Cache_Memcached class

LICENSE: THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

package
Kohana/Cache
author
gimpe <gimpehub@intljaywalkers.com>
copyright
2011 International Jaywalkers
(c) 2018 Koseven Team
license
http://creativecommons.org/licenses/by/3.0/ CC BY 3.0
link
http://github.com/gimpe/kohana-memcached


Constants

DEFAULT_EXPIRE

integer 3600

Properties

public static string $default

default driver to use

string(4) "file"

public static Kohana_Cache $instances

instances

array(0) 

protected Config $_config

Default value:
array(0) 

protected $memcached_instance

Default value:
NULL

Methods

public delete(string $id ) (defined in Kohana_Cache_Memcached)

Delete a cache entry based on id

// Delete 'foo' entry from the default group
Cache::instance()->delete('foo');

// Delete 'foo' entry from the memcache group
Cache::instance('memcache')->delete('foo')

Parameters

  • string $id required - Id to remove from cache

Return Values

  • boolean

Source Code

public function delete($id)
{
    return $this->memcached_instance->delete($this->_sanitize_id($id));
}

public delete_all() (defined in Kohana_Cache_Memcached)

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()->delete_all();

// Delete all cache entries in the memcache group
Cache::instance('memcache')->delete_all();

Return Values

  • boolean

Source Code

public function delete_all()
{
    return $this->memcached_instance->flush();
}

public get(string $id [, string $default = NULL ] ) (defined in Kohana_Cache_Memcached)

Retrieve a cached value entry by id.

// Retrieve cache entry from default group
$data = Cache::instance()->get('foo');

// Retrieve cache entry from default group and return 'bar' if miss
$data = Cache::instance()->get('foo', 'bar');

// Retrieve cache entry from memcache group
$data = Cache::instance('memcache')->get('foo');

Parameters

  • string $id required - Id of cache to entry
  • string $default = NULL - Default value to return if cache miss

Tags

Return Values

  • mixed

Source Code

public function get($id, $default = NULL)
{
    $result = $this->memcached_instance->get($this->_sanitize_id($id));

    if ($this->memcached_instance->getResultCode() !== Memcached::RES_SUCCESS)
    {
        $result = $default;
    }

    return $result;
}

public set(string $id , string $data [, integer $lifetime = integer 3600 ] ) (defined in Kohana_Cache_Memcached)

Set a value to cache with id and lifetime

$data = 'bar';

// Set 'bar' to 'foo' in default group, using default expiry
Cache::instance()->set('foo', $data);

// Set 'bar' to 'foo' in default group for 30 seconds
Cache::instance()->set('foo', $data, 30);

// Set 'bar' to 'foo' in memcache group for 10 minutes
if (Cache::instance('memcache')->set('foo', $data, 600))
{
     // Cache was set successfully
     return
}

Parameters

  • string $id required - Id of cache entry
  • string $data required - Data to set to cache
  • integer $lifetime = integer 3600 - Lifetime in seconds

Return Values

  • boolean

Source Code

public function set($id, $data, $lifetime = 3600)
{
    return $this->memcached_instance->set($this->_sanitize_id($id), $data, $lifetime);
}

final public __clone() (defined in Kohana_Cache)

Overload the __clone() method to prevent cloning

Tags

Return Values

  • void

Source Code

final public function __clone()
{
	throw new Cache_Exception('Cloning of Kohana_Cache objects is forbidden');
}

public config([ mixed $key = NULL , mixed $value = NULL ] ) (defined in Kohana_Cache)

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(array('driver' => 'memcache', '...'));

// Set a new configuration setting
$cache->config('servers', array(
     'foo' => 'bar',
     '...'
     ));

// Get a configuration setting
$servers = $cache->config('servers);

Parameters

  • mixed $key = NULL - Key to set to array, either array or config path
  • mixed $value = NULL - Value to associate with key

Return Values

  • mixed

Source Code

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;
}

public static instance([ string $group = NULL ] ) (defined in Kohana_Cache)

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'];

Parameters

  • string $group = NULL - The name of the cache group to use [Optional]

Tags

Return Values

  • Cache

Source Code

public static function instance($group = NULL)
{
       // If there is no group supplied, try to get it from the config
       if ($group === NULL)
       {
           $group = Kohana::$config->load('cache.default');
       }

	// 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];
}

protected __construct(array $config ) (defined in Kohana_Cache_Memcached)

Ensures singleton pattern is observed, loads the default expiry

Parameters

  • array $config required - Configuration

Source Code

protected function __construct(array $config)
{
    if (!extension_loaded('memcached'))
    {
        // exception missing memcached extension
        throw new Kohana_Cache_Exception('memcached extension is not loaded');
    }

    parent::__construct($config);

    $this->memcached_instance = new Memcached;

    // load servers from configuration
    $servers = Arr::get($this->_config, 'servers', []);

    if (empty($servers))
    {
        // exception no server found
        throw new Kohana_Cache_Exception('no Memcached servers in config/cache.php');
    }

    // load options from configuration
    $options = Arr::get($this->_config, 'options', []);

    // set options
    foreach ($options as $option => $value)
    {
        if ($option === Memcached::OPT_SERIALIZER && $value === Memcached::SERIALIZER_IGBINARY
                && !Memcached::HAVE_IGBINARY)
        {
            // exception serializer Igbinary not supported
            throw new Kohana_Cache_Exception('serializer Igbinary not supported, please fix config/cache.php');
        }

        if ($option === Memcached::OPT_SERIALIZER && $value === Memcached::SERIALIZER_JSON
                && !Memcached::HAVE_JSON)
        {
            // exception serializer JSON not supported
            throw new Kohana_Cache_Exception('serializer JSON not supported, please fix config/cache.php');
        }

        $this->memcached_instance->setOption($option, $value);
    }

    // add servers
    foreach ($servers as $pos => $server)
    {
        $host   = Arr::get($server, 'host');
        $port   = Arr::get($server, 'port', NULL);
        $weight = Arr::get($server, 'weight', NULL);
        $status = Arr::get($server, 'status', TRUE);

        if (!empty($host))
        {
            // status can be used by an external healthcheck to mark the memcached instance offline
            if ($status === TRUE)
            {
                $this->memcached_instance->addServer($host, $port, $weight);
            }
        }
        else
        {
            // exception no server host
            throw new Kohana_Cache_Exception('no host defined for server[' .$pos . '] in config/cache.php');
        }
    }
}

protected _sanitize_id(string $id ) (defined in Kohana_Cache)

Replaces troublesome characters with underscores and adds prefix to avoid duplicates

// Sanitize a cache id
$id = $this->_sanitize_id($id);

Parameters

  • string $id required - Id of cache to sanitize

Return Values

  • string

Source Code

protected function _sanitize_id($id)
{

    // adding cache prefix to avoid duplicates
    $prefix = '';
    // configuration for the specific cache group
    if (isset($this->_config['prefix']) AND $this->_config['prefix'] !== NULL)
    {
        $prefix = $this->_config['prefix'];
    }
    // prefix general configuration cache
    else
    {
        $prefix = Kohana::$config->load('cache.prefix');
    }

    // sha1 the id makes sure name is not too long and has not any not allowed characters
    return $prefix.sha1($id);
}

Do you want to contribute to Koseven?

We need YOUR help!

This project is open source. What does this mean? YOU can help:
  • Found a bug? Report it on Github
  • Need a feature? Add it Here
  • Want to help? Join the Forum
Go to Github