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

Configuration Bundle Laravel Package

dwcasteam/configuration-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dwcasteam/configuration-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Dwcasteam\ConfigurationBundle\DwcasteamConfigurationBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Define a configuration file (e.g., config/my_app.php) with a structured array:

    return [
        'key' => 'value',
        'nested' => [
            'subkey' => 'subvalue',
        ],
    ];
    
  3. First Use Case Access configuration in a controller/service:

    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class MyController
    {
        public function __construct(private ParameterBagInterface $params)
        {
        }
    
        public function index()
        {
            $value = $this->params->get('my_app.key');
            // Outputs: 'value'
        }
    }
    

Implementation Patterns

1. Configuration Hierarchy & Overrides

  • Environment-Specific Configs: Use %kernel.environment% to load different configs:

    # config/packages/my_app.yaml
    imports:
        - { resource: "@MyAppConfigBundle/Resources/config/config_${env}.php" }
    

    Example: config/config_dev.php overrides config/config_prod.php.

  • Parameter Bag Integration:

    $this->params->has('my_app.nested.subkey'); // Check existence
    $this->params->get('my_app', []); // Get entire section
    

2. Dynamic Configuration Loading

  • Runtime Configuration Updates: Use ParameterBagInterface to modify values dynamically (e.g., via API):

    $this->params->set('my_app.runtime_key', 'new_value');
    
  • Merge Configs: Combine multiple config files in a service:

    use Symfony\Component\Config\Loader\LoaderInterface;
    
    class ConfigMergerService
    {
        public function merge(array $configs): array
        {
            return array_replace_recursive(...$configs);
        }
    }
    

3. Dependency Injection (DI) Integration

  • Typed Config Services: Bind config to a service for type safety:

    # config/services.yaml
    services:
        App\Service\MyService:
            arguments:
                $config: '%my_app%'
    
  • Autowiring with Attributes:

    use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
    
    #[Autoconfigure(tag: 'my_app.config')]
    class MyService
    {
        public function __construct(private array $config) {}
    }
    

4. Validation & Defaults

  • Schema Validation: Use Symfony’s Validator to validate configs:

    use Symfony\Component\Validator\Validator\ValidatorInterface;
    
    $errors = $validator->validate($config, [
        new Assert\Collection([
            'key' => new Assert\NotBlank(),
            'nested' => new Assert\All([
                new Assert\Type('array'),
            ]),
        ]),
    ]);
    
  • Fallback Defaults:

    $value = $this->params->get('my_app.optional_key', 'default_value');
    

Gotchas and Tips

Pitfalls

  1. Caching Issues:

    • Config changes may not reflect immediately due to Symfony’s cache. Clear cache after updates:
      php bin/console cache:clear
      
    • Use dumpenv to force environment reloads in development.
  2. Parameter Bag Immutability:

    • ParameterBagInterface is immutable by default. Use ParameterBag (not ParameterBagInterface) for runtime modifications:
      $params = new ParameterBag($this->params->all());
      $params->set('key', 'new_value');
      
  3. Circular Imports:

    • Avoid circular references in imports (e.g., config_a.yaml importing config_b.yaml, which imports config_a.yaml). Use absolute paths or guard clauses.
  4. Namespace Collisions:

    • Prefix config keys to avoid clashes (e.g., my_app.key vs. other_app.key).

Debugging Tips

  • Dump Config:
    $this->params->all(); // Dump entire parameter bag (use sparingly in production).
    
  • Environment Variables: Override configs via .env:
    MY_APP_KEY=custom_value
    
    Access via %env(MY_APP_KEY)% in YAML or $_ENV['MY_APP_KEY'] in PHP.

Extension Points

  1. Custom Config Loaders: Extend LoaderInterface to support non-PHP config files (e.g., JSON, YAML):

    use Symfony\Component\Config\Loader\LoaderInterface;
    
    class JsonConfigLoader implements LoaderInterface
    {
        public function load($resource, $type = null)
        {
            return json_decode(file_get_contents($resource), true);
        }
        // ...
    }
    
  2. Event Listeners: Listen to kernel.request to modify configs dynamically:

    use Symfony\Component\HttpKernel\Event\RequestEvent;
    
    class ConfigModifierListener
    {
        public function onKernelRequest(RequestEvent $event)
        {
            $request = $event->getRequest();
            $this->params->set('my_app.user_agent', $request->headers->get('User-Agent'));
        }
    }
    
  3. Compiler Passes: Use Symfony’s CompilerPassInterface to merge configs at container compilation:

    use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    
    class ConfigCompilerPass implements CompilerPassInterface
    {
        public function process(ContainerBuilder $container)
        {
            $definition = $container->findDefinition('my_service');
            $definition->addArgument('%my_app%');
        }
    }
    

Performance Considerations

  • Avoid Over-Fetching: Fetch specific keys instead of entire sections when possible:
    // Bad: $this->params->get('my_app'); // Loads all nested keys
    // Good: $this->params->get('my_app.key');
    
  • Lazy-Loading: For large configs, lazy-load sections via a service:
    class LazyConfigService
    {
        public function getSection(string $section): array
        {
            return $this->params->get($section, []);
        }
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope