3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
6 use Friendica\Database\Database;
7 use Friendica\Util\DateTimeFormat;
12 * @author Hypolite Petovan <hypolite@mrpetovan.com>
14 class DatabaseCache extends AbstractCache implements ICache
21 public function __construct(string $hostname, Database $dba)
23 parent::__construct($hostname);
31 public function getAllKeys($prefix = null)
34 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
36 $where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
39 $stmt = $this->dba->select('cache', ['k'], $where);
42 while ($key = $this->dba->fetch($stmt)) {
43 array_push($keys, $key['k']);
45 $this->dba->close($stmt);
53 public function get($key)
55 $cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
57 if ($this->dba->isResult($cache)) {
58 $cached = $cache['v'];
59 $value = @unserialize($cached);
61 // Only return a value if the serialized value is valid.
62 // We also check if the db entry is a serialized
63 // boolean 'false' value (which we want to return).
64 if ($cached === serialize(false) || $value !== false) {
75 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
79 'v' => serialize($value),
80 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
81 'updated' => DateTimeFormat::utcNow()
85 'v' => serialize($value),
87 'updated' => DateTimeFormat::utcNow()
91 return $this->dba->update('cache', $fields, ['k' => $key], true);
97 public function delete($key)
99 return $this->dba->delete('cache', ['k' => $key]);
105 public function clear($outdated = true)
108 return $this->dba->delete('cache', ['`expires` < NOW()']);
110 return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
114 public function __toString()
116 return self::TYPE_DATABASE;