-
Notifications
You must be signed in to change notification settings - Fork 10
Cache
The Cache module allow you to handle an object persistence between requests and store heavy-computing persistent data.
The simplest way to retrieve a value from cache is via the get method.
$shares = Cache::get('shares');You can optionally pass a default value and an expire time. The dafault value can be either a mixed or a callable. If you pass the latter it will invoked and the returned value will be used as the default value.
$help = Cache::get('help',true);
$shares = Cache::get('shares',function(){
return calc_user_shares();
});Important: When the default value is used (from a cache miss), the cache value will be setted.
$value_generator = function(){
return time();
};
echo Cache::get('memento',$value_generator); // (Cache MISS) returned : 1389122001 ($value_generator called)
echo Cache::get('memento',$value_generator); // (Cache HIT) returned : 1389122001
echo Cache::get('memento',$value_generator); // (Cache HIT) returned : 1389122001You can set a value for a key with the set method.
Cache::set('friend_or_foe','friend');You can pass an optional expiration parameter in seconds.
Cache::set('friend_or_foe','friend',15); // Expire in 15 sec
echo Cache::get('friend_or_foe'); // friend
sleep(20);
echo Cache::get('friend_or_foe'); // (no value)You can delete a cached key with the delete method.
Cache::delete('friend_or_foe');You can delete all cached keys with the flush method.
Cache::flush();You can delete a cached key with the exists method.
if ( Cache::exists('user_info') ) { ... }You can increment/decrement a cached key value with the inc and dec methods.
Example
Event::on('user.login',function(){
Cache::inc('user.logged');
});
Event::on('user.logout',function(){
Cache::dec('user.logged');
});Default inc/dec value is 1, you can however change it by passing the increment/decrement value as the second parameter of the inc/dec methods.
Event::on('boss.killed',function(){
Cache::inc('user.score',1000);
});You can choose the Cache driver via the using method. The optional second parameter is dictionary of init paramenters to pass to the selected driver.
The default driver is Memory, a request-only persistent storage.
Example
// Use File-based caching
Cache::using('File',[
'cache_dir' => __DIR__ . '/cache'
]);You can bybass all cache by passing false to the Cache::enable method.
Cache::enabled(false);A common use for this is for disabling cache in debug mode.
Cache::enabled(!Options::get('debug',false));Core is maintained by using the Semantic Versioning Specification (SemVer).
Copyright 2014-2016 Caffeina srl under the MIT license.
http://caffeina.com