2019-05-03 12:56:07 +03:00
|
|
|
<?php
|
2022-07-01 16:10:30 +03:00
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2022-07-01 16:10:30 +03:00
|
|
|
class MemcachedCache implements CacheInterface
|
|
|
|
{
|
2023-09-21 23:05:55 +03:00
|
|
|
private Logger $logger;
|
2023-09-10 22:50:15 +03:00
|
|
|
private \Memcached $conn;
|
2022-07-01 16:10:30 +03:00
|
|
|
|
2023-09-21 23:05:55 +03:00
|
|
|
public function __construct(
|
|
|
|
Logger $logger,
|
|
|
|
string $host,
|
|
|
|
int $port
|
|
|
|
) {
|
|
|
|
$this->logger = $logger;
|
2023-09-10 22:50:15 +03:00
|
|
|
$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');
|
2022-08-06 23:46:28 +03:00
|
|
|
}
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
public function get(string $key, $default = null)
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2023-09-10 22:50:15 +03:00
|
|
|
$value = $this->conn->get($key);
|
2023-07-19 06:05:49 +03:00
|
|
|
if ($value === false) {
|
2023-09-10 22:50:15 +03:00
|
|
|
return $default;
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
2023-09-10 22:50:15 +03:00
|
|
|
return $value;
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
public function set(string $key, $value, $ttl = null): void
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2023-09-10 22:50:15 +03:00
|
|
|
$expiration = $ttl === null ? 0 : time() + $ttl;
|
|
|
|
$result = $this->conn->set($key, $value, $expiration);
|
2022-07-01 16:10:30 +03:00
|
|
|
if ($result === false) {
|
2023-09-21 23:05:55 +03:00
|
|
|
$this->logger->warning('Failed to store an item in memcached', [
|
2023-09-10 22:50:15 +03:00
|
|
|
'key' => $key,
|
2023-07-19 06:05:49 +03:00
|
|
|
'code' => $this->conn->getLastErrorCode(),
|
|
|
|
'message' => $this->conn->getLastErrorMessage(),
|
|
|
|
'number' => $this->conn->getLastErrorErrno(),
|
|
|
|
]);
|
|
|
|
// Intentionally not throwing an exception
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
public function delete(string $key): void
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2023-09-10 22:50:15 +03:00
|
|
|
$this->conn->delete($key);
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
public function clear(): void
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2023-09-10 22:50:15 +03:00
|
|
|
$this->conn->flush();
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
|
|
|
|
2023-09-10 22:50:15 +03:00
|
|
|
public function prune(): void
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2023-09-10 22:50:15 +03:00
|
|
|
// memcached manages pruning on its own
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
2019-05-03 12:56:07 +03:00
|
|
|
}
|