3 * @file src/Core/Cache.php
5 namespace Friendica\Core;
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
11 * @brief Class for storing data for a short time
13 class Cache extends \Friendica\BaseObject
15 const MONTH = 2592000;
19 const HALF_HOUR = 1800;
20 const QUARTER_HOUR = 900;
21 const FIVE_MINUTES = 300;
25 * @var Cache\ICacheDriver
27 static $driver = null;
29 public static function init()
31 switch(Config::get('system', 'cache_driver', 'database')) {
33 $memcache_host = Config::get('system', 'memcache_host', '127.0.0.1');
34 $memcache_port = Config::get('system', 'memcache_port', 11211);
36 self::$driver = new Cache\MemcacheCacheDriver($memcache_host, $memcache_port);
39 $memcached_hosts = Config::get('system', 'memcached_hosts', [['127.0.0.1', 11211]]);
41 self::$driver = new Cache\MemcachedCacheDriver($memcached_hosts);
44 $redis_host = Config::get('system', 'redis_host', '127.0.0.1');
45 $redis_port = Config::get('system', 'redis_port', 6379);
47 self::$driver = new Cache\RedisCacheDriver($redis_host, $redis_port);
50 self::$driver = new Cache\DatabaseCacheDriver();
55 * Returns the current cache driver
57 * @return Cache\ICacheDriver
59 private static function getDriver()
61 if (self::$driver === null) {
69 * @brief Fetch cached data according to the key
71 * @param string $key The key to the cached data
73 * @return mixed Cached $value or "null" if not found
75 public static function get($key)
77 $time = microtime(true);
79 $return = self::getDriver()->get($key);
81 self::getApp()->save_timestamp($time, 'cache');
87 * @brief Put data in the cache according to the key
89 * The input $value can have multiple formats.
91 * @param string $key The key to the cached data
92 * @param mixed $value The value that is about to be stored
93 * @param integer $duration The cache lifespan
97 public static function set($key, $value, $duration = self::MONTH)
99 $time = microtime(true);
101 $return = self::getDriver()->set($key, $value, $duration);
103 self::getApp()->save_timestamp($time, 'cache_write');
109 * @brief Delete a value from the cache
111 * @param string $key The key to the cached data
115 public static function delete($key)
117 $time = microtime(true);
119 $return = self::getDriver()->delete($key);
121 self::getApp()->save_timestamp($time, 'cache_write');
127 * @brief Remove outdated data from the cache
129 * @param integer $max_level The maximum cache level that is to be cleared
133 public static function clear()
135 return self::getDriver()->clear();