定制 mohanad/laravel-config-switcher 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mohanad/laravel-config-switcher

Composer 安装命令:

composer require mohanad/laravel-config-switcher

包简介

A Laravel package for managing configuration and environment settings with snapshot/rollback functionality

README 文档

README

A powerful Laravel package for managing configuration and environment settings with snapshot/rollback functionality. This package provides a secure admin panel to manage your Laravel application's configuration files and environment variables with the ability to create snapshots and rollback to previous states.

Features

  • 🔧 Environment Management: Safely update .env file variables through a web interface
  • 📁 Config File Management: Manage Laravel configuration files with validation
  • 📸 Snapshot System: Create snapshots of your current configuration state
  • 🔄 Rollback Functionality: Restore your configuration to any previous snapshot
  • 🔒 Security Features: IP restrictions, user authentication, and validation rules
  • 🎨 Modern UI: Beautiful, responsive admin panel built with Tailwind CSS
  • Artisan Commands: CLI commands for snapshot management
  • 🧪 Comprehensive Testing: Full test coverage with PHPUnit

How It Works

🏗️ Architecture Overview

The Laravel Config Switcher package follows a clean, layered architecture that integrates seamlessly with Laravel:

User Request → Routes → Controller → Service → Database/File System
     ↑                                                      ↓
Admin Panel ← Views ← Response ← Controller ← Service ← Result

🔧 Core Components & Their Roles

Service Provider (ConfigSwitcherServiceProvider)

  • Purpose: Registers the package with Laravel and bootstraps all components
  • When it runs: Every time Laravel boots up
  • Key functions:
    • Binds services to the Laravel container
    • Loads migrations, views, and routes
    • Registers Artisan commands
    • Publishes configuration files
// Automatically discovered by Laravel
'providers' => [
    "Mohanad\\ConfigSwitcher\\ConfigSwitcherServiceProvider"
]

ConfigManager Service

  • Purpose: Manages environment variables and configuration files
  • Key methods:
    • getEnvConfig() - Reads and parses .env file
    • updateEnvConfig() - Updates .env file safely with validation
    • getConfigValues() - Reads Laravel configuration files
    • getCurrentState() - Creates backup of current configuration state
    • restoreFromState() - Restores configuration from saved state

SnapshotManager Service

  • Purpose: Handles configuration snapshots and rollback functionality
  • Key methods:
    • createSnapshot() - Saves current configuration state to database
    • restoreSnapshot() - Restores configuration to any previous state
    • compareWithSnapshot() - Shows differences between current and saved states
    • cleanupOldSnapshots() - Manages storage by removing old snapshots

🔄 How It Works in Practice

Snapshot Creation Process

  1. User Action: User clicks "Create Snapshot" in admin panel
  2. Request Processing: Controller receives the request and validates input
  3. State Capture: SnapshotManager.createSnapshot() calls ConfigManager.getCurrentState()
  4. Data Collection: System reads current .env file and configuration files
  5. State Assembly: Combines all configuration data into a structured array
  6. Database Storage: Saves the complete state to config_snapshots table
  7. Response: Returns success confirmation to user

Configuration Update Process

  1. User Input: User edits configuration values in admin panel
  2. Validation: Controller validates all input using custom validation rules
  3. File Reading: ConfigManager.updateEnvConfig() reads current .env file
  4. Parsing: Parses file into key-value pairs
  5. Updating: Applies new values while preserving file structure
  6. File Writing: Writes updated configuration back to .env file
  7. Response: Returns success/error status to user

Rollback Process

  1. User Selection: User chooses a snapshot to restore
  2. Confirmation: System asks for confirmation (can be bypassed with --force flag)
  3. Data Retrieval: SnapshotManager.restoreSnapshot() retrieves snapshot data
  4. State Restoration: ConfigManager.restoreFromState() applies saved configuration
  5. File Updates: Updates .env and configuration files with restored values
  6. Verification: System confirms successful restoration

🛡️ Security & Safety Features

Built-in Protections

  • Input Validation: All inputs are validated using Laravel's validation system
  • Automatic Backups: Creates snapshots before making any changes
  • Rollback Capability: Can restore to any previous state instantly
  • IP Restrictions: Limit access to specific IP addresses
  • User Authentication: Require login for access to configuration
  • File Permissions: Safe file operations with proper error handling

Configuration Security

// In config/config-switcher.php
'security' => [
    'allowed_ips' => ['192.168.1.100'], // Only allow specific IPs
    'require_authentication' => true,    // Require login
    'allowed_users' => ['admin@example.com'], // Restrict to specific users
]

📊 Database Schema

Snapshots Table Structure

CREATE TABLE config_snapshots (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    description TEXT NULL,
    config_data LONGTEXT NOT NULL, -- JSON encoded config state
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
);

Configuration State Structure

The config_data field stores the complete configuration state as JSON:

{
    "env": {
        "APP_NAME": "Laravel",
        "APP_ENV": "production",
        "DB_CONNECTION": "mysql",
        "DB_HOST": "127.0.0.1"
    },
    "config": {
        "app": {
            "name": "Laravel",
            "env": "production",
            "debug": false
        },
        "database": {
            "default": "mysql",
            "connections": {
                "mysql": {
                    "driver": "mysql",
                    "host": "127.0.0.1"
                }
            }
        }
    },
    "timestamp": "2024-01-01T12:00:00Z"
}

🔌 Integration with Laravel

Auto-Discovery

Laravel automatically finds and loads your package because of:

  • Service provider registration in composer.json
  • Proper namespace structure following PSR-4
  • Laravel package conventions and standards

Service Container Binding

// Automatically available throughout your Laravel application
$configManager = app(ConfigManager::class);
$snapshotManager = app(SnapshotManager::class);

// Or use dependency injection
public function __construct(
    private ConfigManager $configManager,
    private SnapshotManager $snapshotManager
) {}

🚨 Error Handling & Recovery

Exception Types

  • ConfigFileNotFoundException: When configuration files are missing
  • InvalidConfigException: When configuration values fail validation
  • SnapshotNotFoundException: When requested snapshot doesn't exist
  • SnapshotCreationException: When snapshot creation fails

Recovery Process

try {
    $configManager->updateEnvConfig($newConfig);
} catch (ConfigFileNotFoundException $e) {
    // Handle missing .env file
    Log::error('Environment file not found: ' . $e->getMessage());
} catch (InvalidConfigException $e) {
    // Handle invalid configuration values
    Log::error('Invalid configuration: ' . $e->getMessage());
} catch (\Exception $e) {
    // Handle other unexpected errors
    Log::error('Configuration update failed: ' . $e->getMessage());
}

Performance & Scalability

Optimizations

  • Lazy Loading: Services only load when needed
  • Efficient Queries: Database queries are optimized with proper indexing
  • Memory Management: Large configurations are handled efficiently
  • Caching: Configuration values are cached when appropriate

Database Indexing

-- Optimized queries with proper indexing
CREATE INDEX idx_config_snapshots_name ON config_snapshots(name);
CREATE INDEX idx_config_snapshots_created_at ON config_snapshots(created_at);

🎯 Use Cases & Scenarios

Production Environment Management

  1. Before Deployment: Create snapshot of current configuration
  2. Update Configuration: Change environment variables for new release
  3. Testing: Verify everything works with new configuration
  4. Rollback if Needed: Instantly restore previous working state

Development Workflow

  1. Local Changes: Test configuration changes in development
  2. Create Snapshot: Save working configuration state
  3. Experiment: Try different configuration combinations
  4. Restore: Go back to working state if experiments fail

Team Collaboration

  1. Configuration Sharing: Share working configurations with team
  2. Version Control: Track configuration changes over time
  3. Audit Trail: See who changed what and when
  4. Compliance: Maintain configuration history for audits

🔄 Data Flow Examples

Creating a Snapshot

graph TD
    A[User clicks 'Create Snapshot'] --> B[Controller receives request]
    B --> C[Validate input: name, description]
    C --> D[SnapshotManager.createSnapshot()]
    D --> E[ConfigManager.getCurrentState()]
    E --> F[Read .env file]
    E --> G[Read config files]
    F --> H[Parse environment variables]
    G --> I[Parse configuration arrays]
    H --> J[Combine into state array]
    I --> J
    J --> K[Save to database]
    K --> L[Return success response]
Loading

Updating Configuration

graph TD
    A[User edits config values] --> B[Controller validates input]
    B --> C[ConfigManager.updateEnvConfig()]
    C --> D[Read current .env file]
    D --> E[Parse into key-value pairs]
    E --> F[Apply new values]
    F --> G[Validate final configuration]
    G --> H[Write back to .env file]
    H --> I[Return success/error response]
Loading

🎉 Key Benefits

Safe: Never lose your configuration - always have rollback capability
Fast: Quick configuration updates and instant rollbacks
Secure: Built-in security features and validation
Flexible: Web interface + CLI commands + RESTful API
Reliable: Comprehensive error handling and recovery
Scalable: Works with applications of any size
Maintainable: Clean, SOLID architecture following Laravel standards

This package essentially gives you "Git for your configuration" - you can track changes, create branches (snapshots), and rollback to any previous state, all through a beautiful web interface or powerful command line tools! 🚀

Installation

You can install the package via Composer:

composer require mohanad/laravel-config-switcher

Publish Configuration

php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="config"

Run Migrations

php artisan migrate

Publish Views (Optional)

php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="views"

Configuration

After publishing the configuration file, you can customize the package behavior in config/config-switcher.php:

return [
    'table_name' => 'config_snapshots',
    
    'routes' => [
        'prefix' => 'config-switcher',
        'middleware' => ['web'],
    ],
    
    'security' => [
        'allowed_ips' => [], // Empty array means all IPs are allowed
        'allowed_users' => [], // Empty array means all authenticated users
        'require_authentication' => false,
    ],
    
    'validation' => [
        'env' => [
            'APP_ENV' => '/^(local|staging|production)$/',
            'APP_DEBUG' => '/^(true|false)$/',
            'DB_CONNECTION' => '/^(mysql|pgsql|sqlite|sqlsrv)$/',
        ],
    ],
    
    'snapshots' => [
        'max_snapshots' => 50,
        'auto_cleanup' => true,
        'cleanup_threshold' => 10,
    ],
];

Usage

Web Interface

Access the admin panel at /config-switcher (or your configured prefix).

Environment Variables

  • View and edit all environment variables from your .env file
  • Real-time validation with custom rules
  • Safe updates with backup functionality

Configuration Files

  • Browse and edit Laravel configuration files
  • Syntax highlighting and validation
  • File-specific settings management

Snapshots

  • Create snapshots of your current configuration
  • Restore to any previous snapshot
  • Compare differences between snapshots
  • Automatic cleanup of old snapshots

Artisan Commands

Create a Snapshot

php artisan config:snapshot "Before Production Deploy" --description="Snapshot before deploying to production"

List Snapshots

php artisan config:snapshots --limit=20

Rollback to Snapshot

php artisan config:rollback 5 --force

Security

IP Restrictions

Configure allowed IP addresses in your config file:

'security' => [
    'allowed_ips' => ['192.168.1.100', '10.0.0.50'],
],

User Authentication

Require authentication and restrict to specific users:

'security' => [
    'require_authentication' => true,
    'allowed_users' => [1, 2, 'admin@example.com'],
],

Validation Rules

Define custom validation rules for environment variables:

'validation' => [
    'env' => [
        'APP_ENV' => '/^(local|staging|production)$/',
        'CUSTOM_VAR' => function($value) {
            return strlen($value) >= 8;
        },
    ],
],

API Endpoints

The package provides RESTful API endpoints for programmatic access:

Environment Configuration

POST /config-switcher/env/update
Content-Type: application/json

{
    "config": {
        "APP_NAME": "My App",
        "APP_ENV": "production"
    }
}

Snapshots

# Create snapshot
POST /config-switcher/snapshots
{
    "name": "Production Backup",
    "description": "Backup before major changes"
}

# Get all snapshots
GET /config-switcher/snapshots

# Restore snapshot
POST /config-switcher/snapshots/restore
{
    "id": 5
}

# Delete snapshot
DELETE /config-switcher/snapshots
{
    "id": 5
}

Advanced Usage

Programmatic Access

use Mohanad\ConfigSwitcher\Services\ConfigManager;
use Mohanad\ConfigSwitcher\Services\SnapshotManager;

// Get config manager
$configManager = app(ConfigManager::class);

// Update environment variables
$configManager->updateEnvConfig([
    'APP_NAME' => 'New App Name',
    'APP_ENV' => 'production'
]);

// Create snapshot
$snapshotManager = app(SnapshotManager::class);
$snapshot = $snapshotManager->createSnapshot('API Backup', 'Created via API');

// Restore snapshot
$snapshotManager->restoreSnapshot($snapshot->id);

Custom Validation

use Mohanad\ConfigSwitcher\Services\ConfigManager;

$configManager = app(ConfigManager::class);

$rules = [
    'APP_ENV' => '/^(local|staging|production)$/',
    'DB_PASSWORD' => function($value) {
        return strlen($value) >= 12 && preg_match('/[A-Za-z0-9@#$%^&+=]/', $value);
    },
];

$configManager->validateConfig($config, $rules);

Testing

Run the test suite:

composer test

The package includes comprehensive tests for:

  • Configuration management
  • Snapshot functionality
  • API endpoints
  • Validation rules
  • Security features

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Security Vulnerabilities

If you discover a security vulnerability, please send an e-mail to mohanad@example.com. All security vulnerabilities will be promptly addressed.

License

This package is open-sourced software licensed under the MIT license.

Changelog

1.0.0

  • Initial release
  • Environment variable management
  • Configuration file management
  • Snapshot and rollback functionality
  • Web admin panel
  • Artisan commands
  • Security features
  • Comprehensive testing

Support

For support, please open an issue on GitHub or contact mohanad@example.com.

Note: This package is designed for development and staging environments. Use with caution in production environments and always backup your configuration before making changes.

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-03