Easy Config / Settings save and read class with caching PHP/Laravel

 

 

Photo by Emile Perron on Unsplash  

 

Commonly most web applications require save configs and settings . there are many ways and methods to save and retrieve configs and settings. today i will share with you my method to save and retrieve settings data in laravel application.

 

Create migration and and Model

php artisan make:model Settings -m


in your migration file: add these fields:

public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key');
$table->string('value');
$table->unsignedBigInteger('updated_user')->nullable();
$table->timestamps();
});
}

use 'updated_user' to track who changed value last time.

you can also use 'text' or any suitable type to 'value' field I used string(varchar255) here.


DB Model class

<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class Settings extends Model
{
//Make fillable all fields except id
protected $guarded = ['id'];
}


Settings service

<?php

namespace App\Classes;
// your namespace. you can change it to your related namespace.

use Illuminate\Support\Facades\Cache;
use App\Models\Settings;

class SettingsService
{
public const CACHED_TIME = 60 * 60 * 24; //cache time day
//key prefix for cache retrive not mandetory
const KEY_PRFX = "settings.";

/** set setting value */

public static function setVal($key, $value)
{
Cache::forget(self::KEY_PRFX . $key);

return Settings::updateOrCreate(
[
'key' => $key,
],
[
'value' => $value,
'updated_user' => auth()->id() ?? null
]
);
}


/** get setting value */
public static function getVal($key, $default_value = null, $cached = true)
{
//create a function so its easy to inject to cache method
$readValFunc = function () use ($key, $default_value) {
$seting = Settings::where('key', $key)->first();
return data_get($seting, 'value', $default_value);
};


//check is cached value or current value
if ($cached) {
return self::cached($key, $readValFunc);
}

return $readValFunc();
}


/** cache the setting value */
private static function cached($key, callable $func)
{
return Cache::remember(self::KEY_PRFX . $key, self::CACHED_TIME, $func);
}
}



You can now use just importing class to any controller or any class, but let make more easy accessing by registering to app container

Registering class

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Classes\SettingsService;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
        
$this->app->singleton('Settings', function($app) {
return new SettingsService();
});
}
}


in your app service provider file, just import class, and add singleton service to boot function. 

now clear class cached data using

php artisan optimize:clear

(if class not registered try running also composer dump-autoload)


now we can use like bellow


//set value
app('Settings')->setVal('your_settings.key', 'value');
//get value
app('Settings')->getVal('your_settings.key', 'default_value');
 

that it :D . thanks for reading!.  if you found any mistakes please comment.

 



Comments

Popular posts from this blog

How to use Spatie packages to enhance your Laravel development experience

Handling undefined variables in laravel

Some Briefs of Data Mining