]> git.mxchange.org Git - friendica.git/blob - src/Core/Cache/RedisCacheDriver.php
Merge pull request #5042 from Quix0r/rewrites/curly-braces-is-result-usage-002
[friendica.git] / src / Core / Cache / RedisCacheDriver.php
1 <?php
2
3 namespace Friendica\Core\Cache;
4
5 use Friendica\BaseObject;
6 use Friendica\Core\Cache;
7
8 /**
9  * Redis Cache Driver. This driver is based on Memcache driver
10  *
11  * @author Hypolite Petovan <mrpetovan@gmail.com>
12  * @author Roland Haeder <roland@mxchange.org>
13  */
14 class RedisCacheDriver extends BaseObject implements ICacheDriver
15 {
16         /**
17          * @var Redis
18          */
19         private $redis;
20
21         public function __construct($redis_host, $redis_port)
22         {
23                 if (!class_exists('Redis', false)) {
24                         throw new \Exception('Redis class isn\'t available');
25                 }
26
27                 $this->redis = new \Redis();
28
29                 if (!$this->redis->connect($redis_host, $redis_port)) {
30                         throw new \Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
31                 }
32         }
33
34         public function get($key)
35         {
36                 $return = null;
37
38                 // We fetch with the hostname as key to avoid problems with other applications
39                 $cached = $this->redis->get(self::getApp()->get_hostname() . ':' . $key);
40
41                 // @see http://php.net/manual/en/redis.get.php#84275
42                 if (is_bool($cached) || is_double($cached) || is_long($cached)) {
43                         return $return;
44                 }
45
46                 $value = @unserialize($cached);
47
48                 // Only return a value if the serialized value is valid.
49                 // We also check if the db entry is a serialized
50                 // boolean 'false' value (which we want to return).
51                 if ($cached === serialize(false) || $value !== false) {
52                         $return = $value;
53                 }
54
55                 return $return;
56         }
57
58         public function set($key, $value, $duration = Cache::MONTH)
59         {
60                 // We store with the hostname as key to avoid problems with other applications
61                 return $this->redis->set(
62                         self::getApp()->get_hostname() . ":" . $key,
63                         serialize($value),
64                         time() + $duration
65                 );
66         }
67
68         public function delete($key)
69         {
70                 return $this->redis->delete($key);
71         }
72
73         public function clear()
74         {
75                 return true;
76         }
77 }