Modules

Kohana_Cache_Memcached
extends Cache
extends Kohana_Cache

Implements: Cache_Arithmetic | Kohana_Cache_Arithmetic

This class is a transparent base class for Cache_Memcached and should not be accessed directly.

Kohana Cache Memcached driver. Provides a memcached based driver for the Kohana Cache library.

Supported cache engines

Configuration example

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.

General cache group configuration settings

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)

Memcached server configuration

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

System requirements

  • Memcached
  • Memcached PHP extension
package
Kohana/Cache
category
Base
author
Tinsh
copyright
© 2018 Kohana Group
license
https://kohana.top/license

Class declared in MODPATH/cache/classes/Kohana/Cache/Memcached.php on line 77.

Constants

CACHE_CEILING

integer 2592000

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 array $defaultConfig

The default configuration for the memcached server.

Default value:
array(0) 

protected Memcached $memcached

Memcached resource.

Default value:
NULL

protected array $options

Memcached options.

Default value:
array(0) 

Methods

public decrement( string $id [, int $step = integer 1 ] ) (defined in Kohana_Cache_Memcached)

Decrement a given value by the step value supplied. Useful for shared counters and other persistent integer based tracking.

Parameters

  • string $id required - Id of cache entry to decrement.
  • int $step = integer 1 - Step value to decrement by.

Return Values

  • int
  • bool

Source Code

public function decrement($id, $step = 1)
{
    return $this->memcached->decrement($id, $step);
}

public delete( string $id [, int $time = integer 0 ] ) (defined in Kohana_Cache_Memcached)

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

Parameters

  • string $id required - Id of entry to delete.
  • int $time = integer 0 - The amount of time the server will wait to delete the entry.

Return Values

  • bool

Source Code

public function delete($id, $time = 0)
{
    return $this->memcached->delete($this->_sanitize_id($id), $time);
}

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

Return Values

  • bool

Source Code

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

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

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

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)
{
    // 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;
}

public increment( string $id [, int $step = integer 1 ] ) (defined in Kohana_Cache_Memcached)

Increment a given value by the step value supplied. Useful for shared counters and other persistent integer based tracking.

Parameters

  • string $id required - Id of cache entry to increment.
  • int $step = integer 1 - Step value to increment by.

Return Values

  • int
  • bool

Source Code

public function increment($id, $step = 1)
{
    return $this->memcached->increment($id, $step);
}

public set( string $id , mixed $data [, int $lifetime = NULL ] ) (defined in Kohana_Cache_Memcached)

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

Parameters

  • string $id required - Id of cache entry.
  • mixed $data required - Data to set to cache.
  • int $lifetime = NULL - Lifetime in seconds, maximum value 2592000.

Return Values

  • bool

Source Code

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

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

// Set a new configuration setting
$cache->config('servers', ['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
    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)

Construct the memcached cache driver. This method cannot be invoked externally. The file cache driver must be instantiated using the Cache::instance() method.

Parameters

  • array $config required - Configuration

Tags

Source Code

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

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

Replaces troublesome characters with underscores.

// 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)
{
    // Change slashes and spaces to underscores
    return str_replace(['/', '\\', ' '], '_', $id);
}