模块

Cache_Memcache
继承自 Cache

BootPHP Cache Memcache driver,

Supported cache engines

Configuration example

Below is an example of a memcache server configuration.

return array(
    'default'   => array(                    // Default group
           'driver'     => 'memcache',     // using Memcache driver
           'servers'       => array(           // Available server definitions
                // First memcache server server
                array(
                    'host'         => 'localhost',
                    'port'         => 11211,
                    'persistent'      => false
                    'weight'         => 1,
                    'timeout'       => 1,
                    'retry_interval'   => 15,
                    'status'         => true,
            'instant_death'    => true,
                    'failure_callback' => array('className', 'classMethod')
                ),
                // Second memcache server
                array(
                    'host'         => '192.168.1.5',
                    'port'         => 22122,
                    'persistent'      => true
                )
           ),
           'compression'    => false,          // Use compression?
     ),
)

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 all types of cache driver.

Name Required Description
driver YES (string) The driver type to use
servers YES (array) Associative array of server details, must include a host key. (see Memcache server configuration below)
compression NO (boolean) Use data compression when caching

Memcache server configuration

The following settings should be used when defining each memcache server

Name Required Description
host YES (string) The host of the memcache server, i.e. localhost; or 127.0.0.1; or memcache.domain.tld
port NO (integer) Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets. Default 11211
persistent NO (boolean) Controls the use of a persistent connection. Default true
weight NO (integer) Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers. Default 1
timeout NO (integer) Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. Default 1
retry_interval NO (integer) Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Default 15
status NO (boolean) Controls if the server should be flagged as online. Default true
failure_callback NO (callback) Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server. Default NULL

System requirements

  • BootPHP 3.0.x
  • PHP 5.2.4 or greater
  • Memcache (plus Memcached-tags for native tagging support)
  • Zlib
package
BootPHP/缓存
author
Tinsh
copyright
© 2005-2016 Kilofox Studio

该类在 MODPATH/cache/classes/cache/memcache.php 第 83 行声明。

常量

CACHE_CEILING

integer 2592000

DEFAULT_EXPIRE

integer 3600

属性

public static string $default

default driver to use

string(4) "file"

public static BootPHP_Cache $instances

instances

array(0) 

protected Config $_config

protected array $_default_config

The default configuration for the memcached server

protected string $_flags

Flags to use when storing values

protected Memcache $_memcache

Memcache resource

方法

public _failed_request( string $hostname , integer $port ) (在 Cache_Memcache 中定义)

Callback method for Memcache::failure_callback to use if any Memcache call on a particular server fails. This method switches off that instance of the server if the configuration setting `instant_death` is set to `true`.

参数

  • string $hostname required - Hostname
  • integer $port required - Port

Tags

  • Since - 3.0.8

返回值

  • void|boolean

源代码

public function _failed_request($hostname, $port)
{
	if (!$this->_config['instant_death'])
		return;
	// Setup non-existent host
	$host = false;
	// Get host settings from configuration
	foreach ($this->_config['servers'] as $server)
	{
		// Merge the defaults, since they won't always be set
		$server += $this->_default_config;
		// We're looking at the failed server
		if ($hostname == $server['host'] and $port == $server['port'])
		{
			// Server to disable, since it failed
			$host = $server;
			continue;
		}
	}
	if (!$host)
		return;
	else
	{
		return $this->_memcache->setServerParams(
				$host['host'], $host['port'], $host['timeout'], $host['retry_interval'], false, // Server is offline
				array($this, '_failed_request'
		));
	}
}

public decrement( string $id [, int $step = integer 1 ] ) (在 Cache_Memcache 中定义)

Decrements 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

返回值

  • integer
  • boolean

源代码

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

public delete( string $id [, integer $timeout = integer 0 ] ) (在 Cache_Memcache 中定义)

Delete a cache entry based on id

// Delete the 'foo' cache entry immediately
Cache::instance('memcache')->delete('foo');

// Delete the 'bar' cache entry after 30 seconds
Cache::instance('memcache')->delete('bar', 30);

参数

  • string $id required - Id of entry to delete
  • integer $timeout = integer 0 - Timeout of entry, if zero item is deleted immediately, otherwise the item will delete after the specified value in seconds

返回值

  • boolean

源代码

public function delete($id, $timeout = 0)
{
	// Delete the id
	return $this->_memcache->delete($this->_sanitize_id($id), $timeout);
}

public deleteAll( ) (在 Cache_Memcache 中定义)

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('memcache')->deleteAll();

返回值

  • boolean

源代码

public function deleteAll()
{
	$result = $this->_memcache->flush();
	// We must sleep after flushing, or overwriting will not work!
	// @see http://php.net/manual/en/function.memcache-flush.php#81420
	sleep(1);
	return $result;
}

public get( string $id [, string $default = NULL ] ) (在 Cache_Memcache 中定义)

Retrieve a cached value entry by id.

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

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

参数

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

Tags

返回值

  • mixed

源代码

public function get($id, $default = NULL)
{
	// Get the value from Memcache
	$value = $this->_memcache->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 ] ) (在 Cache_Memcache 中定义)

Increments 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

返回值

  • integer
  • boolean

源代码

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

public set( string $id , mixed $data [, integer $lifetime = integer 3600 ] ) (在 Cache_Memcache 中定义)

Set a value to cache with id and lifetime

$data = 'bar';

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

参数

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

返回值

  • boolean

源代码

public function set($id, $data, $lifetime = 3600)
{
	// If the lifetime is greater than the ceiling
	if ($lifetime > Cache_Memcache::CACHE_CEILING)
	{
		// Set the lifetime to maximum cache time
		$lifetime = Cache_Memcache::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 memcache
	return $this->_memcache->set($this->_sanitize_id($id), $data, $this->_flags, $lifetime);
}

final public __clone( ) (在 Cache 中定义)

Overload the __clone() method to prevent cloning

Tags

返回值

  • void

源代码

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

public config( [ mixed $key = NULL , mixed $value = NULL ] ) (在 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);

参数

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

public static instance( [ string $group = NULL ] ) (在 Cache 中定义)

Creates a singleton of a BootPHP 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]

Tags

返回值

  • BootPHP_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 = BootPHP::$config->load('cache');
	if (!$config->offsetExists($group))
	{
		throw new Cache_Exception(
		'Failed to load BootPHP Cache group: :group', array(':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 ) (在 Cache_Memcache 中定义)

Constructs the memcache BootPHP_Cache object

参数

  • array $config required - Configuration

Tags

源代码

protected function __construct(array $config)
{
	// Check for the memcache extention
	if (!extension_loaded('memcache'))
	{
		throw new Cache_Exception('Memcache PHP extention not loaded');
	}
	parent::__construct($config);
	// Setup Memcache
	$this->_memcache = new Memcache;
	// 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 Memcache servers defined in configuration');
	}
	// Setup default server configuration
	$this->_default_config = array(
		'host' => 'localhost',
		'port' => 11211,
		'persistent' => false,
		'weight' => 1,
		'timeout' => 1,
		'retry_interval' => 15,
		'status' => true,
		'instant_death' => true,
		'failure_callback' => array($this, '_failed_request'),
	);
	// Add the memcache servers to the pool
	foreach ($servers as $server)
	{
		// Merge the defined config with defaults
		$server += $this->_default_config;
		if (!$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'], $server['weight'], $server['timeout'], $server['retry_interval'], $server['status'], $server['failure_callback']))
		{
			throw new Cache_Exception('Memcache could not connect to host \':host\' using port \':port\'', array(':host' => $server['host'], ':port' => $server['port']));
		}
	}
	// Setup the flags
	$this->_flags = Arr::get($this->_config, 'compression', false) ? MEMCACHE_COMPRESSED : false;
}

protected _sanitize_id( string $id ) (在 Cache 中定义)

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(array('/', '\\', ' '), '_', $id);
}