Browse Source

Merge pull request #267 from ControlPanel-gg/configuration_options_caching

Caching configuration options
AVMG 3 years ago
parent
commit
0039950a01
2 changed files with 18 additions and 3 deletions
  1. 1 0
      .gitignore
  2. 17 3
      app/Models/Configuration.php

+ 1 - 0
.gitignore

@@ -4,6 +4,7 @@
 /storage/*.key
 /vendor
 /storage/credit_deduction_log
+storage/debugbar
 .env
 .env.testing
 .env.backup

+ 17 - 3
app/Models/Configuration.php

@@ -4,11 +4,14 @@ namespace App\Models;
 
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Cache;
 
 class Configuration extends Model
 {
     use HasFactory;
 
+    public const CACHE_TAG = 'configuration';
+
     public $primaryKey = 'key';
 
     public $incrementing = false;
@@ -21,14 +24,25 @@ class Configuration extends Model
         'type',
     ];
 
+    public static function boot()
+    {
+        parent::boot();
+
+        static::updated(function (Configuration $configuration) {
+            Cache::forget(self::CACHE_TAG .':'. $configuration->key);
+        });
+    }
+
     /**
      * @param string $key
      * @param $default
      * @return mixed
      */
-    public static function getValueByKey(string $key , $default = null)
+    public static function getValueByKey(string $key, $default = null)
     {
-        $configuration = self::find($key);
-        return $configuration ? $configuration->value : $default;
+        return Cache::rememberForever(self::CACHE_TAG .':'. $key, function () use ($default, $key) {
+            $configuration = self::find($key);
+            return $configuration ? $configuration->value : $default;
+        });
     }
 }