Skip to content

Commit

Permalink
feat: cache (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiio authored Nov 27, 2024
1 parent 6366d0f commit 96867e3
Show file tree
Hide file tree
Showing 25 changed files with 236 additions and 121 deletions.
24 changes: 24 additions & 0 deletions app/Concerns/ClearsCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Concerns;

use Illuminate\Support\Facades\Cache;

trait ClearsCache
{
abstract public function getCacheTags(): array;

public static function bootClearsCache(): void
{
self::created(fn (self $model) => self::clearCache($model));
self::updated(fn (self $model) => self::clearCache($model));
self::deleted(fn (self $model) => self::clearCache($model));
}

private static function clearCache(self $model): void
{
Cache::tags($model->getCacheTags())->flush();
}
}
10 changes: 0 additions & 10 deletions app/Contracts/ClearsCache.php

This file was deleted.

5 changes: 0 additions & 5 deletions app/Jobs/PersistTemporaryTableData.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace App\Jobs;

use App\Contracts\ClearsCache;
use App\Contracts\TemporaryTable;
use App\Jobs\Middleware\RateLimitSchedulableJobMiddleware;
use Exception;
Expand Down Expand Up @@ -65,10 +64,6 @@ public function handle(): void
ON DUPLICATE KEY UPDATE {$updateColumns};
SQL);
}

if ($model instanceof ClearsCache) {
$model->clearCache($this->electionId);
}
}

public function middleware(): array
Expand Down
20 changes: 12 additions & 8 deletions app/Livewire/NewsFeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

use App\Models\Article;
use App\Models\Election;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Services\CacheService;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithPagination;
Expand All @@ -28,13 +29,16 @@ public function reload(): void
}

#[Computed]
protected function articles(): LengthAwarePaginator
protected function articles(): Collection
{
return Article::query()
->whereBelongsTo($this->election)
->with('author.media', 'media')
->onlyPublished()
->orderByDesc('published_at')
->paginate(50);
return CacheService::make('articles', $this->election)
->remember(
fn () => Article::query()
->whereBelongsTo($this->election)
->with('author.media', 'media')
->onlyPublished()
->orderByDesc('published_at')
->get()
);
}
}
65 changes: 42 additions & 23 deletions app/Livewire/Pages/ElectionPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use App\Models\County;
use App\Models\Election;
use App\Models\Locality;
use App\Services\CacheService;
use ArchTech\SEO\SEOManager;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Select;
Expand Down Expand Up @@ -46,6 +47,7 @@ abstract class ElectionPage extends Component implements HasForms
public function mount()
{
$this->checkDefaultPage();

$validation = Validator::make([
'country' => $this->country,
'county' => $this->county,
Expand Down Expand Up @@ -91,13 +93,17 @@ public function form(Form $form): Form
->label(__('app.field.country'))
->placeholder(__('app.field.country'))
->hiddenLabel()
->options(
fn () => Country::query()
->whereHas($whereHasKey, function (Builder $query) {
$query->whereBelongsTo($this->election);
})
->pluck('name', 'id')
)
->options(function () use ($whereHasKey) {
return CacheService::make(['countries', $whereHasKey], $this->election)
->remember(
fn () => Country::query()
->whereHas($whereHasKey, function (Builder $query) {
$query->whereBelongsTo($this->election)
->whereNotNull('country_id');
})
->pluck('name', 'id')
);
})
->afterStateUpdated(function (Set $set) {
$set('county', null);
$set('locality', null);
Expand All @@ -110,13 +116,17 @@ public function form(Form $form): Form
->label(__('app.field.county'))
->placeholder(__('app.field.county'))
->hiddenLabel()
->options(
fn () => County::query()
->whereHas($whereHasKey, function (Builder $query) {
$query->whereBelongsTo($this->election);
})
->pluck('name', 'id')
)
->options(function () use ($whereHasKey) {
return CacheService::make(['counties', $whereHasKey], $this->election)
->remember(
fn () => County::query()
->whereHas($whereHasKey, function (Builder $query) use ($whereHasKey) {
$query->whereBelongsTo($this->election)
->whereNotNull("{$whereHasKey}.county_id");
})
->pluck('name', 'id')
);
})
->afterStateUpdated(function (Set $set) {
$set('locality', null);
})
Expand All @@ -128,15 +138,24 @@ public function form(Form $form): Form
->label(__('app.field.locality'))
->hiddenLabel()
->placeholder(__('app.field.locality'))
->options(
fn (Get $get) => Locality::query()
->where('county_id', $get('county'))
->whereHas($whereHasKey, function (Builder $query) {
$query->whereBelongsTo($this->election);
})
->limit(1000)
->pluck('name', 'id')
)
->options(function (Get $get) use ($whereHasKey) {
$county_id = $get('county');

return CacheService::make(['localities', $whereHasKey], $this->election, county: $county_id)
->remember(
fn () => Locality::query()
->where('county_id', $county_id)
->whereHas($whereHasKey, function (Builder $query) use ($county_id) {
$query->whereBelongsTo($this->election);

if ($county_id !== 403) {
$query->whereNull('parent_id');
}
})
->limit(150)
->pluck('name', 'id')
);
})
->visible(fn (Get $get) => DataLevel::isValue($get('level'), DataLevel::NATIONAL) &&
! \is_null($get('county')))
->searchable()
Expand Down
5 changes: 2 additions & 3 deletions app/Livewire/Pages/ElectionResults.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace App\Livewire\Pages;

use App\Enums\Time;
use App\Models\Candidate;
use App\Models\Party;
use App\Models\Vote;
Expand Down Expand Up @@ -34,7 +33,7 @@ public function render(): View
#[Computed]
public function parties(): Collection
{
return Cache::remember("parties:{$this->election->id}", Time::DAY_IN_SECONDS->value, function () {
return Cache::remember("parties:{$this->election->id}", now()->addDay(), function () {
return Party::query()
->whereBelongsTo($this->election)
// ->whereHas('votes', function (Builder $query) {
Expand All @@ -48,7 +47,7 @@ public function parties(): Collection
#[Computed]
public function candidates(): Collection
{
return Cache::remember("candidates:{$this->election->id}", Time::DAY_IN_SECONDS->value, function () {
return Cache::remember("candidates:{$this->election->id}", now()->addDay(), function () {
return Candidate::query()
->whereBelongsTo($this->election)
// ->whereHas('votes', function (Builder $query) {
Expand Down
16 changes: 10 additions & 6 deletions app/Livewire/VoteMonitorStats.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Models\Election;
use App\Models\VoteMonitorStat;
use App\Services\CacheService;
use Livewire\Attributes\Computed;
use Livewire\Component;

Expand All @@ -18,12 +19,15 @@ class VoteMonitorStats extends Component
#[Computed]
public function stats(): array
{
return VoteMonitorStat::query()
->whereBelongsTo($this->election)
->where('enabled', true)
->orderBy('order')
->get()
->toArray();
return CacheService::make('vote-monitor-stats', $this->election)
->remember(
fn () => VoteMonitorStat::query()
->whereBelongsTo($this->election)
->where('enabled', true)
->orderBy('order')
->get()
->toArray()
);
}

#[Computed]
Expand Down
9 changes: 9 additions & 0 deletions app/Models/Article.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Models;

use App\Concerns\BelongsToElection;
use App\Concerns\ClearsCache;
use App\Concerns\Publishable;
use App\Enums\User\Role;
use Database\Factories\ArticleFactory;
Expand All @@ -18,6 +19,7 @@

class Article extends Model implements HasMedia
{
use ClearsCache;
use HasFactory;
use BelongsToElection;
use InteractsWithMedia;
Expand Down Expand Up @@ -74,4 +76,11 @@ public function registerMediaCollections(): void
->optimize();
});
}

public function getCacheTags(): array
{
return [
"election:{$this->election_id}:articles",
];
}
}
9 changes: 9 additions & 0 deletions app/Models/Candidate.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Models;

use App\Concerns\BelongsToElection;
use App\Concerns\ClearsCache;
use App\Contracts\HasDisplayName;
use Database\Factories\CandidateFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
Expand All @@ -19,6 +20,7 @@
class Candidate extends Model implements HasMedia, HasDisplayName
{
use BelongsToElection;
use ClearsCache;
/** @use HasFactory<CandidateFactory> */
use HasFactory;
use InteractsWithMedia;
Expand Down Expand Up @@ -74,4 +76,11 @@ public function getDisplayName(): string
{
return $this->display_name ?? $this->name;
}

public function getCacheTags(): array
{
return [
"candidates:{$this->election_id}",
];
}
}
7 changes: 7 additions & 0 deletions app/Models/Election.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Models;

use App\Concerns\ClearsCache;
use App\Concerns\HasSlug;
use App\Enums\ElectionType;
use Database\Factories\ElectionFactory;
Expand All @@ -17,6 +18,7 @@

class Election extends Model implements HasName, HasAvatar
{
use ClearsCache;
/** @use HasFactory<ElectionFactory> */
use HasFactory;
use HasSlug;
Expand Down Expand Up @@ -127,4 +129,9 @@ public function getFilamentAvatarUrl(): ?string

return 'https://ui-avatars.com/api/?name=E';
}

public function getCacheTags(): array
{
return ['elections'];
}
}
18 changes: 18 additions & 0 deletions app/Models/Menu.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Models;

use App\Concerns\ClearsCache;
use Datlechin\FilamentMenuBuilder\Models\Menu as BaseMenu;

class Menu extends BaseMenu
{
use ClearsCache;

public function getCacheTags(): array
{
return ['menus'];
}
}
18 changes: 18 additions & 0 deletions app/Models/MenuItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Models;

use App\Concerns\ClearsCache;
use Datlechin\FilamentMenuBuilder\Models\MenuItem as BaseMenuItem;

class MenuItem extends BaseMenuItem
{
use ClearsCache;

public function getCacheTags(): array
{
return ['menus'];
}
}
18 changes: 18 additions & 0 deletions app/Models/MenuLocation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Models;

use App\Concerns\ClearsCache;
use Datlechin\FilamentMenuBuilder\Models\MenuLocation as BaseMenuLocation;

class MenuLocation extends BaseMenuLocation
{
use ClearsCache;

public function getCacheTags(): array
{
return ['menus'];
}
}
Loading

0 comments on commit 96867e3

Please sign in to comment.