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