Skip to content

Repository files navigation

InitPHP Config

Advanced configuration manager for PHP: a single configuration tree with dotted-path access, case-insensitive keys, and loaders for arrays, PHP files, whole directories and class/object properties — usable either as an injectable object or through a static facade.

CILatest Stable VersionTotal DownloadsLicensePHP Version Require

Requirements

Installation

composer require initphp/config

Key Concepts

  • Dotted pathsdb.host addresses host inside the db array. Keys can be nested arbitrarily deep.
  • Case-insensitive keysDB.Host, db.host and Db.HOST all refer to the same entry. Keys are folded to lower-case internally.
  • Three entry points that all share the same read/write contract (ConfigInterface):
    • Classes — turn a class's public properties into configuration.
    • Library — an injectable object with the full loader API.
    • Config — a static facade over a shared Library.

Quick Start

Configuration classes

Declare your configuration as public properties and read it through the shared API:

useInitPHP\Config\Classes;
finalclass MyAppConfig extends Classes
{
publicstring$url = 'http://lvh.me';
publicstring$name = 'LocalHost';
/** @var array<string, string> */publicarray$db = [
'host' => 'localhost',
'user' => 'root',
];
}
$config = newMyAppConfig();
$config->get('url'); // "http://lvh.me"$config->get('db.host'); // "localhost"$config->get('details', 'Not Found'); // "Not Found"if ($config->has('name')) {
$config->get('name'); // "LocalHost"
}

The Library object

useInitPHP\Config\Library;
$config = newLibrary();
$config->set('site.url', 'http://lvh.me')
->set('site.db.host', 'localhost');
$config->get('site.url'); // "http://lvh.me"$config->get('SITE.DB.HOST'); // "localhost" (case-insensitive)

The Config static facade

Every call is forwarded to a lazily created, process-wide Library singleton:

useInitPHP\Config\Config;
Config::setArray('site', ['url' => 'http://lvh.me']);
Config::get('site.url'); // "http://lvh.me"
Config::has('site.url'); // true
Config::reset(); // discard the shared instance (useful in tests)

Reading and writing

The following methods are available on Classes, Library, and the Config facade alike:

MethodDescription
get(string $key, mixed $default = null): mixedRead a value, or $default when the key is absent.
set(string $key, mixed $value): selfWrite a value (intermediate arrays are created as needed).
has(string $key): boolWhether the key exists (a stored null still counts as present).
remove(string $key): selfRemove a key (a no-op when it is absent).
all(): arrayThe entire configuration tree as a plain array.

Loaders (Library / Config)

setArray()

publicfunction setArray(?string$name, array$assoc = []): self;

Imports an associative array. When $name is null or '' the array is merged into the root; otherwise it is stored under $name.

Config::setArray('site', [
'url' => 'http://lvh.me',
'db' => ['host' => 'localhost', 'user' => 'db_user'],
]);
Config::get('site.url'); // "http://lvh.me"
Config::get('site.db.host'); // "localhost"

setFile()

publicfunction setFile(?string$name, string$path): self;

Loads a PHP file that returns an associative array.

// config/db.phpreturn [
'HOST' => 'localhost',
'USER' => 'root',
];
Config::setFile('db', __DIR__ . '/config/db.php');
Config::get('db.host'); // "localhost" (keys are case-insensitive)

setDir()

publicfunction setDir(?string$name, string$path, array$exclude = []): self;

Loads every top-level *.php file in a directory. Each file is stored under a key derived from its base name; when $name is given it becomes a common prefix. Files can be skipped via $exclude (with or without the .php suffix).

// config/db.php -> returns ['HOST' => 'localhost']// config/site.php -> returns ['URL' => 'http://lvh.me']
Config::setDir('app', __DIR__ . '/config', ['secrets']);
Config::get('app.db.host'); // "localhost"
Config::get('app.site.url'); // "http://lvh.me"

setClass()

publicfunction setClass(string|object$classOrObject): self;

Imports the public properties of a class or object under the class's short name. A class name imports the property defaults; an instance imports the current values.

namespaceApp\Config;
class AppConfig
{
publicstring$url = 'http://lvh.me';
}
class Database
{
publicstring$host = 'localhost';
}
Config::setClass(\App\Config\AppConfig::class); // by class name
Config::setClass(new \App\Config\Database()); // by instance
Config::get('appconfig.url'); // "http://lvh.me"
Config::get('database.host'); // "localhost"

Object-style access (Library)

A Library exposes top-level entries as read-only nested objects:

$config = newLibrary();
$config->set('db.host', 'localhost')->set('db.user', 'root');
$config->db->host; // "localhost"$config->db->user; // "root"

Error handling

Loader failures throw InitPHP\Config\Exceptions\ConfigException (a RuntimeException): missing files, files that do not return an array, invalid directories, and unknown class names.

useInitPHP\Config\Exceptions\ConfigException;
try {
Config::setFile('db', '/path/to/missing.php');
} catch (ConfigException$e) {
// "Configuration file "/path/to/missing.php" was not found."
}

Documentation

In-depth guides with runnable examples live in docs/.

Testing

composer test# PHPUnit
composer analyse # PHPStan (level 8)
composer cs:check # PHP-CS-Fixer (dry-run)

Credits

License

Released under the MIT License. Copyright © InitPHP.

About

Advanced configuration manager for PHP with dotted-path access, case-insensitive keys, and array/file/directory/class loaders.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages