M1: 数据模型 + sablog:import 脚本(MySQL 8 验证通过,不迁移 trackback 等过时功能)
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class Setting extends Model
|
||||
{
|
||||
protected $primaryKey = 'key';
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $fillable = ['key', 'value'];
|
||||
|
||||
public const CACHE_KEY = 'blog.settings';
|
||||
|
||||
public static function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$settings = self::allSettings();
|
||||
|
||||
return $settings[$key] ?? $default;
|
||||
}
|
||||
|
||||
public static function set(string $key, mixed $value): void
|
||||
{
|
||||
self::updateOrCreate(['key' => $key], ['value' => is_scalar($value) || $value === null ? $value : json_encode($value)]);
|
||||
self::flushCache();
|
||||
}
|
||||
|
||||
public static function forget(string $key): void
|
||||
{
|
||||
self::where('key', $key)->delete();
|
||||
self::flushCache();
|
||||
}
|
||||
|
||||
public static function allSettings(): array
|
||||
{
|
||||
return Cache::remember(self::CACHE_KEY, now()->addDay(), function () {
|
||||
return self::query()->pluck('value', 'key')->all();
|
||||
});
|
||||
}
|
||||
|
||||
public static function flushCache(): void
|
||||
{
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
}
|
||||
|
||||
public static function seedDefaults(array $defaults): void
|
||||
{
|
||||
foreach ($defaults as $key => $value) {
|
||||
if (! self::query()->where('key', $key)->exists()) {
|
||||
self::query()->create(['key' => $key, 'value' => $value]);
|
||||
}
|
||||
}
|
||||
self::flushCache();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user