ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Memcached.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
21namespace ILIAS\Cache\Adaptor;
22
24
28class Memcached extends BaseAdaptor implements Adaptor
29{
33 private const PERSISTENT_ID = 'ilias_cache';
34 private ?\Memcached $server = null;
35
36 public function __construct(Config $config)
37 {
38 parent::__construct($config);
39 if (!class_exists(\Memcached::class)) {
40 return;
41 }
42 if ($config->getNodes() === []) {
43 return;
44 }
45 $this->initServer($config);
46 }
47
48
49 public function isAvailable(): bool
50 {
51 return class_exists(\Memcached::class) && $this->server !== null && $this->server->getVersion() !== false;
52 }
53
54 public function has(string $container, string $key): bool
55 {
56 return $this->server->get($this->buildKey($container, $key)) !== false;
57 }
58
59 public function get(string $container, string $key): ?string
60 {
61 return $this->server->get($this->buildKey($container, $key)) ?: null;
62 }
63
64 public function set(string $container, string $key, string $value, int $ttl): void
65 {
66 $this->server->set($this->buildKey($container, $key), $value, $ttl);
67 }
68
69 public function delete(string $container, string $key): void
70 {
71 $this->server->delete($this->buildKey($container, $key), 0);
72 }
73
74 public function flushContainer(string $container): void
75 {
76 $prefix = $this->buildContainerPrefix($container);
77 foreach ($this->server->getAllKeys() as $key) {
78 if (str_starts_with((string) $key, $prefix)) {
79 $this->server->set($key, false, 0);
80 }
81 }
82 foreach ($this->server->getAllKeys() as $key) {
83 if (str_starts_with((string) $key, $prefix)) {
84 $this->server->get(
85 $key
86 ); // invalidates the key, see https://www.php.net/manual/en/memcached.expiration.php
87 }
88 }
89 $this->server->flushBuffers();
90 // $this->lock(1);// see https://github.com/memcached/memcached/issues/307
91 }
92
93 public function flush(): void
94 {
95 $this->server->flush();
96 }
97
98 protected function initServer(Config $config): void
99 {
100 $this->server = new \Memcached(self::PERSISTENT_ID);
101 $nodes = $config->getNodes();
102 foreach ($nodes as $node) {
103 $this->server->addServer(
104 $node->getHost(),
105 $node->getPort(),
106 $node->getWeight() ?? 100 / count($nodes)
107 );
108 }
109 }
110}
buildKey(string $container, string $key)
Definition: BaseAdaptor.php:42
buildContainerPrefix(string $container)
Definition: BaseAdaptor.php:47
initServer(Config $config)
Definition: Memcached.php:98
flushContainer(string $container)
Definition: Memcached.php:74
__construct(Config $config)
Definition: Memcached.php:36
has(string $container, string $key)
Definition: Memcached.php:54
__construct(Container $dic, ilPlugin $plugin)
@inheritDoc
$container
@noRector
Definition: wac.php:37