celestifyx / stellaris
A powerful, elegant, and extensible configuration management library for PHP.
1.0.2
2025-07-24 18:08 UTC
Requires
- php: ^8.2
- ext-dom: *
- ext-json: *
- ext-libxml: *
- ext-mbstring: *
- ext-simplexml: *
- psr/cache: 3.0.0
- psr/log: 3.0.2
- symfony/yaml: 7.3.1
- yosymfony/toml: 1.0.4
This package is not auto-updated.
Last update: 2025-07-24 17:33:54 UTC
README
A powerful, elegant, and extensible configuration management library for PHP that supports multiple formats, advanced caching, comprehensive validation, and enterprise-grade features.
Table of Contents
- ✨ Features
- 📦 Installation
- ⚙️ Framework Integration
- 🚀 Quick Start
- 📖 Comprehensive Documentation
- 🎯 Format-Specific Examples
- 📋 Requirements
- 📄 License
- 🌟 Why Choose Stellaris?
✨ Features
🚀 Multi-Format Support
- JSON - Perfect for structured data and APIs
- YAML - Human-readable with comments and advanced features
- XML - Hierarchical data with attributes and namespaces
- INI - Simple key-value pairs with sections
- PHP - Native PHP arrays with full language support
- TOML - Modern configuration format
- Properties – Java-style key-value format
- Dotenv - Environment variable files
- Serialized - PHP serialized data format
💾 Advanced Caching System
- Memory Cache - Lightning-fast in-memory storage
- File Cache - Persistent file-based caching
- Redis Cache - Distributed caching (custom implementation)
- Memcached Cache - High-performance distributed memory caching
- APCu Cache - Shared memory user cache
- Null Cache - No-op cache for development
✅ Comprehensive Validation
- Type Validation - Ensure correct data types
- Range Validation - Numeric min/max constraints
- Email Validation - RFC-compliant email format checking
- URL Validation - Valid URL format with scheme restrictions
- Custom Validators - Extensible validation system
- Pattern Matching - Wildcard pattern support for bulk validation
🔄 Auto-Reload & File Watching
- File Monitoring - Automatic detection of configuration changes
- Hot Reload - Live configuration updates without restart
- Change Callbacks - Custom handlers for configuration updates
- Diff Tracking - Track what changed between configurations
🌍 Environment Integration
- Environment Variables - Load from
$_ENV
with prefix mapping - Custom Mapping - Map environment variables to configuration keys
- Type Conversion - Automatic parsing of boolean, numeric, and JSON values
- Fallback Values - Default values when environment variables are missing
📊 Configuration Management
- Dot Notation - Access nested values with simple syntax (
app.database.host
) - Array Access - Use configuration like native PHP arrays
- Typed Access - Get values with automatic type casting
- Metadata Support - Attach metadata to configuration keys
- Merge Strategies - Combine multiple configurations intelligently
🔒 Enterprise Features
- Type Safety - Strong typing with PHP 8.2+ features
- PSR-3 Logging - Compatible with any PSR-3 logger
- Exception Handling - Detailed error reporting with context
- Memory Efficient - Optimized for large configurations
- Thread Safe - Safe for concurrent access
🧩 Extensibility
- Custom Readers - Add support for new configuration formats
- Plugin Architecture - Extend functionality with custom components
- Event System - Hook into configuration lifecycle events
- Middleware Support - Process configurations through custom pipelines
📦 Installation
composer require celestifyx/stellaris
⚙️ Framework Integration
Stellaris is framework-agnostic and works seamlessly with any PHP project — Laravel, Symfony, Slim, Yii, or custom code.
🚀 Quick Start
<?php
use Stellaris\ConfigManager;
use Stellaris\Cache\MemoryCache;
use Stellaris\Exception\InvalidArgumentException;
use Stellaris\Exception\RuntimeException;
use Stellaris\Exception\ValidationException;
// Create configuration manager with caching
$config = new ConfigManager(cache: new MemoryCache());
// Load configuration from file
try {
$config->load('config/app.json');
} catch (InvalidArgumentException|RuntimeException $e) {
echo "Failed to load configuration: " . $e->getMessage();
}
// Set values with dot notation
try {
$config->set('app.name', 'My Application');
$config->set('database.host', 'localhost');
} catch (InvalidArgumentException|RuntimeException|ValidationException $e) {
echo "Failed to set configuration: " . $e->getMessage();
}
// Get values with defaults
$appName = $config->get('app.name');
$dbHost = $config->get('database.host', 'localhost');
// Use array access
$config['api.key'] = 'secret-key';
$apiKey = $config['api.key'];
// Save configuration
try {
$config->save();
} catch (InvalidArgumentException|RuntimeException $e) {
echo "Failed to save configuration: " . $e->getMessage();
}
📖 Comprehensive Documentation
Loading Configuration
From Files
// Single file
$config->load('config/app.json');
// Single file with explicit formats
$config->load('config/.env.local', format: ConfigFormat::ENV);
// Load multiple files with explicit formats
$config->loadMultiple([
['path' => 'config/app.json', 'format' => ConfigFormat::JSON],
['path' => 'config/database.yaml', 'format' => ConfigFormat::YAML],
['path' => 'config/.env.local', 'format' => ConfigFormat::ENV],
['path' => 'config/cache.data', 'format' => ConfigFormat::SERIALIZED],
'config/services.xml'
]);
// Multiple files (merged in order)
$config->load([
'config/app.json',
'config/database.yaml',
'config/cache.ini',
'config/services.xml',
'config/features.php'
]);
From String Content
use Stellaris\Enum\ConfigFormat;
// YAML from string
$yamlString = "
app:
name: My App
debug: true
features:
- authentication
- caching
- logging
";
$config->loadFromString($yamlString, ConfigFormat::YAML);
// JSON from string
$jsonString = '{"api": {"version": "v2", "timeout": 30}}';
$config->loadFromString($jsonString, ConfigFormat::JSON);
From Environment Variables
// Load all environment variables with prefix
$config->loadFromEnvironment('APP_');
// With custom mapping
$config->loadFromEnvironment('DB_', [
'HOST' => 'database.host',
'PORT' => 'database.port',
'NAME' => 'database.name'
]);
// Environment variables are automatically parsed:
// 'true'/'false' -> boolean
// '123' -> integer
// '3.14' -> float
// '{"key":"value"}' -> array
// 'null' -> null
Advanced Configuration Access
Dot Notation
// Set nested values
$config->set('app.database.connections.mysql.host', 'localhost');
$config->set('app.database.connections.mysql.port', 3306);
// Get nested values
$host = $config->get('app.database.connections.mysql.host');
$port = $config->get('app.database.connections.mysql.port', 3306);
// Check if nested key exists
if ($config->has('app.database.connections.redis')) echo "Redis configuration exists";
Typed Access
// Get values with automatic type casting
$port = $config->getTyped('database.port', 'int'); // Always returns int
$timeout = $config->getTyped('api.timeout', 'float'); // Always returns float
$enabled = $config->getTyped('features.cache', 'bool'); // Always returns bool
$hosts = $config->getTyped('database.hosts', 'array'); // Always returns array
// Supported types: string, int, integer, float, double, bool, boolean, array
Array Access Interface
// Use configuration like a native PHP array
$config['app']['name'] = 'My Application';
$config['database']['host'] = 'localhost';
// Check existence
if (isset($config['app']['debug'])) $debug = $config['app']['debug'];
// Iterate over configuration
foreach ($config as $key => $value) echo $key . ": " . json_encode($value) . PHP_EOL;
Validation System
Built-in Validators
use Stellaris\Validator\TypeValidator;
use Stellaris\Validator\RangeValidator;
use Stellaris\Validator\EmailValidator;
use Stellaris\Validator\UrlValidator;
// Type validation
$config->addValidator('app.name', new TypeValidator('string'));
$config->addValidator('app.port', new TypeValidator('int'));
$config->addValidator('app.debug', new TypeValidator('bool'));
// Range validation for numbers
$config->addValidator('app.port', new RangeValidator(1000, 65535));
$config->addValidator('cache.ttl', new RangeValidator(60, 86400));
// Email validation
$config->addValidator('mail.from', new EmailValidator());
// URL validation
$config->addValidator('api.webhook_url', new UrlValidator(['https']));
// Pattern matching (wildcards)
$config->addValidator('database.*', new TypeValidator('string'));
$config->addValidator('cache.stores.*.ttl', new RangeValidator(0, 86400));
Custom Validators
use Stellaris\Validator\ValidatorInterface;
class DatabaseNameValidator implements ValidatorInterface {
private string $errorMessage = '';
/**
* @param mixed $value
*
* @return bool
*/
function validate(mixed $value): bool {
if (!is_string($value)) {
$this->errorMessage = 'Database name must be a string';
return false;
}
if (!preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $value)) {
$this->errorMessage = 'Database name must start with letter and contain only letters, numbers, and underscores';
return false;
}
return true;
}
/**
* @return string
*/
function getErrorMessage(): string {
return $this->errorMessage;
}
/**
* @return string
*/
function getName(): string {
return 'database_name';
}
/**
* @return array
*/
function getOptions(): array {
return [];
}
}
$config->addValidator('database.name', new DatabaseNameValidator());
Validation Execution
try {
// Validate entire configuration
$config->validate();
echo "Configuration is valid!";
} catch (ValidationException $e) {
echo "Validation failed: " . $e->getMessage() . PHP_EOL;
// Get detailed violations
foreach ($e->getViolations() as $field => $message) echo " " . $field . ": " . $message . PHP_EOL;
}
Caching System
Memory Cache (Default)
use Stellaris\Cache\MemoryCache;
$config = new ConfigManager(cache: new MemoryCache());
// Get cache statistics
$cache = $config->getCache();
if ($cache instanceof MemoryCache) {
$stats = $cache->getStats();
echo "Cache hits: " . $stats['total_keys'] . PHP_EOL;
echo "Memory usage: " . ($stats['memory_usage'] / 1024 / 1024) . " MB\n";
}
File Cache
use Stellaris\Cache\FileCache;
$config = new ConfigManager(cache: new FileCache('/tmp/config_cache'));
Custom Cache Implementation
use Stellaris\Cache\CacheInterface;
class RedisCache implements CacheInterface {
private $redis;
/**
* @param $redisClient
*
* @return void
*/
function __construct($redisClient) {
$this->redis = $redisClient;
}
/**
* @param string $key
* @param mixed|null $default
*
* @return mixed
*/
function get(string $key, mixed $default = null): mixed {
$value = $this->redis->get($key);
return (($value !== false) ? unserialize($value) : $default);
}
/**
* @param string $key
* @param mixed $value
* @param int $ttl
*
* @return bool
*/
function set(string $key, mixed $value, int $ttl = 0): bool {
return $this->redis->setex($key, ($ttl ?: 3600), serialize($value));
}
// ... implement other methods
}
$config = new ConfigManager(cache: new RedisCache($redisClient));
File Watching & Auto-Reload
// Watch single file for changes
$config->watch('config/app.json', function (string $path) {
echo "Configuration file " . $path . " changed!";
// Custom reload logic here
});
// Watch multiple files
$config->watch('config/database.yaml');
$config->watch('config/cache.ini');
// Check for changes manually
if ($config->checkForChanges()) echo "Configuration updated!";
// Enable auto-save (saves immediately on changes)
$config->enableAutoSave();
$config->set('app.version', '2.0.0'); // Automatically saved
Configuration Export & Import
use Stellaris\Enum\ConfigFormat;
// Export to different formats
$json = $config->export(ConfigFormat::JSON);
$yaml = $config->export(ConfigFormat::YAML);
$xml = $config->export(ConfigFormat::XML);
$ini = $config->export(ConfigFormat::INI);
$php = $config->export(ConfigFormat::PHP);
// Save exported configuration
file_put_contents('backup/config.yaml', $yaml);
// Get configuration diff
$diff = $config->getDiff();
if (!empty($diff)) {
echo "Changes detected:\n";
foreach ($diff as $key => $change) echo " " . $key . ": " . $change['action'] . PHP_EOL;
}
Metadata Management
// Set metadata for configuration keys
$config->setMetadata('database.password', [
'sensitive' => true,
'description' => 'Database password - handle with care',
'last_updated' => date('Y-m-d H:i:s'),
'updated_by' => 'admin',
'validation_rules' => ['required', 'min:8']
]);
// Get metadata
$metadata = $config->getMetadata('database.password');
if ($metadata['sensitive']) {
// Handle sensitive data appropriately
}
// Get all metadata
$allMetadata = $config->getMetadata();
Advanced Features
Configuration Merging
// Merge additional configuration
$config->merge([
'new_feature' => [
'enabled' => true,
'settings' => ['option1' => 'value1']
]
]);
// Merge without recursion (replace arrays entirely)
$config->merge($newConfig, false);
Configuration Reset & Reload
// Reset to original state
$config->reset();
// Reload from files
$config->reload();
// Clear all configuration
$config->clear();
Iterator Support
// Iterate over all configuration
foreach ($config as $key => $value) echo $key . ": " . json_encode($value) . PHP_EOL;
// Count configuration keys
echo "Total keys: " . count($config) . PHP_EOL;
// Check if empty
if ($config->isEmpty()) echo "No configuration loaded\n";
🎯 Format-Specific Examples
JSON Configuration
{
"app": {
"name": "My Application",
"version": "1.0.0",
"debug": true
},
"database": {
"default": "mysql",
"connections": {
"mysql": {
"host": "localhost",
"port": 3306,
"database": "myapp"
}
}
},
"features": ["auth", "cache", "logging"]
}
YAML Configuration
# Application Configuration
app:
name: My Application
version: 1.0.0
debug: true
# Database with multiple connections
database:
default: mysql
connections:
mysql:
host: localhost
port: 3306
database: myapp
# Features list
features:
- auth
- cache
- logging
XML Configuration
<?xml version="1.0" encoding="UTF-8" ?>
<config>
<app>
<name>My Application</name>
<version>1.0.0</version>
<debug>true</debug>
</app>
<database default="mysql">
<connections>
<mysql>
<host>localhost</host>
<port>3306</port>
<database>myapp</database>
</mysql>
</connections>
</database>
<features>
<feature>auth</feature>
<feature>cache</feature>
<feature>logging</feature>
</features>
</config>
INI Configuration
; Application settings
[app]
name = "My Application"
version = 1.0.0
debug = true
; Database configuration
[database]
default = mysql
[database.mysql]
host = localhost
port = 3306
database = myapp
; Features (using indexed notation)
[features]
0 = auth
1 = cache
2 = logging
PHP Configuration
<?php
return [
// Application configuration
'app' => [
'name' => 'My Application',
'version' => '1.0.0',
'debug' => env('APP_DEBUG', true)
],
// Database configuration
'database' => [
'default' => 'mysql',
'connections' => [
'mysql' => [
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 3306),
'database' => env('DB_DATABASE', 'myapp')
]
]
],
// Features array
'features' => ['auth', 'cache', 'logging']
];
/**
* @param string $key
* @param mixed|null $default
*
* @return mixed
*/
function env(string $key, mixed $default = null): mixed {
return ($_ENV[$key] ?? $default);
}
TOML Configuration
# Application configuration
[app]
name = "My Application"
version = "1.0.0"
debug = true
# Database configuration
[database]
default = "mysql"
[database.mysql]
host = "localhost"
port = 3306
database = "myapp"
# Features array
features = ["auth", "cache", "logging"]
Properties Configuration
# Application configuration
app.name=My Application
app.version=1.0.0
app.debug=true
# Database configuration
database.default=mysql
database.mysql.host=localhost
database.mysql.port=3306
database.mysql.database=myapp
# Features array (comma-separated)
features=auth,cache,logging
Dotenv Configuration
# Application configuration
APP_NAME="My Application"
APP_VERSION=1.0.0
APP_DEBUG=true
# Database configuration
DATABASE_DEFAULT=mysql
DATABASE_MYSQL_HOST=localhost
DATABASE_MYSQL_PORT=3306
DATABASE_MYSQL_DATABASE=myapp
# Features array
FEATURES=auth,cache,logging
Serialized Configuration
a:3:{s:3:"app";a:3:{s:4:"name";s:14:"My Application";s:7:"version";s:5:"1.0.0";s:5:"debug";b:1;}s:8:"database";a:2:{s:7:"default";s:5:"mysql";s:11:"connections";a:1:{s:5:"mysql";a:3:{s:4:"host";s:9:"localhost";s:4:"port";i:3306;s:8:"database";s:5:"myapp";}}}s:8:"features";a:3:{i:0;s:4:"auth";i:1;s:5:"cache";i:2;s:7:"logging";}}
📋 Requirements
- PHP 8.2+ - Modern PHP with strong typing support
- ext-json - JSON processing (usually included)
- ext-simplexml - XML processing (usually included)
- ext-dom - XML DOM manipulation (usually included)
- ext-libxml - Core XML library used by DOM and SimpleXML
- ext-mbstring - Multibyte string support for handling UTF-8 and non-ASCII characters
Optional Requirements
- symfony/yaml - Enhanced YAML support with advanced features
- yosymfony/toml - TOML format support
- psr/cache - PSR-6 cache interface compatibility
- psr/log - PSR-3 logging interface
📄 License
This project is licensed under the GNU General Public License v3.0 or later - see the LICENSE file for details.
🌟 Why Choose Stellaris?
🚀 Performance
- Optimized for speed with intelligent caching
- Memory-efficient handling of large configurations
- Lazy loading and on-demand parsing
🛡️ Reliability
- Comprehensive test suite with 100% coverage
- Battle-tested in production environments
- Robust error handling and recovery
🔧 Flexibility
- Support for 6 different configuration formats
- Extensible architecture for custom needs
- Framework-agnostic design
📚 Developer Experience
- Intuitive API with excellent IDE support
- Comprehensive documentation with examples
- Strong typing for better code quality
🏢 Enterprise Ready
- Validation and security features
- Monitoring and debugging capabilities
- Scalable architecture for large applications
Stellaris - A powerful, elegant, and extensible configuration management library for PHP. ⭐
Built with ❤️ by the CELESTIFYX Team