taktik - laravel
This commit is contained in:
75
app/Services/Post/CachedPostService.php
Normal file
75
app/Services/Post/CachedPostService.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Post;
|
||||
|
||||
use App\Models\Post;
|
||||
use App\Services\CacheKeyBuilder;
|
||||
use App\Services\PaginableResource;
|
||||
use App\Services\QueryRequestModifiers\Post\PostFilter;
|
||||
use App\Services\QueryRequestModifiers\Post\PostFilterDTO;
|
||||
use App\Services\QueryRequestModifiers\Post\PostOrder;
|
||||
use App\Services\QueryRequestModifiers\Post\PostOrderDTO;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class CachedPostService extends PostService
|
||||
{
|
||||
public function __construct(
|
||||
PostFilter $postFilter,
|
||||
PostOrder $postOrder,
|
||||
protected readonly CacheKeyBuilder $cacheKeyBuilder,
|
||||
protected readonly int $cacheTtl = 60,
|
||||
) {
|
||||
parent::__construct($postFilter, $postOrder);
|
||||
}
|
||||
|
||||
public function fetchPosts(int $page, ?PostFilterDTO $filters, ?PostOrderDTO $orderDef): PaginableResource
|
||||
{
|
||||
return Cache::tags(['posts', 'fetch-posts', 'post-page-' . $page])
|
||||
->remember(
|
||||
$this->cacheKeyBuilder->buildCacheKeyFromArgs('post-page', $page, $filters, $orderDef),
|
||||
$this->cacheTtl,
|
||||
function () use ($page, $filters, $orderDef) {
|
||||
return parent::fetchPosts($page, $filters, $orderDef);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public function findPost(int $id): ?Post
|
||||
{
|
||||
return Cache::tags(['posts', 'find-post-' . $id])
|
||||
->remember('post-' . $id, $this->cacheTtl, function () use ($id) {
|
||||
return parent::findPost($id);
|
||||
});
|
||||
}
|
||||
|
||||
public function storePost(array $data): Post
|
||||
{
|
||||
$newPost = parent::storePost($data);
|
||||
|
||||
Cache::tags('fetch-posts')->flush();
|
||||
|
||||
return $newPost;
|
||||
}
|
||||
|
||||
public function updatePost(array $data, int $id): ?Post
|
||||
{
|
||||
$updatedPost = parent::updatePost($data, $id);
|
||||
|
||||
if ($updatedPost !== null) {
|
||||
Cache::tags('fetch-posts')->flush();
|
||||
Cache::tags('find-post-' . $id)->flush();
|
||||
}
|
||||
|
||||
return $updatedPost;
|
||||
}
|
||||
|
||||
public function deletePost(int $id): bool
|
||||
{
|
||||
Cache::tags('fetch-posts')->flush();
|
||||
Cache::tags('find-post-' . $id)->flush();
|
||||
|
||||
return parent::deletePost($id); // TODO: Change the autogenerated stub
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user