lithium\storage\Cache::key()
Generates one or multiple safe cache keys optionally adding a suffix with a hash over the provided data. The hash value is generated in an optimized way dependending on the type of data.
Simple usage (in this case noop):
Cache::key('default', 'post');
// returns `'post'`
Cache::key('default', ['posts', 'banners']);
// returns `['posts', 'banners']`
Cache::key('default', ['posts' => 'foo', 'banners' => 'bar]);
// returns `['posts' => 'foo', 'banners' => 'bar']`
Make a key safe to use with adapter (exact result depends on key constraints enforced by the selected adapter:
Cache::key('default', 'posts for Helgi Þorbjörnsson');
// returns `'posts_for_Helgi__orbj_rnsson_c7f8433a'`
Using additional scalar or non-scalar data to generate key:
Cache::key('default', 'post', 2);
// returns `'post:1ad5be0d'`
Cache::key('default', 'post', array(2, 'json'));
// returns `'post:723f0e19'`
Cache::key('default', ['posts', 'banners'], 'json');
// returns `['posts:6b072545', 'banners:6b072545']`
Cache::key('default', ['posts' => 'foo', 'banners' => 'bar'], 'json');
// returns `['posts:38ec40e5' => 'foo', 'banners:38ec40e5' => 'bar']`
Or with a resuable key generator function:
$posts[0] = ['id' => 1];
$posts[1] = ['id' => 2];
$key = function($data) { return 'post:' . $data['id']};
Cache::key('default', $key, $post[0]); // returns `'post:1'`
Cache::key('default', $key, $post[1]); // returns `'post:2'`
This example shows a key mutating generator function:
$base = 'post';
$key = function($id) use (&base) { return $base .= ":{$id}"; };
Cache::key('default', $key, 1); // returns `'post:1'`
Cache::key('default', $key, 2); // returns `'post:1:2'`
Parameters
-
string
$name
Configuration to be used for generating key/s.
-
mixed
$key
String or an array of strings that will be used as the cache key/s. Also accepts associative arrays where the key part will be modified, but the value left untouched. Also accepts a key generator function that is passed $data and must return a string that will be used as the key.
-
mixed
$data
Additional data to use when generating key. Can be any kind of type except a resource. The method will calculate a hash of the data and append that to the key/s. When $key is a function the data is passed to it instead.
Returns
string|arrayThe generated cache key/s.
Source
public static function key($name, $key, $data = null) {
$adapter = static::adapter($name);
if (is_callable($key)) {
return current($adapter->key([$key($data)]));
}
$keys = ($isMulti = is_array($key)) ? $key : [$key];
$keys = ($hasData = !is_integer(key($keys))) ? array_keys($keys) : $keys;
if ($data !== null) {
$data = Hash::calculate($data, ['type' => 'crc32b']);
$keys = array_map(function($key) use ($data) { return $key .= ":{$data}"; }, $keys);
}
$keys = $adapter->key($keys);
$keys = $hasData ? array_combine($keys, array_values((array) $key)) : $keys;
return $isMulti ? $keys : current($keys);
}