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

Config Bundle Laravel Package

dhorchler/config-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dhorchler/config-bundle:dev-master
    

    Update AppKernel.php to include the bundle:

    new DHorchler\ConfigBundle\DHorchlerConfigBundle(),
    
  2. Database Setup: Run migrations to create the config table:

    php app/console doctrine:migrations:diff
    php app/console doctrine:migrations:migrate
    
  3. Configure Sonata Admin: Add the bundle to sonata_block configuration in config.yml:

    sonata_block:
        blocks:
            dhorchler_config.admin_block_config:
                contexts: [admin]
    
  4. First Use Case: Define a config entry via Sonata Admin UI:

    • Navigate to the admin panel (e.g., /admin/config).
    • Create a new config entry (e.g., site_name, type string).
    • Retrieve it in code:
      $siteName = $this->get('dhorchler_config.manager')->get('site_name');
      

Implementation Patterns

Workflows

  1. Defining Configs: Use Sonata Admin to create configs with:

    • Key: Unique identifier (e.g., max_upload_size).
    • Type: Supported types (string, integer, choice, etc.).
    • Default Value: Fallback if no value is set.
    • Validation: Custom constraints (e.g., min/max for integers).
  2. Retrieving Values: Inject the DHorchler\ConfigBundle\Manager\ConfigManager service:

    $value = $this->get('dhorchler_config.manager')->get('key');
    

    Use in templates:

    {{ app.config.get('key') }}
    
  3. Updating Values:

    • Runtime: Modify via Sonata Admin (no code changes).
    • Code: Use the manager:
      $this->get('dhorchler_config.manager')->set('key', 'new_value');
      
  4. Validation: Define rules in Sonata Admin (e.g., min/max for integer types). Errors are customizable via YAML:

    constraints:
        - NotBlank: { message: "This value is required" }
        - Range: { min: 1, max: 100, message: "Must be between 1 and 100" }
    
  5. Default Values: Set defaults in the Sonata Admin form. Override globally in config.yml:

    dhorchler_config:
        defaults:
            site_name: "My App"
    

Integration Tips

  • Caching: Cache retrieved values if performance is critical:
    $value = $this->get('dhorchler_config.manager')->get('key', ['cache' => true]);
    
  • Environment-Specific Configs: Use Symfony’s parameter system to seed initial values:
    # app/config/parameters.yml
    parameters:
        dhorchler_config.seed:
            site_name: "%env(SITE_NAME)%"
    
  • Events: Listen for config updates (e.g., clear cache):
    $dispatcher->addListener('dhorchler_config.update', function() {
        $this->get('cache')->clear();
    });
    

Gotchas and Tips

Pitfalls

  1. Bundle Maturity:

    • The package is Symfony 2.5-only and lacks Laravel compatibility. For Laravel, consider alternatives like:
    • Workaround: Use this bundle in a Symfony microservice alongside Laravel via API calls.
  2. Sonata Admin Dependency:

    • Requires Sonata Admin to be installed and configured. If you’re not using Sonata, this bundle is not viable.
    • Alternative: Use Laravel’s built-in config() system or packages like spatie/laravel-settings.
  3. Migration Issues:

    • The doctrine:migrations:diff step may fail if the config table already exists. Manually check the schema:
      php app/console doctrine:schema:update --dump-sql
      
  4. Type-Specific Quirks:

    • Choice/MultipleChoice: Values must match the defined options exactly (case-sensitive).
    • Date/Datetime: Uses Symfony’s DateType/DateTimeType; ensure your Doctrine entities are compatible.
  5. Caching Conflicts:

    • Runtime updates won’t reflect in cached views until the cache is cleared. Use events or tags:
      $this->get('dhorchler_config.manager')->set('key', 'value', ['cache_tag' => 'config']);
      

Debugging

  1. Missing Configs:

    • Verify the key exists in the database (config table). Use:
      php app/console doctrine:query:sql "SELECT * FROM config"
      
    • Check for typos in the key when retrieving.
  2. Validation Errors:

    • Sonata Admin logs validation errors in the browser console. Inspect the network tab for failed requests.
    • Override error messages in the config definition YAML.
  3. Permission Issues:

    • Ensure the Sonata Admin user has edit access to the Config admin class. Check sonata_admin.security.handler in config.yml.

Extension Points

  1. Custom Data Types: Extend the bundle by creating a new Type class (e.g., BooleanType) and register it in the bundle’s services:

    # DHorchlerConfigBundle/Resources/config/services.yml
    services:
        dhorchler_config.type.boolean:
            class: AppBundle\Type\BooleanType
            tags:
                - { name: dhorchler_config.type }
    
  2. Custom Admin Fields: Override the Sonata Admin form type for the Config entity:

    // src/AppBundle/Admin/ConfigAdmin.php
    class ConfigAdmin extends Admin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper->add('value', 'your_custom_field_type');
        }
    }
    
  3. Event Listeners: Subscribe to config update events to trigger side effects (e.g., log changes):

    // src/AppBundle/EventListener/ConfigListener.php
    class ConfigListener
    {
        public function onConfigUpdate(ConfigUpdateEvent $event)
        {
            \Log::info("Config updated: {$event->getKey()}");
        }
    }
    

    Register the listener in services.yml:

    services:
        app.config_listener:
            class: AppBundle\EventListener\ConfigListener
            tags:
                - { name: kernel.event_listener, event: dhorchler_config.update }
    
  4. Laravel Adaptation: If you must use this in Laravel, create a facade to wrap the Symfony manager:

    // app/Facades/ConfigFacade.php
    class ConfigFacade extends Facade
    {
        protected static function getFacadeAccessor() { return 'dhorchler_config.manager'; }
    }
    

    Register the Symfony container as a Laravel service provider (advanced).

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui