1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Xetaravel\Livewire\Traits; |
||
6 | |||
7 | use Psr\Container\ContainerExceptionInterface; |
||
8 | use Psr\Container\NotFoundExceptionInterface; |
||
9 | |||
10 | trait WithCachedRows |
||
11 | { |
||
12 | /** |
||
13 | * Whatever we use the cache or not. |
||
14 | * |
||
15 | * @var bool |
||
16 | */ |
||
17 | protected bool $useCache = false; |
||
18 | |||
19 | /** |
||
20 | * Modify the option to use the cache. |
||
21 | * |
||
22 | * @return void |
||
23 | */ |
||
24 | public function useCachedRows(): void |
||
25 | { |
||
26 | $this->useCache = true; |
||
27 | } |
||
28 | |||
29 | /** |
||
30 | * Function to store and get back queries result from the cache. |
||
31 | * |
||
32 | * @param mixed $callback The callback function. (The query stored) |
||
33 | * |
||
34 | * @return mixed |
||
35 | * |
||
36 | * @throws ContainerExceptionInterface |
||
37 | * @throws NotFoundExceptionInterface |
||
38 | */ |
||
39 | public function cache(mixed $callback): mixed |
||
40 | { |
||
41 | $cacheKey = $this->getId(); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
42 | |||
43 | // If we use the cache and the cache has the id, return it. |
||
44 | if ($this->useCache && cache()->has($cacheKey)) { |
||
45 | return cache()->get($cacheKey); |
||
46 | } |
||
47 | |||
48 | // Get the callback result. |
||
49 | $result = $callback(); |
||
50 | |||
51 | // Store the result in the cache. |
||
52 | cache()->put($cacheKey, $result); |
||
53 | |||
54 | return $result; |
||
55 | } |
||
56 | } |
||
57 |