Skip to content

Instantly share code, notes, and snippets.

@mrl22
Last active February 25, 2024 14:48
Show Gist options
  • Save mrl22/e94ec1ff4f6bc507128bd8d5e7bbaf34 to your computer and use it in GitHub Desktop.
Save mrl22/e94ec1ff4f6bc507128bd8d5e7bbaf34 to your computer and use it in GitHub Desktop.
Psr\SimpleCache\CacheInterface implementation for Laravel - Tested on Laravel 10 with PHP 8.2
<?php
/**
* Created by PhpStorm.
* User: leo108
* Date: 2017/8/14
* Time: 15:44
*
* Updated by Richard Leishman to support PHP 8.2
*/
namespace App\Cache;
use Cache;
use Psr\SimpleCache\CacheInterface;
class SimpleCacheBridge implements CacheInterface
{
public function get($key, $default = null): mixed
{
return Cache::get($key, $default);
}
public function set($key, $value, $ttl = null): bool
{
Cache::put($key, $value, $this->ttl2minutes($ttl));
return true;
}
public function delete($key): bool
{
return Cache::forget($key);
}
public function clear(): bool
{
return Cache::flush();
}
public function getMultiple($keys, $default = null): iterable
{
return Cache::many($keys);
}
public function setMultiple($values, $ttl = null): bool
{
Cache::putMany((array)$values, $this->ttl2minutes($ttl));
return true;
}
public function deleteMultiple($keys): bool
{
foreach ($keys as $key) {
$this->delete($key);
}
return true;
}
public function has($key): bool
{
return Cache::has($key);
}
protected function ttl2minutes($ttl): float|int|null
{
if (is_null($ttl)) {
return null;
}
if ($ttl instanceof \DateInterval) {
return $ttl->days * 86400 + $ttl->h * 3600 + $ttl->i * 60;
}
return $ttl / 60;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment