teknyo/laravel-settings-manager
Composer 安装命令:
composer require teknyo/laravel-settings-manager
包简介
Easily manage app settings stored in DB or JSON file
README 文档
README
A simple, elegant, and powerful settings manager for Laravel applications. Store and retrieve application settings from database or JSON file with built-in caching support.
✨ Features
- 🗄️ Multiple Storage Drivers: Database or JSON file storage
- ⚡ Built-in Caching: Automatic caching layer for performance
- 🔄 Automatic Serialization: Store arrays, objects, and primitives
- 🎨 Clean API: Simple and intuitive
Setting::get()andSetting::set()methods - 🛠️ Artisan Commands: Manage settings from command line
- 📦 Batch Operations: Set or delete multiple settings at once
- 🔒 Type-Safe: Full type hints and return types
- 🚀 Laravel 10 & 11: Compatible with latest Laravel versions
📋 Requirements
- PHP 8.1 or higher
- Laravel 10.x or 11.x
📦 Installation
Install the package via Composer:
composer require yourvendor/laravel-settings
Publish Configuration
Publish the configuration file:
php artisan vendor:publish --tag=settings-config
Setup Database Driver
If using the database driver, publish and run migrations:
php artisan vendor:publish --tag=settings-migrations php artisan migrate
⚙️ Configuration
The configuration file will be published to config/settings.php:
return [ // Storage driver: 'database' or 'json' 'driver' => env('SETTINGS_DRIVER', 'database'), // Database driver settings 'database' => [ 'connection' => env('DB_CONNECTION', 'mysql'), 'table' => 'settings', ], // JSON driver settings 'json' => [ 'path' => 'app/settings.json', ], // Cache settings 'cache' => [ 'enabled' => true, 'store' => env('CACHE_DRIVER', 'file'), 'prefix' => 'settings', ], ];
Environment Variables
Add to your .env file:
SETTINGS_DRIVER=database # or 'json'
🚀 Usage
Basic Operations
use YourVendor\Settings\Facades\Setting; // Set a setting Setting::set('site_name', 'My Awesome Website'); Setting::set('timezone', 'Asia/Colombo'); Setting::set('maintenance_mode', false); // Get a setting $siteName = Setting::get('site_name'); // Returns: 'My Awesome Website' // Get with default value $theme = Setting::get('theme', 'light'); // Returns: 'light' if 'theme' doesn't exist // Check if setting exists if (Setting::has('site_name')) { echo 'Site name is configured'; } // Delete a setting Setting::forget('old_setting');
Working with Arrays and Objects
The package automatically serializes complex data types:
// Store arrays Setting::set('features', [ 'dark_mode' => true, 'api_enabled' => false, 'max_upload_size' => 10, ]); // Retrieve arrays $features = Setting::get('features'); // Returns: ['dark_mode' => true, 'api_enabled' => false, 'max_upload_size' => 10] // Store objects Setting::set('email_config', [ 'driver' => 'smtp', 'host' => 'smtp.mailtrap.io', 'port' => 587, ]);
Batch Operations
// Set multiple settings at once Setting::setMany([ 'app_name' => 'MyApp', 'app_version' => '1.0.0', 'maintenance_mode' => false, 'items_per_page' => 20, ]); // Delete multiple settings Setting::forgetMany(['temp_key1', 'temp_key2', 'cache_key']); // Get all settings $allSettings = Setting::all(); // Returns: ['site_name' => 'My Site', 'timezone' => 'UTC', ...] // Clear all settings (use with caution!) Setting::clear();
🎯 Artisan Commands
Manage settings from the command line:
Get a Setting
php artisan setting:get site_name # Output: Value for 'site_name': "My Awesome Website" # With default value php artisan setting:get theme --default=light
Set a Setting
# Simple value php artisan setting:set site_name "My New Site Name" # Boolean php artisan setting:set maintenance_mode false # JSON value php artisan setting:set features '{"dark_mode":true,"notifications":false}' # Number php artisan setting:set max_users 1000
List All Settings
php artisan setting:list
Output:
+-------------------+--------------------------------+
| Key | Value |
+-------------------+--------------------------------+
| site_name | "My Awesome Website" |
| timezone | "Asia/Colombo" |
| maintenance_mode | false |
| features | {"dark_mode":true} |
+-------------------+--------------------------------+
Clear All Settings
php artisan setting:clear
# Skip confirmation
php artisan setting:clear --force
💡 Real-World Examples
Application Configuration
// In your AppServiceProvider public function boot() { config(['app.timezone' => Setting::get('timezone', 'UTC')]); config(['app.name' => Setting::get('site_name', 'Laravel')]); }
Feature Flags
if (Setting::get('features.new_dashboard', false)) { return view('dashboard.new'); } return view('dashboard.old');
Maintenance Mode
// Middleware public function handle($request, Closure $next) { if (Setting::get('maintenance_mode', false)) { return response()->view('maintenance', [], 503); } return $next($request); }
User Preferences
class UserSettingsController { public function update(Request $request) { $userId = auth()->id(); Setting::setMany([ "user.{$userId}.theme" => $request->theme, "user.{$userId}.language" => $request->language, "user.{$userId}.notifications" => $request->notifications, ]); return back()->with('success', 'Settings updated!'); } }
API Rate Limiting
$rateLimit = Setting::get('api.rate_limit', 60); $rateLimitWindow = Setting::get('api.rate_limit_window', 1); RateLimiter::for('api', function (Request $request) use ($rateLimit, $rateLimitWindow) { return Limit::perMinutes($rateLimitWindow, $rateLimit); });
🔧 Advanced Usage
Custom Storage Location (JSON Driver)
// config/settings.php 'json' => [ 'path' => 'custom/path/settings.json', ],
Disable Caching
// config/settings.php 'cache' => [ 'enabled' => false, ],
Custom Cache Store
// config/settings.php 'cache' => [ 'enabled' => true, 'store' => 'redis', // Use Redis for caching 'prefix' => 'app_settings', ],
Multiple Database Connections
// config/settings.php 'database' => [ 'connection' => 'settings_db', // Use separate connection 'table' => 'app_settings', ],
🏗️ Architecture
Storage Drivers
Database Driver: Stores settings in a database table with automatic JSON serialization.
JSON Driver: Stores settings in a JSON file with file locking for concurrent access.
Caching Layer
The CachedRepository wraps any storage driver and provides transparent caching:
- Cache hits avoid database/file queries
- Automatic cache invalidation on updates
- Configurable TTL (default: 1 hour)
- Supports any Laravel cache driver
📊 Performance
- Caching: First access queries storage, subsequent accesses use cache
- Batch Operations: Use
setMany()for multiple settings (single transaction) - JSON Driver: Single file read loads all settings into memory
- Database Driver: Indexed key column for fast lookups
📝 License
This package is open-sourced software licensed under the MIT license.
🐛 Support
If you discover any security vulnerabilities or bugs, please email info@teknyo.lk.
For general questions and support, please open an issue on GitHub.
📚 Changelog
Please see CHANGELOG for more information on what has changed recently.
🗺️ Roadmap
- Setting groups/namespaces
- Setting validation rules
- Web UI for managing settings
- Import/Export functionality
- Setting encryption for sensitive data
- Audit log for setting changes
- Setting versioning/history
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-01