koel/app/Services/MediaCacheService.php

60 lines
1.2 KiB
PHP
Raw Normal View History

2017-01-06 03:04:08 +00:00
<?php
namespace App\Services;
use App\Models\Album;
2017-01-06 03:04:08 +00:00
use App\Models\Artist;
use App\Models\Song;
2018-08-19 14:56:56 +00:00
use Illuminate\Cache\Repository as Cache;
2017-01-06 03:04:08 +00:00
2018-08-19 14:56:56 +00:00
class MediaCacheService
2017-01-06 03:04:08 +00:00
{
2018-08-24 15:27:19 +00:00
private const CACHE_KEY = 'media_cache';
2018-08-19 14:56:56 +00:00
private $cache;
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
2017-01-06 03:04:08 +00:00
2017-08-05 21:51:59 +00:00
/**
2017-08-05 22:27:41 +00:00
* Get media data.
2017-08-05 21:51:59 +00:00
* If caching is enabled, the data will be retrieved from the cache.
2017-08-05 22:27:41 +00:00
*
2020-12-22 20:11:22 +00:00
* @return array<mixed>
2017-08-05 21:51:59 +00:00
*/
2018-08-24 15:27:19 +00:00
public function get(): array
2017-01-06 03:04:08 +00:00
{
2017-01-15 04:27:05 +00:00
if (!config('koel.cache_media')) {
return $this->query();
2017-01-15 04:27:05 +00:00
}
2019-07-22 07:03:23 +00:00
return $this->cache->rememberForever(self::CACHE_KEY, function (): array {
2017-08-05 21:51:59 +00:00
return $this->query();
});
2017-01-06 03:04:08 +00:00
}
/**
* Query fresh data from the database.
*
2020-12-22 20:11:22 +00:00
* @return array<mixed>
*/
2018-08-24 15:27:19 +00:00
private function query(): array
{
return [
'albums' => Album::orderBy('name')->get(),
'artists' => Artist::orderBy('name')->get(),
'songs' => Song::all(),
];
}
2017-08-05 21:51:59 +00:00
/**
* Clear the media cache.
*/
2018-08-24 15:27:19 +00:00
public function clear(): void
2017-01-06 03:04:08 +00:00
{
2018-08-24 15:27:19 +00:00
$this->cache->forget(self::CACHE_KEY);
2017-01-06 03:04:08 +00:00
}
}