Last active
February 25, 2024 14:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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