aboutsummaryrefslogtreecommitdiff
path: root/caches/MemcachedCache.php
blob: f994c1ae3f9f8cade2fd9f20ba83bbb3e81611d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

declare(strict_types=1);

class MemcachedCache implements CacheInterface
{
    private Logger $logger;
    private \Memcached $conn;

    public function __construct(
        Logger $logger,
        string $host,
        int $port
    ) {
        $this->logger = $logger;
        $this->conn = new \Memcached();
        // This call does not actually connect to server yet
        if (!$this->conn->addServer($host, $port)) {
            throw new \Exception('Unable to add memcached server');
        }
    }

    public function get(string $key, $default = null)
    {
        $value = $this->conn->get($key);
        if ($value === false) {
            return $default;
        }
        return $value;
    }

    public function set(string $key, $value, $ttl = null): void
    {
        $expiration = $ttl === null ? 0 : time() + $ttl;
        $result = $this->conn->set($key, $value, $expiration);
        if ($result === false) {
            $this->logger->warning('Failed to store an item in memcached', [
                'key'           => $key,
                'code'          => $this->conn->getLastErrorCode(),
                'message'       => $this->conn->getLastErrorMessage(),
                'number'        => $this->conn->getLastErrorErrno(),
            ]);
            // Intentionally not throwing an exception
        }
    }

    public function delete(string $key): void
    {
        $this->conn->delete($key);
    }

    public function clear(): void
    {
        $this->conn->flush();
    }

    public function prune(): void
    {
        // memcached manages pruning on its own
    }
}