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

Laminas Config Aggregator Laravel Package

laminas/laminas-config-aggregator

Aggregate and merge configuration from multiple providers in Laminas/Mezzio apps. Supports ordered loading, caching, PHP/array and glob-based config files, and environment-specific overrides for fast, predictable configuration builds.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laminas/laminas-config-aggregator
    

    For multi-format support (YAML, JSON, XML, INI):

    composer require laminas/laminas-config
    
  2. Basic Setup: Create a config file (e.g., config/database.global.php):

    return ['db' => ['dsn' => 'mysql:host=localhost']];
    
  3. First Use Case:

    use Laminas\ConfigAggregator\ConfigAggregator;
    use Laminas\ConfigAggregator\PhpFileProvider;
    
    $aggregator = new ConfigAggregator([
        new PhpFileProvider('config/*.global.php'),
    ]);
    
    $config = $aggregator->getMergedConfig();
    // Use $config['db']['dsn'] in your app
    

Where to Look First

  • Providers: Focus on PhpFileProvider for PHP files and LaminasConfigProvider for multi-format support.
  • Documentation: Config Processors and Providers.
  • Caching: Enable caching in production for faster bootstrapping (see ConfigCacheProvider).

Implementation Patterns

Core Workflows

  1. Layered Configuration: Use providers in a specific order (e.g., global.php, local.php, module.php) to override defaults:

    $aggregator = new ConfigAggregator([
        new PhpFileProvider('config/autoload/{,*.}global.php'),
        new PhpFileProvider('config/autoload/{,*.}local.php'),
    ]);
    
  2. Environment-Specific Configs: Dynamically include environment files (e.g., dev.php, prod.php):

    $aggregator = new ConfigAggregator([
        new PhpFileProvider(sprintf('config/autoload/%s.php', $_ENV['APP_ENV'] ?? 'dev')),
    ]);
    
  3. Module-Based Aggregation: Treat each module as a provider (e.g., AuthModuleConfig::class):

    class AuthModuleConfig {
        public function __invoke() {
            return ['auth' => ['driver' => 'oauth']];
        }
    }
    

Integration Tips

  • Service Container: Bind the aggregator to Laravel’s container for dependency injection:

    $app->singleton(ConfigAggregator::class, function ($app) {
        return new ConfigAggregator([...]);
    });
    
  • Caching: Cache merged configs in production:

    use Laminas\ConfigAggregator\ConfigCacheProvider;
    
    $cacheFile = storage_path('framework/config-cache.php');
    $aggregator = new ConfigAggregator([
        new ConfigCacheProvider($cacheFile, [
            new PhpFileProvider('config/*.php'),
        ]),
    ]);
    
  • Validation: Use post-processors to validate configs (e.g., with Respect\Validation):

    $aggregator = new ConfigAggregator([...], null, [
        function (array $config) {
            $validator = new Validator();
            $validator->validate($config, [
                'db.dsn' => 'required|string',
            ]);
            return $config;
        },
    ]);
    
  • Dynamic Providers: Load providers conditionally (e.g., based on feature flags):

    $providers = [];
    if ($app->runningInConsole()) {
        $providers[] = new PhpFileProvider('config/console/*.php');
    }
    

Gotchas and Tips

Pitfalls

  1. Duplicate Providers: Avoid duplicate class strings or instances—throws InvalidConfigProviderException:

    // ❌ Throws exception
    new ConfigAggregator([SomeProvider::class, SomeProvider::class]);
    
  2. Globbing Quirks:

    • Use Laminas\Stdlib\Glob for cross-platform patterns (e.g., {dev,prod}.php).
    • Fallback to PHP’s glob() if laminas-stdlib is missing.
  3. Precedence Order: Later providers override earlier ones. Test ordering carefully:

    // 'local.php' overrides 'global.php'
    new ConfigAggregator([
        new PhpFileProvider('config/*.global.php'),
        new PhpFileProvider('config/*.local.php'),
    ]);
    
  4. Caching Caveats:

    • Cache files must be writable.
    • Clear cache manually when config files change:
      if (file_exists($cacheFile)) unlink($cacheFile);
      

Debugging

  • Inspect Merged Config: Use var_dump($aggregator->getMergedConfig()) to debug precedence issues.
  • Disable Caching: Temporarily remove ConfigCacheProvider to test live config changes.

Extension Points

  1. Custom Providers: Create providers for non-PHP sources (e.g., database, API):

    class ApiConfigProvider {
        public function __invoke() {
            return json_decode(file_get_contents('https://api.example.com/config'), true);
        }
    }
    
  2. Post-Processors for Transformations: Convert configs to Laravel-specific formats (e.g., config('db.default')):

    $aggregator = new ConfigAggregator([...], null, [
        function (array $config) {
            return collect($config)->mapWithKeys(fn ($value, $key) =>
                ['config.' . str_replace(['.', '[', ']'], '.', $key)] => $value
            )->toArray();
        },
    ]);
    
  3. Environment Variables: Replace placeholders (e.g., %DB_HOST%) with .env values:

    $aggregator = new ConfigAggregator([...], null, [
        function (array $config) {
            return preg_replace_callback('/%([^%]+)%/', function ($matches) {
                return env($matches[1], $matches[0]);
            }, $config);
        },
    ]);
    

Performance Tips

  • Lazy Loading: Use generators for large config sets (e.g., yield per file).
  • Cache Invalidation: Implement a cache tag system (e.g., touch() config files on change).
  • Memory: Stream large configs (e.g., fgetcsv() for CSV configs) instead of loading entirely into memory.

Laravel-Specific Quirks

  • Service Provider Booting: Register the aggregator in register() and bind configs in boot():

    public function boot() {
        $this->app->singleton('config', function () {
            return new ConfigAggregator([...])->getMergedConfig();
        });
    }
    
  • Config Publishing: Publish provider templates to config/:

    $this->publishes([
        __DIR__.'/config.php' => config_path('aggregator.php'),
    ]);
    
  • Environment Configs: Override configs per environment (e.g., .env-based providers):

    $aggregator = new ConfigAggregator([
        new PhpFileProvider(sprintf('config/%s.php', $this->app->environment())),
    ]);
    
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.
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
anil/file-picker
broqit/fields-ai