PHPackages                             monkeyscloud/monkeyslegion-mlc - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. monkeyscloud/monkeyslegion-mlc

ActiveLibrary[Caching](/categories/caching)

monkeyscloud/monkeyslegion-mlc
==============================

`.mlc` MonkeysLegion Config format parser &amp; loader - Production-ready configuration management

2.0.0(5mo ago)11.1k↑142.9%4MITPHPPHP ^8.4

Since Jul 23Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Mlc)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-mlc)[ RSS](/packages/monkeyscloud-monkeyslegion-mlc/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (4)Used By (4)

MonkeysLegion MLC - Configuration Parser
========================================

[](#monkeyslegion-mlc---configuration-parser)

Production-ready `.mlc` configuration file parser and loader for PHP 8.4+.

Features
--------

[](#features)

- 🚀 **Production-Ready**: Built for high-traffic sites with caching and validation
- 🔒 **Secure**: Path traversal prevention, file permission checks
- ⚡ **Fast**: File-based caching with automatic invalidation
- 🎯 **Type-Safe**: Strong typing with helpful getters (`getString()`, `getInt()`, etc.)
- 🔧 **Flexible**: Support for multiple config formats and merge strategies
- 🛡️ **Validated**: Schema-based validation support
- 📝 **Well-Documented**: Comprehensive error messages with line numbers

Installation
------------

[](#installation)

```
composer require monkeyscloud/monkeyslegion-mlc
```

Basic Usage
-----------

[](#basic-usage)

### Loading Configuration

[](#loading-configuration)

```
use MonkeysLegion\Mlc\Loader;
use MonkeysLegion\Mlc\Parser;

$loader = new Loader(
    parser: new Parser(),
    baseDir: '/path/to/config'
);

// Load single file
$config = $loader->loadOne('app');

// Load and merge multiple files
$config = $loader->load(['app', 'database', 'cache']);
```

### Accessing Values

[](#accessing-values)

```
// Dot-notation access
$dbHost = $config->get('database.host', 'localhost');

// Type-safe getters
$port = $config->getInt('database.port', 3306);
$debug = $config->getBool('app.debug', false);
$name = $config->getString('app.name');
$allowed = $config->getArray('cors.allowed_origins', []);

// Required values (throws if missing)
$secret = $config->getRequired('app.secret');

// Check existence
if ($config->has('redis.enabled')) {
    // ...
}

// Get all data
$all = $config->all();
```

MLC Format
----------

[](#mlc-format)

### Basic Syntax

[](#basic-syntax)

```
# Comments start with #

# Key-value pairs (both syntaxes work)
app_name = "My Application"
app_env  production

# Numbers
port = 8080
timeout = 30.5

# Booleans
debug = true
enabled false

# Arrays
allowed_ips = ["127.0.0.1", "192.168.1.1"]

# Multi-line arrays
allowed_methods = [
    "GET",
    "POST",
    "PUT",
    "DELETE"
]

# Sections
database {
    host = localhost
    port = 3306
    name = mydb

    # Nested sections
    credentials {
        username = root
        password = secret
    }
}

# Environment variables (via .env files)
secret_key = ${APP_SECRET}

```

Advanced Features
-----------------

[](#advanced-features)

### Caching

[](#caching)

The MLC package integrates with [MonkeysLegion-Cache](https://github.com/MonkeysCloud/MonkeysLegion-Cache) for high-performance caching with multiple drivers.

```
use MonkeysLegion\Cache\CacheManager;
use MonkeysLegion\Mlc\Loader;
use MonkeysLegion\Mlc\Parser;

// Setup cache (supports File, Redis, Memcached, Array drivers)
$cacheConfig = [
    'default' => 'file',
    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => '/var/cache/mlc',
            'prefix' => 'mlc_',
        ],
        'redis' => [
            'driver' => 'redis',
            'host' => '127.0.0.1',
            'port' => 6379,
            'database' => 1,
            'prefix' => 'mlc_',
        ],
    ],
];

$cacheManager = new CacheManager($cacheConfig);
$cache = $cacheManager->store('file'); // PSR-16 CacheInterface

$loader = new Loader(
    parser: new Parser(),
    baseDir: '/path/to/config',
    cache: $cache
);

$config = $loader->load(['app', 'database']);

// Clear cache when needed
$loader->clearCache();

// Or use the cache manager directly
$cacheManager->clear();
```

**Benefits of MonkeysLegion-Cache integration:**

- PSR-16 compliant caching
- Multiple cache drivers (File, Redis, Memcached, Array)
- Cache tagging support
- Automatic cache invalidation
- Production-tested reliability

For more details on cache configuration and drivers, see the [MonkeysLegion-Cache documentation](https://github.com/MonkeysCloud/MonkeysLegion-Cache).

### Validation

[](#validation)

```
use MonkeysLegion\Mlc\Validator\SchemaValidator;

$schema = [
    'database' => [
        'type' => 'array',
        'required' => true,
        'children' => [
            'host' => ['type' => 'string', 'required' => true],
            'port' => ['type' => 'int', 'required' => true, 'min' => 1, 'max' => 65535],
            'name' => ['type' => 'string', 'required' => true],
        ],
    ],
    'app' => [
        'type' => 'array',
        'children' => [
            'debug' => ['type' => 'bool', 'required' => true],
            'env' => [
                'type' => 'string',
                'required' => true,
                'enum' => ['dev', 'staging', 'production'],
            ],
        ],
    ],
];

$validator = new SchemaValidator($schema);
$loader->setValidator($validator);

try {
    $config = $loader->load(['app', 'database']);
} catch (LoaderException $e) {
    // Validation failed
    echo $e->getMessage();
}
```

### Freezing Configuration

[](#freezing-configuration)

Prevent accidental modifications in production:

```
$config = $loader->load(['app']);
$config->freeze();

// This will throw FrozenConfigException
$config->set('app.debug', true);
```

### Auto-Freeze

[](#auto-freeze)

```
// Automatically freeze all loaded configs
$loader->setAutoFreeze(true);

$config = $loader->load(['app']); // Already frozen
```

### Hot-Reload Detection (Development)

[](#hot-reload-detection-development)

```
$lastCheck = time();

// Later...
if ($loader->hasChanges(['app', 'database'], $lastCheck)) {
    $config = $loader->reload(['app', 'database']);
    $lastCheck = time();
}
```

### Configuration Subsets

[](#configuration-subsets)

```
$config = $loader->load(['app']);

// Get only database config
$dbConfig = $config->subset('database');

// Access as if it were root
$host = $dbConfig->get('host'); // instead of 'database.host'
```

### Merging Configurations

[](#merging-configurations)

```
$baseConfig = $loader->load(['base']);
$envConfig = $loader->load(['production']);

$merged = $baseConfig->merge($envConfig);
```

### Export

[](#export)

```
// To JSON
$json = $config->toJson();

// To array
$array = $config->toArray();
```

Environment Variables
---------------------

[](#environment-variables)

The loader automatically loads `.env` files in this order:

1. `.env`
2. `.env.local`
3. `.env.{APP_ENV}`
4. `.env.{APP_ENV}.local`

Where `APP_ENV` is determined from `$_SERVER['APP_ENV']` or `$_ENV['APP_ENV']`.

### Custom Environment Directory

[](#custom-environment-directory)

```
$loader = new Loader(
    parser: new Parser(),
    baseDir: '/path/to/config',
    envDir: '/path/to/env'  // Different directory for .env files
);
```

### Disable Auto-Load

[](#disable-auto-load)

```
$loader = new Loader(
    parser: new Parser(),
    baseDir: '/path/to/config',
    autoLoadEnv: false
);

// Load manually when needed
$loader->loadEnvironment();
```

Error Handling
--------------

[](#error-handling)

The package provides detailed error messages:

```
use MonkeysLegion\Mlc\Exception\ParserException;
use MonkeysLegion\Mlc\Exception\LoaderException;
use MonkeysLegion\Mlc\Exception\SecurityException;

try {
    $config = $loader->load(['app']);
} catch (ParserException $e) {
    // Parse error with file and line number
    echo $e->getMessage();
    echo $e->getFile();
    echo $e->getLine();
} catch (SecurityException $e) {
    // Security issue (path traversal, permissions, etc.)
    echo $e->getMessage();
} catch (LoaderException $e) {
    // Loading error (file not found, validation failed, etc.)
    echo $e->getMessage();
}
```

Security Features
-----------------

[](#security-features)

- **Path Traversal Prevention**: Validates all file paths
- **File Permission Checks**: Warns about world-writable configs
- **File Size Limits**: Prevents DoS via large files (10MB default)
- **Depth Limits**: Prevents infinite nesting (50 levels default)
- **Immutability**: Frozen configs cannot be modified

Performance
-----------

[](#performance)

### Benchmarks

[](#benchmarks)

With caching enabled:

- **First load**: ~5ms for 5 config files
- **Cached load**: ~0.5ms (10x faster)
- **Memory**: ~50KB per config

### Best Practices

[](#best-practices)

1. **Always use caching in production**
2. **Freeze configs after loading**
3. **Use type-safe getters** for better IDE support
4. **Validate configs** to catch errors early
5. **Cache configs at application bootstrap**

Backwards Compatibility
-----------------------

[](#backwards-compatibility)

This version is **100% backwards compatible** with 1.x:

```
// Old code still works
$loader = new Loader(new Parser(), '/path/to/config');
$config = $loader->load(['app']);
$value = $config->get('key.path');

// New features are opt-in
$config->freeze();  // New
$config->getInt('port', 8080);  // New
```

Migration from 1.x
------------------

[](#migration-from-1x)

No changes required! The new version is a drop-in replacement.

To use new features:

```
// Add caching
$loader = new Loader(
    new Parser(),
    '/path/to/config',
    cache: new FileCache('/tmp/config-cache')
);

// Use type-safe getters
$port = $config->getInt('server.port', 8080);

// Freeze in production
if ($_ENV['APP_ENV'] === 'production') {
    $config->freeze();
}
```

Testing
-------

[](#testing)

```
# Run tests
composer test

# Run static analysis
composer stan

# Fix code style
composer cs-fix

# Run all CI checks
composer ci
```

License
-------

[](#license)

MIT License - see LICENSE file for details.

Support
-------

[](#support)

- **Issues**:
- **Documentation**:

Changelog
---------

[](#changelog)

### 2.0.0 (Production Release)

[](#200-production-release)

- ✨ Added caching support (File, Null)
- ✨ Added schema validation
- ✨ Added type-safe getters
- ✨ Added config freezing
- ✨ Added security checks
- ✨ Better error messages with line numbers
- ✨ Hot-reload detection
- ✨ Configuration subsets and merging
- 🔒 Path traversal prevention
- 🔒 File permission checks
- 🐛 Fixed edge cases in parser
- 📝 Comprehensive documentation
- ✅ 100% backwards compatible with 1.x

### 1.0.0

[](#100)

- Initial release

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance72

Regular maintenance activity

Popularity22

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~72 days

Total

3

Last Release

155d ago

Major Versions

1.0.0 → 2.0.x-dev2025-12-14

### Community

Maintainers

![](https://www.gravatar.com/avatar/51e4df19377776baa8eafb605d9e7d2374b855c686f552c20d6856e94e3597c3?d=identicon)[yorchperaza](/maintainers/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (11 commits)")

---

Tags

configurationconfigparsercachemonkeyslegionmlc

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-mlc/health.svg)

```
[![Health](https://phpackages.com/badges/monkeyscloud-monkeyslegion-mlc/health.svg)](https://phpackages.com/packages/monkeyscloud-monkeyslegion-mlc)
```

###  Alternatives

[romanpitak/nginx-config-processor

Nginx configuration files processor.

7235.3k1](/packages/romanpitak-nginx-config-processor)[corneltek/configkit

Fast config toolkit, which provides super lightweight config accessor and loader.

1314.1k8](/packages/corneltek-configkit)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
