Skip to content

Commit 28bff9e

Browse files
authored
Create LaravelCache.php
1 parent 8fc60b1 commit 28bff9e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/Utils/LaravelCache.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace ZhenMu\Support\Utils;
4+
5+
use Carbon\Carbon;
6+
use Illuminate\Support\Facades\Cache;
7+
8+
class LaravelCache
9+
{
10+
/**
11+
* 单位 秒
12+
*/
13+
const DEFAULT_CACHE_TIME = 3600;
14+
15+
/**
16+
* 执行指定函数并缓存指定时长
17+
*
18+
* @param string $cacheKey
19+
* @param callable|Carbon|null $cacheTime
20+
* @param callable|null $callable
21+
* @param boolean $forever
22+
* @return void
23+
*/
24+
public static function remember(string $cacheKey, callable|Carbon $cacheTime = null, callable $callable = null, $forever = false)
25+
{
26+
if (!is_callable($callable)) {
27+
return null;
28+
}
29+
30+
// 使用默认缓存时间
31+
if (is_callable($cacheTime)) {
32+
$callable = $cacheTime;
33+
$cacheTime = now()->addSeconds(CacheUtility::DEFAULT_CACHE_TIME);
34+
}
35+
36+
if ($forever) {
37+
$data = Cache::rememberForever($cacheKey, $callable);
38+
} else {
39+
$data = Cache::remember($cacheKey, $cacheTime, $callable);
40+
}
41+
42+
if (!$data) {
43+
Cache::pull($cacheKey);
44+
}
45+
46+
return $data;
47+
}
48+
49+
/**
50+
* 执行指定函数并永久缓存
51+
*
52+
* @param string $cacheKey
53+
* @param callable|Carbon|null $cacheTime
54+
* @param callable|null $callable
55+
* @return void
56+
*/
57+
public static function rememberForever(string $cacheKey, callable|Carbon $cacheTime = null, callable $callable = null)
58+
{
59+
return CacheUtility::remember($cacheKey, $cacheTime, $callable, true);
60+
}
61+
}

0 commit comments

Comments
 (0)