(C)oncept-Labs Config Manager

Maintainers

Package info

github.com/Concept-Labs/config

pkg:composer/concept-labs/config

Statistics

Installs: 188

Dependents: 8

Suggesters: 0

Stars: 0

Open Issues: 0


README

A powerful, flexible, and extensible configuration management library for PHP 8.2+.

PHP >= 8.2 | License: MIT | Part of the Concept Labs ecosystem

Features

  • Dot Notation Access: Access nested configuration values using intuitive dot notation
  • Multiple Format Support: JSON, PHP arrays, and extensible to YAML, INI, etc.
  • Plugin System: Extensible plugin architecture for custom processing
  • Variable Interpolation: Support for environment variables, references, and context values
  • Import/Include System: Modular configuration with file imports
  • Context Management: Flexible context for runtime variable resolution
  • Lazy Resolution: Efficient lazy evaluation of configuration values
  • Factory Pattern: Dependency injection support with custom factories
  • SOLID Principles: Clean architecture following best practices
  • Facade Interface: Simplified configuration creation with pre-configured plugins
  • Type Safe: Full PHP 8.2+ type hints and strict typing
  • 100% Backward Compatible: All improvements maintain existing API

Architecture

Built with SOLID principles in mind:

  • Single Responsibility: Each class has one clear purpose
  • Open/Closed: Extensible through factories and plugins without modification
  • Liskov Substitution: Any factory can replace defaults
  • Interface Segregation: Focused interfaces, no fat interfaces
  • Dependency Inversion: Depends on abstractions, not concrete classes

Dependency Injection

Customize components through optional factory injection:

use Concept\Config\Config;
use Concept\Config\Factory\DefaultStorageFactory;
use Concept\Config\Factory\DefaultResourceFactory;
use Concept\Config\Factory\DefaultParserFactory;

// Use custom factories for complete control
$config = new Config(
    data: ['app' => 'MyApp'],
    context: ['env' => 'production'],
    storageFactory: new CustomStorageFactory(),
    resourceFactory: new CustomResourceFactory(),
    parserFactory: new CustomParserFactory()
);

// Or use defaults - factories are optional
$config = new Config(['app' => 'MyApp']);

Installation

Install via Composer:

composer require concept-labs/config

Quick Start

Basic Usage

use Concept\Config\Config;

// Create a config instance with inline data
$config = new Config([
    'app' => [
        'name' => 'MyApp',
        'debug' => true,
        'version' => '1.0.0'
    ],
    'database' => [
        'host' => 'localhost',
        'port' => 3306
    ]
]);

// Access values using dot notation
echo $config->get('app.name');        // "MyApp"
echo $config->get('database.host');   // "localhost"

// Set values
$config->set('app.version', '2.0.0');

// Check if a key exists
if ($config->has('app.debug')) {
    // ...
}

Loading from Files

use Concept\Config\Facade\Config;

// Use the Facade for fully-featured configuration with all plugins pre-configured
$config = Config::config('config/app.json', context: [
    'ENV' => getenv()
]);

// Or use the direct class
use Concept\Config\Config;

// Load from a JSON file
$config = new Config();
$config->load('config/app.json', parse: true);

// Or use the static factory
use Concept\Config\StaticFactory;

$config = StaticFactory::fromFile('config/app.json', parse: true);

Using Context and Variables

// Create config with environment variable support
$config = new Config([
    'database' => [
        'host' => '@env(DB_HOST)',
        'user' => '@env(DB_USER)',
        'password' => '@env(DB_PASSWORD)'
    ]
], context: [
    'ENV' => getenv()
]);

// Parse to resolve variables
$config->getParser()->parse($config->dataReference());

Documentation

Comprehensive documentation is available in the docs directory:

Key Concepts

Dot Notation

Access nested configuration values using familiar dot notation:

$config->get('database.connection.host');
$config->set('cache.drivers.redis.port', 6379);

Plugin System

Extend functionality through plugins:

// Environment variables
'@env(DB_HOST)'

// Config references
'@database.host'

// Custom plugins
$config->getParser()->registerPlugin(MyCustomPlugin::class, priority: 100);

Factories

Multiple ways to create configurations:

// Facade - Simplified interface with pre-configured plugins
use Concept\Config\Facade\Config;

$config = Config::config('config/*.json', context: [
    'env' => 'production',
    'ENV' => getenv()
]);

// Static factory
use Concept\Config\StaticFactory;

$config = StaticFactory::create(['key' => 'value']);
$config = StaticFactory::fromFile('config.json');
$config = StaticFactory::fromGlob('config/*.json');

// Builder factory
use Concept\Config\Factory;

$config = (new Factory())
    ->withFile('config/app.json')
    ->withFile('config/database.json')
    ->withContext(['env' => 'production'])
    ->create();

The Facade Interface

The Concept\Config\Facade\Config class provides a simplified, opinionated way to create configurations with all essential plugins pre-configured and ready to use.

use Concept\Config\Facade\Config;

// Create config from file(s) with all plugins enabled
$config = Config::config(
    source: 'config/*.json',           // File path or glob pattern
    context: ['env' => 'production'],  // Optional context variables
    overrides: ['debug' => false]      // Optional configuration overrides
);

// The facade automatically configures these plugins in priority order:
// - EnvPlugin (999): @env(VAR_NAME) - Environment variables
// - ContextPlugin (998): ${context.key} - Context values  
// - IncludePlugin (997): @include(file) - Include external files
// - ImportPlugin (996): @import directive - Import and merge configs
// - ReferencePlugin (995): @path.to.value - Internal references
// - ConfigValuePlugin (994): Config-specific value resolution

When to use the Facade:

  • You want a quick, fully-featured configuration setup
  • You need environment variables, references, imports, and includes
  • You prefer convention over configuration
  • You're starting a new project and want sensible defaults

When to use other factories:

  • StaticFactory: Simple use cases without plugins
  • Factory: Custom plugin configuration and advanced control

Advanced Features

Importing Configurations

// Import from another file
$config->import('additional-config.json', parse: true);

// Import to a specific path
$config->importTo('database-config.json', 'database', parse: true);

Configuration Nodes

// Get a configuration subtree as a new Config instance
$dbConfig = $config->node('database');
echo $dbConfig->get('host'); // Direct access without 'database.' prefix

Exporting

Export configuration to files with automatic format detection based on file extension:

// Export to JSON (auto-detected from .json extension)
$config->export('output/config.json');

// Export to PHP array (auto-detected from .php extension)
$config->export('output/config.php');

The format is automatically determined by the Resource adapter system based on the file extension.

Examples

Multi-Environment Configuration

{
  "app": {
    "name": "MyApp",
    "env": "@env(APP_ENV)",
    "debug": "@env(APP_DEBUG)"
  },
  "database": {
    "host": "@env(DB_HOST)",
    "port": "@env(DB_PORT)",
    "name": "@env(DB_NAME)"
  }
}

Configuration with References

{
  "paths": {
    "root": "/var/www",
    "public": "@paths.root/public",
    "storage": "@paths.root/storage"
  }
}

Importing Multiple Files

{
  "@import": [
    "config/database.json",
    "config/cache.json",
    "config/services.json"
  ]
}

Development

Requirements

  • PHP 8.2 or higher
  • Composer

Dependencies

  • concept-labs/arrays - Array manipulation utilities

Running Tests

This package includes comprehensive test coverage using both PHPUnit and Pest:

# Run all tests
composer test

# Run only unit tests
composer test:unit

# Run only feature tests
composer test:feature

# Run tests with coverage
composer test:coverage

Test Statistics:

  • 143 tests covering all functionality
  • 259 assertions
  • PHPUnit and Pest test styles
  • Unit and integration tests

See tests/README.md for detailed testing documentation.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

Credits

Developed and maintained by Concept Labs.

Made with care by Concept Labs