Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Simple Config Laravel Package

bitscout/simple-config

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bitscout/simple-config
    

    Add to bundles.php:

    Bitscout\SimpleConfig\BitscoutSimpleConfigBundle::class => ['all' => true],
    
  2. Configuration Create config/packages/bitscout_simple_config.yaml:

    bitscout_simple_config:
      fields:
        site_name:
          label: "Site Name"
          type: string
          default: "My App"
          show: true
    

    This injects SIMPLE_CONFIG_SITE_NAME as an environment variable.

  3. Accessing Values Retrieve values via:

    $siteName = $_ENV['SIMPLE_CONFIG_SITE_NAME'] ?? config('bitscout_simple_config.fields.site_name.default');
    

    Or use Laravel’s config helper:

    $siteName = config('bitscout_simple_config.fields.site_name.default');
    
  4. Admin Integration Add a SonataAdmin menu entry in sonata_admin.yaml:

    menu:
      main:
        - { route: admin_app_bitscout_simple_config_list, label: 'Config', icon: '<i class="fa fa-cog"></i>' }
    

Implementation Patterns

Workflow: Dynamic Configuration Management

  1. Define Config Fields Use bitscout_simple_config.yaml to declare all configurable fields:

    bitscout_simple_config:
      fields:
        maintenance_mode:
          label: "Maintenance Mode"
          type: boolean
          default: false
        api_timeout:
          label: "API Timeout (seconds)"
          type: int
          default: 30
    
  2. Override Defaults via Admin

    • Users edit values in the SonataAdmin interface (route: admin_app_bitscout_simple_config_list).
    • Changes persist in the database (assuming the bundle implements storage).
  3. Runtime Access

    • Environment Variables: Prefer $_ENV['SIMPLE_CONFIG_KEY'] for runtime overrides.
    • Fallback to Config: Use config('bitscout_simple_config.fields.key.default') if env vars are missing.
    • Service Binding (Advanced): Bind a service to resolve config dynamically:
      $this->app->bind('config.resolver', function ($app) {
          return new ConfigResolver($app['config']);
      });
      
  4. Conditional Logic Use config values to drive feature flags or environment-specific behavior:

    if ($_ENV['SIMPLE_CONFIG_MAINTENANCE_MODE'] === 'true') {
        abort(503, 'Site under maintenance');
    }
    
  5. Validation Extend the bundle’s validation logic (if supported) or validate manually:

    $timeout = (int) ($_ENV['SIMPLE_CONFIG_API_TIMEOUT'] ?? 30);
    if ($timeout < 10 || $timeout > 60) {
        throw new \InvalidArgumentException('Timeout must be between 10 and 60 seconds.');
    }
    

Integration Tips

  • SonataAdmin Menu Grouping Organize config entries under a logical group (e.g., "Settings") by leveraging Sonata’s menu hierarchy.

  • Environment-Specific Overrides Use Laravel’s env() function to merge config with .env:

    $value = env('SIMPLE_CONFIG_CUSTOM_VAR', config('bitscout_simple_config.fields.custom_var.default'));
    
  • Caching Cache resolved config values if performance is critical:

    $cacheKey = 'config.site_name';
    $siteName = Cache::remember($cacheKey, now()->addHours(1), function () {
        return $_ENV['SIMPLE_CONFIG_SITE_NAME'] ?? config('bitscout_simple_config.fields.site_name.default');
    });
    
  • Testing Mock config values in tests:

    $_ENV['SIMPLE_CONFIG_TEST_MODE'] = 'true';
    $this->assertTrue($_ENV['SIMPLE_CONFIG_TEST_MODE']);
    

Gotchas and Tips

Pitfalls

  1. Bundle Incompleteness

    • The package is not fully implemented (as noted in the README). Expect missing features like:
      • Database storage for config values.
      • SonataAdmin CRUD operations (list/edit).
      • Validation or sanitization of user inputs.
    • Workaround: Manually implement a Config model/table and override the bundle’s behavior.
  2. Environment Variable Pollution

    • The bundle injects all config fields as env vars (SIMPLE_CONFIG_*), which may conflict with existing .env variables.
    • Tip: Prefix keys or use a naming convention (e.g., APP_SIMPLE_CONFIG_*).
  3. Type Safety

    • The type field (e.g., int, boolean) is not enforced by the bundle. User inputs may corrupt data.
    • Fix: Add validation in a custom SonataAdmin form type or middleware.
  4. Missing Documentation

    • No examples for:
      • Database schema or migrations.
      • Customizing the admin interface.
      • Handling nested config structures.
    • Tip: Inspect the source code (vendor/bitscout/simple-config) for clues.
  5. SonataAdmin Dependency

    • The bundle assumes SonataAdmin is installed. If not, the menu route (admin_app_bitscout_simple_config_list) will 404.
    • Solution: Implement a fallback admin interface or use a standalone route.

Debugging

  1. Check Config Loading Verify the YAML file is parsed correctly:

    php artisan config:clear
    php artisan config:cache
    

    Then dump the config:

    dd(config('bitscout_simple_config'));
    
  2. Environment Variable Conflicts If SIMPLE_CONFIG_* vars are ignored, check:

    • .env file for overrides.
    • Server environment (e.g., Apache/PHP-FPM settings).
  3. Admin Route Issues Ensure:

    • SonataAdmin is properly installed and configured.
    • The route is added to sonata_admin.yaml before the bundle tries to use it.

Extension Points

  1. Custom Storage Override the default storage (likely a simple array or file-based) by extending the bundle’s ConfigManager:

    // config/packages/bitscout_simple_config.php
    return [
        'storage' => [
            'driver' => 'database',
            'table' => 'simple_config',
        ],
    ];
    
  2. Add Validation Extend the SonataAdmin form type to add validation rules:

    // src/Form/Type/ConfigType.php
    use Symfony\Component\Validator\Constraints as Assert;
    
    $builder->add('value', TextType::class, [
        'constraints' => [
            new Assert\Type(['type' => 'numeric']),
            new Assert\Range(['min' => 1, 'max' => 100]),
        ],
    ]);
    
  3. Event Listeners Listen for config changes to trigger actions (e.g., cache clearing):

    // EventSubscriber
    public function onConfigUpdate(ConfigUpdateEvent $event)
    {
        Cache::clear();
    }
    
  4. Localization Support multi-language labels by extending the config structure:

    bitscout_simple_config:
      fields:
        site_name:
          label:
            en: "Site Name"
            fr: "Nom du Site"
    

    Then resolve dynamically:

    $label = config("bitscout_simple_config.fields.site_name.label.{$app->getLocale()}");
    

Pro Tips

  • Use for Non-Critical Settings Since the bundle is unfinished, limit its use to low-risk configurations (e.g., feature toggles, non-sensitive defaults).

  • Fallback to Database If the bundle lacks database storage, implement a simple config_values table:

    // Migration
    Schema::create('config_values', function (Blueprint $table) {
        $table->string('key')->unique();
        $table->text('value')->nullable();
        $table->timestamps();
    });
    
  • Combine with Laravel Config Merge SimpleConfig with Laravel’s native config for a unified approach:

    # config/app.php
    'site' => [
        'name' => env('SIMPLE_CONFIG_SITE_NAME', config('bitscout_simple_config.fields.site_name.default')),
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware