class Cache implements CacheInterface
{  
   protected \Memcached $cache;
   
   function __construct()
   {
       $this->cache = new \Memcached;
   }
   
   function store(mixed $key, mixed $data, $ttl): bool
   {
       try {
           $result = $this->cache->set($key, $data, $ttl);
           if (!$result) {
               throw new Exception('Failed to store data in cache.');
           }
           return $result;
       } catch (\MemcachedException $e) {
           throw new Exception(sprintf('Failed to store data in cache. %s', $e->getMessage()), 0, $e);
       }
   }

   function fetch(mixed $key): mixed
   {
       $result = $this->cache->get($key);
       if ($this->cache->getResultCode() == Memcached::RES_NOTFOUND) {
           return false;
       }
       if ($result === false) {
           throw new Exception('Failed to fetch data from cache. Error: ' . $this->cache->getResultMessage());
       }
       return $result;
   }

   function delete(mixed $key): bool
   {
       $result = $this->cache->delete($key);
       if ($result === false) {
           throw new Exception('Failed to delete data from cache: ' . $this->cache->getResultMessage());
       }
       return $result;
   }

   function addServer(string $host, int $port = 11211, int $weight = 10): void
   {
       try {
           $result = $this->cache->addServer($host, $port, $weight);
           if (!$result) {
               throw new Exception(sprintf('Failed to add Memcached server %s:%d.', $host, $port));
           }
       } catch (Throwable $e) {
           throw new Exception(sprintf('Failed to add Memcached server %s:%d: %s', $host, $port, $e->getMessage()));
       }
   }
}



interface CacheInterface
{
   public function store(string $key, mixed $data, int $ttl): bool;
   public function fetch(string $key): mixed;
   public function delete(string $key): bool;
   public function addServer(string $host, int $port = 11211, int $weight = 10): void;
}
Last edited by STorrents2020 on 2023-03-10 00:21:30