diff --git a/README.md b/README.md index 105e913..1cb92ac 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ try { ## Documentation -In-depth guides with runnable examples live in [`docs/`](docs/README.md). +In-depth guides with runnable examples live in [`docs/`](docs/Home.md). ## Testing diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..23afef6 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,294 @@ +# API Reference + +The full surface of the package's public types. Behavioural deep-dives +are linked into the relevant guides. + +Namespace: `InitPHP\Config` (interfaces under `InitPHP\Config\Interfaces`, +exceptions under `InitPHP\Config\Exceptions`). + +| Type | Kind | Summary | +| --- | --- | --- | +| [`ConfigInterface`](#configinterface) | interface | The shared read/write contract. | +| [`AbstractConfig`](#abstractconfig) | abstract class | Shared implementation of the contract. | +| [`Classes`](#classes) | abstract class | Properties-as-configuration base. | +| [`Library`](#library) | final class | Main object + loader API. | +| [`Config`](#config) | final class | Static facade over a shared `Library`. | +| [`ConfigException`](#configexception) | class | Thrown by loaders on failure. | + +--- + +## `ConfigInterface` + +`InitPHP\Config\Interfaces\ConfigInterface` — the minimal contract every +configuration store fulfils. Depend on this in service signatures. + +```php +interface ConfigInterface +{ + public function set(string $key, $value): self; + public function get(string $key, $default = null); + public function has(string $key): bool; + public function remove(string $key): self; + public function all(): array; +} +``` + +| Method | Returns | Description | +| --- | --- | --- | +| `set(string $key, $value)` | `static` | Write a value; intermediate arrays are created for dotted keys. | +| `get(string $key, $default = null)` | `mixed` | Read a value, or `$default` when the key is absent. | +| `has(string $key)` | `bool` | Whether the key exists (a stored `null` still counts as present). | +| `remove(string $key)` | `static` | Remove a key; a no-op when it is absent. | +| `all()` | `array` | The entire configuration tree as a plain array. | + +Keys may use dotted-path notation; see +[Keys & Dotted Paths](Keys-and-Dotted-Paths.md). + +--- + +## `AbstractConfig` + +`InitPHP\Config\AbstractConfig` — `abstract`, `implements ConfigInterface`. +Holds the underlying [`ParameterBag`](https://github.com/InitPHP/ParameterBag) +and implements the shared CRUD + lifecycle. Concrete subclasses populate +the store in their constructor. You do not use this type directly; it is +the common base for [`Classes`](#classes) and [`Library`](#library). + +```php +abstract class AbstractConfig implements ConfigInterface +{ + protected ParameterBag $parameterBag; + + final protected static function newParameterBag(array $data = []): ParameterBag; + + public function __destruct(); + + public function set(string $key, $value): ConfigInterface; + public function get(string $key, $default = null); + public function has(string $key): bool; + public function remove(string $key): ConfigInterface; + public function all(): array; + + public function close(): void; +} +``` + +| Member | Description | +| --- | --- | +| `newParameterBag(array $data = [])` | Builds a store in multi (dotted) + case-insensitive mode. Used by every subclass for consistency. | +| `close()` | Clears the tree by resetting to a fresh empty store; the instance stays usable (options preserved). | +| `__destruct()` | Calls `close()`. | + +--- + +## `Classes` + +`InitPHP\Config\Classes` — `abstract`, extends [`AbstractConfig`](#abstractconfig). +Turns a subclass's own properties into a configuration tree. See +[Configuration Classes](Configuration-Classes.md). + +```php +abstract class Classes extends AbstractConfig +{ + public function __construct(); +} +``` + +- Imports the **default values** of the subclass's **public and + protected** properties (private properties are excluded). +- The internal `parameterBag` property is never imported. +- Provides the full [`ConfigInterface`](#configinterface) surface + inherited from `AbstractConfig`. + +```php +final class AppConfig extends Classes +{ + public string $url = 'http://lvh.me'; + public array $db = ['host' => 'localhost']; +} + +$config = new AppConfig(); +$config->get('db.host'); // 'localhost' +``` + +--- + +## `Library` + +`InitPHP\Config\Library` — `final`, extends [`AbstractConfig`](#abstractconfig). +The main entry point: the CRUD surface plus loaders and object access. +See [The Library Object](The-Library-Object.md). + +```php +final class Library extends AbstractConfig +{ + public const VERSION = '2.0.0'; + + public function __construct(array $data = []); + + public function __get(string $name); // object-style read + public function __debugInfo(): array; + + public function version(): string; + public function replace(array $data): self; + + public function setArray(?string $name, array $assoc = []): self; + public function setFile(?string $name, string $path): self; + public function setDir(?string $name, string $path, array $exclude = []): self; + public function setClass($classOrObject): self; // string|object +} +``` + +### Constructor + +```php +public function __construct(array $data = []); +``` + +Seeds the store with `$data` in dotted-path, case-insensitive mode. + +### `version` + +```php +public function version(): string; +``` + +Returns the package version string (the `VERSION` constant, e.g. +`'2.0.0'`). + +### `replace` + +```php +public function replace(array $data): self; +``` + +Discards the entire tree and installs `$data`. Contrast with +[`set()`](#configinterface), which writes a single key. + +### `setArray` + +```php +public function setArray(?string $name, array $assoc = []): self; +``` + +Imports an associative array under `$name`, or merges it into the root +when `$name` is `null`/`''`. See [Loaders → setArray](Loaders.md#setarray). + +### `setFile` + +```php +public function setFile(?string $name, string $path): self; +``` + +Loads a PHP file that returns an array. Throws +[`ConfigException`](#configexception) when the file is missing, lacks a +`.php` extension, or does not return an array. See +[Loaders → setFile](Loaders.md#setfile). + +### `setDir` + +```php +public function setDir(?string $name, string $path, array $exclude = []): self; +``` + +Loads every top-level `*.php` file in `$path`. `$name` is an optional +common prefix; `$exclude` lists base names to skip. Throws +[`ConfigException`](#configexception) when `$path` is not a directory. +See [Loaders → setDir](Loaders.md#setdir). + +### `setClass` + +```php +public function setClass($classOrObject): self; // accepts string|object +``` + +Imports the **public** properties of a class name (defaults) or object +(runtime values) under the class's short name. Throws +[`ConfigException`](#configexception) when a class name does not exist. +See [Loaders → setClass](Loaders.md#setclass). + +### `__get` + +```php +public function __get(string $name); +``` + +Reads a top-level entry as a value (scalar) or a recursively built +`stdClass` (array); returns `null` for unknown keys. See +[Object Access](Object-Access.md). + +### `__debugInfo` + +```php +public function __debugInfo(): array; +``` + +Returns `['version' => …, 'data' => …]` so `var_dump()` shows the version +and the current tree rather than internals. + +--- + +## `Config` + +`InitPHP\Config\Config` — `final`, static facade over a shared +[`Library`](#library). Cannot be instantiated (private constructor). See +[The Config Facade](The-Config-Facade.md). + +```php +final class Config +{ + public static function __callStatic(string $name, array $arguments); + public static function reset(): void; +} +``` + +| Member | Description | +| --- | --- | +| `__callStatic()` | Forwards any call to the shared `Library` instance. | +| `reset()` | Discards the shared instance (a no-op if none exists). | + +The forwarded methods are declared as `@method` annotations for IDE +support: + +```php +@method static string version() +@method static mixed get(string $key, $default = null) +@method static Library set(string $key, $value) +@method static bool has(string $key) +@method static Library remove(string $key) +@method static array all() +@method static Library replace(array $data) +@method static Library setArray(?string $name, array $assoc = []) +@method static Library setFile(?string $name, string $path) +@method static Library setDir(?string $name, string $path, array $exclude = []) +@method static Library setClass(string|object $classOrObject) +@method static void close() +``` + +--- + +## `ConfigException` + +`InitPHP\Config\Exceptions\ConfigException` — extends +`\RuntimeException`. Thrown by the loaders. Each failure mode has a named +constructor. See [Exceptions](Exceptions.md). + +```php +class ConfigException extends \RuntimeException +{ + public static function fileNotFound(string $path): self; + public static function fileMustReturnArray(string $path): self; + public static function notAPhpFile(string $path): self; + public static function notADirectory(string $path): self; + public static function directoryNotReadable(string $path): self; + public static function classNotFound(string $class): self; +} +``` + +--- + +## See also + +- [Quick Start](Quick-Start.md) — the everyday API in five minutes. +- [Loaders](Loaders.md) — every loader, with examples and error cases. +- [Exceptions](Exceptions.md) — messages and handling patterns. diff --git a/docs/Configuration-Classes.md b/docs/Configuration-Classes.md new file mode 100644 index 0000000..af5b808 --- /dev/null +++ b/docs/Configuration-Classes.md @@ -0,0 +1,109 @@ +# Configuration Classes + +`InitPHP\Config\Classes` is an abstract base class that turns a +subclass's properties into a configuration tree. It is the most natural +fit for configuration that ships with your application **as code** — +typed, discoverable, and version-controlled alongside the rest of your +source. + +## Defining a config class + +Extend `Classes` and declare your configuration as properties with +default values: + +```php +use InitPHP\Config\Classes; + +final class AppConfig extends Classes +{ + public string $url = 'http://lvh.me'; + public string $name = 'LocalHost'; + + /** @var array */ + public array $db = [ + 'host' => 'localhost', + 'user' => 'root', + ]; +} +``` + +## Reading it back + +```php +$config = new AppConfig(); + +$config->get('url'); // 'http://lvh.me' +$config->get('name'); // 'LocalHost' +$config->get('db.host'); // 'localhost' (nested array → dotted path) +$config->get('db.user'); // 'root' + +$config->has('URL'); // true (case-insensitive) +$config->all(); // ['url' => ..., 'name' => ..., 'db' => [...]] +``` + +## Updating at runtime + +A config class is not frozen. Because it shares the +[`ConfigInterface`](API-Reference.md#configinterface) surface, you can +`set` and `remove` after construction: + +```php +$config->set('db.pass', 'secret'); +$config->get('db.pass'); // 'secret' + +$config->remove('db.pass'); +$config->has('db.pass'); // false +``` + +## What gets imported + +- The property **default values** declared on the class are imported. +- Both **public and protected** properties are included — they are + visible from the `Classes` base in the inheritance chain. A subclass's + **private** properties are **not** imported. +- The internal `parameterBag` infrastructure property is **never** part + of the tree. + +```php +final class WithVisibility extends Classes +{ + public string $publicValue = 'public'; + protected string $protectedValue = 'protected'; + private string $privateValue = 'private'; +} + +$config = new WithVisibility(); + +$config->get('publicValue'); // 'public' +$config->get('protectedValue'); // 'protected' +$config->has('privateValue'); // false +$config->has('parameterBag'); // false +``` + +> **Note:** this differs from +> [`Library::setClass()`](Loaders.md#setclass), which imports **public** +> properties only. The difference is intentional: `Classes` inspects +> itself from within the hierarchy, whereas `setClass()` inspects an +> unrelated class from the outside. + +## How it works + +`Classes::__construct()` reads the declared property defaults of the +concrete subclass (`get_class_vars(static::class)`), drops the internal +infrastructure property, and seeds the underlying store in dotted-path, +case-insensitive mode. You do not call `parent::__construct()` with any +arguments — just extend and declare properties. + +## When to use it + +| Use `Classes` when… | Reach for [`Library`](The-Library-Object.md) when… | +| --- | --- | +| Config is known at author time. | Config is loaded from files/env at runtime. | +| You want IDE autocompletion and types. | Sources are dynamic (directories, env). | +| Config is small and stable. | You compose many sources into one tree. | + +## Related reading + +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) — how nested arrays become dotted keys. +- [Typed Config Class recipe](Recipe-Typed-Config-Class.md) — a fuller example. +- [API Reference](API-Reference.md#classes) — the class surface. diff --git a/docs/Exceptions.md b/docs/Exceptions.md new file mode 100644 index 0000000..bcd3880 --- /dev/null +++ b/docs/Exceptions.md @@ -0,0 +1,153 @@ +# Exceptions + +The package throws a single exception type from its loaders: + +``` +\RuntimeException +└── InitPHP\Config\Exceptions\ConfigException +``` + +Because it extends the SPL `\RuntimeException`, existing +`catch (\RuntimeException $e)` blocks continue to work. Most applications +will want to catch the more specific type explicitly so the intent is +unambiguous. + +```php +use InitPHP\Config\Config; +use InitPHP\Config\Exceptions\ConfigException; + +try { + Config::setFile('db', '/path/to/missing.php'); +} catch (ConfigException $e) { + error_log($e->getMessage()); +} +``` + +## When it is raised + +Every failure mode has a dedicated named constructor with a consistent +message. + +| Trigger | Named constructor | Message | +| --- | --- | --- | +| [`setFile()`](Loaders.md#setfile) path does not exist | `ConfigException::fileNotFound()` | `Configuration file "…" was not found.` | +| [`setFile()`](Loaders.md#setfile) target lacks a `.php` extension | `ConfigException::notAPhpFile()` | `Configuration file "…" must have a ".php" extension.` | +| [`setFile()`](Loaders.md#setfile) file does not return an array | `ConfigException::fileMustReturnArray()` | `Configuration file "…" must return an array.` | +| [`setDir()`](Loaders.md#setdir) path is not a directory | `ConfigException::notADirectory()` | `"…" is not a valid directory.` | +| [`setDir()`](Loaders.md#setdir) directory cannot be read | `ConfigException::directoryNotReadable()` | `Could not read the directory "…".` | +| [`setClass()`](Loaders.md#setclass) class name does not exist | `ConfigException::classNotFound()` | `Class "…" was not found.` | + +### File not found + +```php +Config::setFile('db', __DIR__ . '/config/db.php'); + +// ConfigException: +// Configuration file "/…/config/db.php" was not found. +``` + +### File does not return an array + +A loaded file must `return` an associative array: + +```php +// config/bad.php +echo 'oops'; // no return + +Config::setFile('bad', __DIR__ . '/config/bad.php'); + +// ConfigException: +// Configuration file "/…/config/bad.php" must return an array. +``` + +### Wrong extension + +```php +Config::setFile('db', __DIR__ . '/config/db.ini'); + +// ConfigException: +// Configuration file "/…/config/db.ini" must have a ".php" extension. +``` + +### Unknown class + +```php +Config::setClass('App\\Config\\DoesNotExist'); + +// ConfigException: +// Class "App\Config\DoesNotExist" was not found. +``` + +## Catching it + +```php +use InitPHP\Config\Config; +use InitPHP\Config\Exceptions\ConfigException; + +try { + Config::setDir('app', __DIR__ . '/config'); +} catch (ConfigException $e) { + fwrite(STDERR, $e->getMessage() . PHP_EOL); + exit(1); +} +``` + +## Tolerating an optional file + +A missing override file is often expected. Catch and ignore: + +```php +try { + Config::setFile('local', __DIR__ . '/config/local.php'); +} catch (ConfigException) { + // Optional override — safe to skip when absent. +} +``` + +## Re-throwing from your own boundary + +If you wrap the package in a service of your own, re-throw as your own +domain type and preserve the original as `$previous`: + +```php +use InitPHP\Config\Exceptions\ConfigException; +use InitPHP\Config\Library; + +final class ConfigLoader +{ + public function load(string $dir): Library + { + try { + return (new Library())->setDir('app', $dir); + } catch (ConfigException $e) { + throw new \App\BootstrapException( + 'Application config could not be loaded: ' . $e->getMessage(), + 0, + $e, + ); + } + } +} +``` + +## Things that look like errors but aren't + +The read API is deliberately forgiving — these never throw: + +| Situation | What happens | +| --- | --- | +| `get('missing')` | Returns `$default` (default: `null`). | +| `remove('missing')` | Silent no-op. | +| [`setArray()`](Loaders.md#setarray) / [`setFile()`](Loaders.md#setfile) with a `null` name | Merges into the root instead of failing. | +| `Config::reset()` with no active instance | Silent no-op. | + +```php +Config::get('does.not.exist'); // null +Config::get('does.not.exist', 'fallback'); // 'fallback' +Config::remove('does.not.exist'); // no-op, no exception +``` + +## Related reading + +- [Loaders](Loaders.md) — where each exception originates. +- [API Reference → ConfigException](API-Reference.md#configexception) — the factory list. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..2c36c6b --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,121 @@ +# FAQ + +Quick answers to questions that come up when adopting the package. If +your question is not here, please +[open an issue](https://github.com/InitPHP/Config/issues/new) — +documentation fixes are reviewed eagerly. + +## General + +### What is `initphp/config` for? + +A single, uniform API over configuration loaded from arrays, PHP files, +directories, and class/object properties — with dotted-path access and +case-insensitive keys. Use it for application settings, database/cache +config, feature flags, and similar. + +### How is it different from ParameterBag? + +[`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) is the +low-level nested store. `initphp/config` is built **on top of it** and +adds: file/directory/class loaders, a static facade, object-style access, +and a default-on case-insensitive, dotted-path configuration. If you only +need a key/value bag, use ParameterBag directly; if you need to *load* +configuration from multiple sources, use this package. + +### Which should I use — `Classes`, `Library`, or `Config`? + +| You want… | Use | +| --- | --- | +| Typed, code-defined config | [`Classes`](Configuration-Classes.md) | +| An injectable object loaded at runtime | [`Library`](The-Library-Object.md) | +| Global access with no wiring | [`Config`](The-Config-Facade.md) facade | + +They share the same read/write contract, so you can start with one and +move to another with minimal changes. + +## Usage + +### Why does `Config::get('db.host')` work even though I stored `HOST`? + +Keys are case-insensitive in this package — they are folded to +lower-case internally. `HOST`, `Host`, and `host` all resolve to the same +entry. See [Keys & Dotted Paths](Keys-and-Dotted-Paths.md). + +### Why did `setArray(null, …)` not wipe my existing config? + +In v2 a `null`/empty name **merges into the root** rather than replacing +the whole tree. If you want to discard everything, call +[`replace()`](The-Library-Object.md#replacing-the-whole-tree). (This changed +from v1 — see the [Migration Guide](Migration-Guide.md).) + +### Why can't I do `new Config()`? + +The `Config` facade is a static-only utility with a `private` +constructor. Use the static methods (`Config::get(...)`), or inject a +[`Library`](The-Library-Object.md) when you need an object. + +### My `setDir('app', …)` keys are under `app.*` now — did something change? + +Yes. v1 had an inverted prefix bug that dropped the name. v2 applies the +prefix correctly, so files load under `app.`. Pass `null` as the +name if you want no prefix. See the [Migration Guide](Migration-Guide.md). + +### Why does `setClass()` skip my protected/private properties? + +[`setClass()`](Loaders.md#setclass) reads **public** properties only, +because it inspects the target class from the outside. The +[`Classes`](Configuration-Classes.md) base — which inspects itself from +within the hierarchy — imports public **and** protected properties (but +not private). + +### How do I read a whole subtree at once? + +Either `get('db')` to receive the array, or use +[object access](Object-Access.md): `$library->db->host`. + +### How do I distinguish "set to null" from "not set"? + +Use `has()`. A key whose value is `null` is still considered present; +`get()` will return that `null` rather than your default. See +[Keys & Dotted Paths](Keys-and-Dotted-Paths.md#null-values-vs-missing-keys). + +### How do I reset configuration between tests? + +Call `Config::reset()` in your test's `setUp()` (or `tearDown()`). It +discards the shared singleton so the next test starts clean. For a +[`Library`](The-Library-Object.md), just create a new instance per test — +no global state is involved. + +## Behaviour & limits + +### Does it validate configuration values? + +No. The package is a loader and accessor; values flow through unchanged. +Validate at the consumer boundary (e.g. when reading `db.port`, cast and +range-check it there). + +### Is the configuration immutable? + +No. Both `Library` and `Classes` mutate in place. If you need read-only +config after boot, wrap the instance in your own decorator that exposes +only `get`/`has`/`all`. + +### Is the `Config` facade thread/async safe? + +It is a process-wide singleton; treat it like any shared global. In a +worker that handles many requests in one process, call `Config::reset()` +(or reload) between requests if request-specific config must not leak. + +### Does loading a directory load *every* PHP file? + +Yes — every top-level `*.php` file. Each must `return` an array, or the +call throws. Keep non-config PHP out of the directory, or list it in the +`$exclude` argument. See [Loaders → setDir](Loaders.md#setdir). + +## Related reading + +- [Quick Start](Quick-Start.md) +- [Loaders](Loaders.md) +- [Migration Guide](Migration-Guide.md) +- [Exceptions](Exceptions.md) diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..1b7377a --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,84 @@ +# InitPHP Config — Wiki + +Welcome to the official documentation for **`initphp/config`** — an +advanced configuration manager that gives PHP applications a single, +uniform API over configuration loaded from **arrays**, **PHP files**, +**whole directories**, and **class/object properties**, with +**dotted-path** access and **case-insensitive** keys. + +It is built on top of [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag), +which provides the underlying nested store. + +The package ships three entry points that all share the same read/write +contract: + +| Type | Purpose | +| --- | --- | +| [`Classes`](Configuration-Classes.md) | Turn a class's own properties into configuration. | +| [`Library`](The-Library-Object.md) | An injectable object with the full loader API. | +| [`Config`](The-Config-Facade.md) | A static facade over a shared `Library` singleton. | + +All three implement [`ConfigInterface`](API-Reference.md#configinterface), so +`get` / `set` / `has` / `remove` / `all` behave identically wherever you +use them. + +```bash +composer require initphp/config +``` + +```php +use InitPHP\Config\Config; + +Config::setArray('app', [ + 'name' => 'demo', + 'db' => ['host' => 'localhost', 'user' => 'root'], +]); + +Config::get('app.name'); // 'demo' +Config::get('app.db.host'); // 'localhost' +Config::get('app.db.charset', 'utf8'); // 'utf8' (default — key absent) +Config::get('APP.DB.HOST'); // 'localhost' (case-insensitive) +``` + +## Start here + +- **New to the package?** Read [Installation](Installation.md), then [Quick Start](Quick-Start.md). +- **Defining config as code?** See [Configuration Classes](Configuration-Classes.md). +- **Loading from files/dirs?** See [Loaders](Loaders.md) and the + [Environment-Aware Config recipe](Recipe-Environment-Aware-Config.md). +- **Want global access?** Read [The Config Facade](The-Config-Facade.md). +- **Curious how keys are parsed?** Read [Keys & Dotted Paths](Keys-and-Dotted-Paths.md). +- **Upgrading from v1?** Read the [Migration Guide](Migration-Guide.md). +- **Looking for a specific method?** The full [API Reference](API-Reference.md) + lists every class member. + +## At a glance — entry-point matrix + +| Capability | [`Classes`](Configuration-Classes.md) | [`Library`](The-Library-Object.md) | [`Config`](The-Config-Facade.md) | +| --- | :---: | :---: | :---: | +| `get` / `set` / `has` / `remove` / `all` | ✅ | ✅ | ✅ | +| Dotted-path keys (`db.host`) | ✅ | ✅ | ✅ | +| Case-insensitive keys | ✅ | ✅ | ✅ | +| Initial data source | subclass properties | constructor / loaders | loaders | +| Load array — [`setArray()`](Loaders.md#setarray) | ❌ | ✅ | ✅ | +| Load PHP file — [`setFile()`](Loaders.md#setfile) | ❌ | ✅ | ✅ | +| Load directory — [`setDir()`](Loaders.md#setdir) | ❌ | ✅ | ✅ | +| Load class/object — [`setClass()`](Loaders.md#setclass) | ❌ | ✅ | ✅ | +| Replace whole tree — `replace()` | ❌ | ✅ | ✅ | +| [Object-style access](Object-Access.md) (`$cfg->db->host`) | ❌ | ✅ | ❌ | +| Lifetime | per instance | per instance | process-wide singleton | + +## Package metadata + +- **License**: MIT +- **Minimum PHP**: 8.2 (tested on 8.2 – 8.5) +- **Runtime dependencies**: [`initphp/parameterbag`](https://packagist.org/packages/initphp/parameterbag) `^2.0` +- **Packagist**: [`initphp/config`](https://packagist.org/packages/initphp/config) +- **Source**: [github.com/InitPHP/Config](https://github.com/InitPHP/Config) +- **Issues**: [github.com/InitPHP/Config/issues](https://github.com/InitPHP/Config/issues) +- **Discussions**: [github.com/orgs/InitPHP/discussions](https://github.com/orgs/InitPHP/discussions) +- **Security**: [`SECURITY.md`](https://github.com/InitPHP/.github/blob/main/SECURITY.md) + +If something in this wiki is unclear, ambiguous, or wrong, please +[open an issue](https://github.com/InitPHP/Config/issues/new) — +documentation fixes are reviewed eagerly. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..875e7dc --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,70 @@ +# Installation + +## Requirements + +| | | +| --- | --- | +| PHP | `^8.2` (tested on 8.2 – 8.5) | +| Extensions | None | +| Runtime dependencies | [`initphp/parameterbag`](https://packagist.org/packages/initphp/parameterbag) `^2.0` | + +`initphp/parameterbag` is pulled in automatically by Composer. Development +dependencies (PHPUnit, PHPStan, PHP-CS-Fixer) live under `require-dev` and +are not installed when you depend on `initphp/config` from another +project. + +## Install via Composer + +```bash +composer require initphp/config +``` + +The classes are autoloaded under the `InitPHP\Config` namespace via +PSR-4: + +```json +{ + "autoload": { + "psr-4": { + "InitPHP\\Config\\": "src/" + } + } +} +``` + +## Verifying the install + +```php + 'world']); +echo $config->get('hello'); // world +``` + +If the autoloader cannot locate the class, double-check that you ran +`composer install` (or `composer dump-autoload`) and that your script +requires `vendor/autoload.php` before instantiating anything. + +## Supported PHP versions in CI + +Every PR runs the test matrix against: + +- PHP 8.2 +- PHP 8.3 +- PHP 8.4 +- PHP 8.5 + +The pipeline also runs static analysis (PHPStan, level 8) and a coding +standard check (PHP-CS-Fixer). If you discover a regression on a +supported version, please +[file an issue](https://github.com/InitPHP/Config/issues/new) and include +the PHP version reported by `php -v`. + +## Next steps + +- Walk through the everyday API in [Quick Start](Quick-Start.md). +- Learn how keys are parsed in [Keys & Dotted Paths](Keys-and-Dotted-Paths.md). +- Upgrading from v1? Read the [Migration Guide](Migration-Guide.md). diff --git a/docs/Keys-and-Dotted-Paths.md b/docs/Keys-and-Dotted-Paths.md new file mode 100644 index 0000000..f891914 --- /dev/null +++ b/docs/Keys-and-Dotted-Paths.md @@ -0,0 +1,84 @@ +# Keys & Dotted Paths + +Every entry point stores data in a single nested tree. Two rules govern +how a string key maps onto that tree. They are inherited from the +underlying [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) +store, which this package always configures in **multi mode** with +**case-insensitive** keys. + +## Dotted paths + +A dot (`.`) separates levels of nesting. Writing a dotted key creates the +intermediate arrays automatically. + +```php +use InitPHP\Config\Library; + +$config = new Library(); +$config->set('db.connections.mysql.host', 'localhost'); + +$config->get('db.connections.mysql.host'); // 'localhost' +$config->get('db.connections.mysql'); // ['host' => 'localhost'] +$config->get('db'); // ['connections' => ['mysql' => ['host' => 'localhost']]] +``` + +Reading a path that hits a scalar before consuming every segment returns +the default rather than descending into the scalar: + +```php +$config->set('app.name', 'InitPHP'); +$config->get('app.name.first', 'n/a'); // 'n/a' +``` + +## Case-insensitivity + +Keys are folded to lower-case internally, so the case you use when +reading does not have to match the case you used when writing. + +```php +$config->set('App.Database.Host', 'localhost'); + +$config->get('app.database.host'); // 'localhost' +$config->get('APP.DATABASE.HOST'); // 'localhost' +$config->has('app.DATABASE.host'); // true +``` + +This applies to every source: + +- A file returning `['HOST' => 'localhost']` loaded under `db` is read + back as `db.host`. +- A class `AppConfig` loaded with [`setClass()`](Loaders.md#setclass) is + read back under `appconfig`. + +```php +// config/db.php -> return ['HOST' => 'localhost']; +$config->setFile('db', __DIR__ . '/config/db.php'); +$config->get('db.host'); // 'localhost' +``` + +> **Why case-insensitive?** ParameterBag v2 is case-sensitive by default, +> but `initphp/config` opts into case-insensitivity so that file/class +> keys written in any casing (`HOST`, `Host`, `host`) resolve uniformly. +> This is configured internally and is not something callers turn off. + +## `null` values vs. missing keys + +`has()` is the authoritative existence check: a key whose stored value is +`null` is still considered present. + +```php +$config->set('feature.flag', null); + +$config->has('feature.flag'); // true +$config->get('feature.flag', 'fallback'); // null (the stored value wins) +$config->has('feature.missing'); // false +$config->get('feature.missing', 'fallback'); // 'fallback' +``` + +## Related reading + +- [Loaders](Loaders.md) — how each source populates the tree. +- [Object Access](Object-Access.md) — reading a subtree as a nested object. +- ParameterBag's own [Nested Data](https://github.com/InitPHP/ParameterBag/wiki/Nested-Data) + and [Case Sensitivity](https://github.com/InitPHP/ParameterBag/wiki/Case-Sensitivity) + pages cover the underlying mechanics. diff --git a/docs/Loaders.md b/docs/Loaders.md new file mode 100644 index 0000000..4ea5d22 --- /dev/null +++ b/docs/Loaders.md @@ -0,0 +1,184 @@ +# Loaders + +The [`Library`](The-Library-Object.md) object — and therefore the +[`Config` facade](The-Config-Facade.md) — can import configuration from four +sources. Every loader returns `$this` for chaining and throws +[`ConfigException`](Exceptions.md) on failure. + +All keys land in the tree case-insensitively; see +[Keys & Dotted Paths](Keys-and-Dotted-Paths.md). + +--- + +## `setArray()` + +```php +public function setArray(?string $name, array $assoc = []): self; +``` + +Import an associative array. With a `$name` the array is nested under +that key; with `null` or `''` it is **merged into the root** (existing +keys are preserved, colliding keys are overwritten). + +```php +$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' +``` + +Merge at the root: + +```php +$config->set('existing', 'kept'); +$config->setArray(null, ['url' => 'http://lvh.me']); + +$config->get('existing'); // 'kept' +$config->get('url'); // 'http://lvh.me' +``` + +> **Replace vs. merge:** a `null`/empty name **merges** into the root. If +> you want to discard everything and start over, use +> [`replace()`](The-Library-Object.md#replacing-the-whole-tree) instead. + +--- + +## `setFile()` + +```php +public function setFile(?string $name, string $path): self; +``` + +Load a PHP file that **returns** an associative array. As with +`setArray()`, a `null`/`''` name merges into the root. + +```php +// config/db.php +return [ + 'HOST' => 'localhost', + 'USER' => 'root', +]; +``` + +```php +$config->setFile('db', __DIR__ . '/config/db.php'); + +$config->get('db.host'); // 'localhost' (keys folded to lower-case) +$config->get('db.user'); // 'root' +``` + +Throws [`ConfigException`](Exceptions.md) when the file: + +- does not exist, +- does not have a `.php` extension, or +- does not return an array. + +--- + +## `setDir()` + +```php +public function setDir(?string $name, string $path, array $exclude = []): self; +``` + +Load every top-level `*.php` file in a directory. Each file is stored +under a key derived from its base name (`db.php` → `db`). A `$name` +becomes a common prefix. `$exclude` lists base names to skip — with or +without the `.php` suffix, matched case-insensitively. + +```php +// config/db.php -> return ['HOST' => 'localhost']; +// config/site.php -> return ['URL' => 'http://lvh.me']; +// config/secrets.php -> return ['KEY' => '...']; + +$config->setDir('app', __DIR__ . '/config', ['secrets']); + +$config->get('app.db.host'); // 'localhost' +$config->get('app.site.url'); // 'http://lvh.me' +$config->has('app.secrets'); // false (excluded) +``` + +Without a name, the files land at the root: + +```php +$config->setDir(null, __DIR__ . '/config'); + +$config->get('db.host'); // 'localhost' +$config->get('site.url'); // 'http://lvh.me' +``` + +Throws [`ConfigException`](Exceptions.md) when the path is not a directory, +or when a loaded file does not return an array. + +> **Every `*.php` file is loaded.** Keep non-config PHP out of the +> directory, or list it in `$exclude`. A file that does not return an +> array aborts the whole call with an exception. + +--- + +## `setClass()` + +```php +public function setClass(string|object $classOrObject): self; +``` + +Import the **public** properties of a class or object under the class's +short name (its namespace stripped). A class *name* imports property +*defaults*; an *instance* imports the *current* values. + +```php +namespace App\Config; + +class Database +{ + public string $host = 'localhost'; + public int $port = 3306; +} +``` + +```php +// By class name — defaults: +$config->setClass(\App\Config\Database::class); +$config->get('database.host'); // 'localhost' +$config->get('database.port'); // 3306 + +// By instance — runtime values: +$db = new \App\Config\Database(); +$db->host = '10.0.0.5'; +$config->setClass($db); +$config->get('database.host'); // '10.0.0.5' +``` + +Throws [`ConfigException`](Exceptions.md) when a class *name* is given but +no such class exists. + +> **Public only.** Unlike [`Classes`](Configuration-Classes.md), which +> imports public **and protected** properties, `setClass()` reads only +> the **public** surface — it inspects the target from the outside. + +--- + +## Composing sources + +Loaders chain, and later writes win on key collisions, so you can layer +a base file under environment-specific overrides: + +```php +$config = new Library(); + +$config + ->setDir('app', __DIR__ . '/config') // base + ->setFile('app', __DIR__ . '/config/local.php'); // overrides merged on top +``` + +For a full worked example see the +[Environment-Aware Config recipe](Recipe-Environment-Aware-Config.md). + +## Related reading + +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) — key parsing and casing. +- [Exceptions](Exceptions.md) — every failure mode, with messages. +- [API Reference](API-Reference.md#library) — signatures and return types. diff --git a/docs/Migration-Guide.md b/docs/Migration-Guide.md new file mode 100644 index 0000000..54261f8 --- /dev/null +++ b/docs/Migration-Guide.md @@ -0,0 +1,172 @@ +# Migration Guide (v1 → v2) + +v2 is a major release. It fixes bugs that changed observable behaviour, +modernises the API, and tightens the type surface. Most everyday +`get`/`set`/`has` code keeps working unchanged; the changes below matter +mostly if you used the static facade as an object, relied on the +(broken) `setDir` prefix, or used `setArray`/`setFile` with a `null` +name. + +## TL;DR + +- **PHP 8.1+** is now required (was 7.4+). The release after 2.0.0 raises the minimum again, to PHP 8.2. +- **`initphp/parameterbag` `^2.0`** is now required (was `^1.0`). +- **Case-insensitive keys still work** — the package opts into them + internally, so reads/writes that worked in v1 keep working. +- The biggest source-level changes: the **facade is static-only**, and + **`setArray`/`setFile` with a `null` name now merge** instead of + replacing the whole tree. + +## Requirements + +| | v1 | v2 | +| --- | --- | --- | +| PHP | `>=7.4` | `^8.1` (`^8.2` from the release after 2.0.0) | +| `initphp/parameterbag` | `^1.0` | `^2.0` | + +ParameterBag v2 made keys case-sensitive by default. To preserve the +behaviour the v1 docs promised (e.g. loading `['HOST' => …]` and reading +`db.host`), `initphp/config` now configures its store with +`caseInsensitive => true` for you. **No action needed** — your +mixed-case keys still resolve. + +## Behavioural changes (bug fixes) + +### `setDir()` now applies the name prefix correctly + +In v1 the prefix logic was inverted, so `setDir('app', …)` did **not** +produce `app.*` keys. v2 fixes it. + +```php +$config->setDir('app', __DIR__ . '/config'); + +// v1: keys landed without the prefix (e.g. 'db.host') ← bug +// v2: $config->get('app.db.host'); // correct +``` + +If you worked around the bug by reading un-prefixed keys, switch to the +prefixed form (or pass `null` as the name to keep no prefix). + +### Object access (`$config->db`) now returns the full subtree + +In v1, reading an array entry via property access collapsed every +element onto one property and returned only the last value. v2 builds a +correct, recursively nested `stdClass`. + +```php +$config->set('db.host', 'localhost')->set('db.user', 'root'); + +// v1: $config->db → only the last value survived ← bug +// v2: $config->db->host; // 'localhost' +// $config->db->user; // 'root' +``` + +See [Object Access](Object-Access.md). + +### `setArray()` / `setFile()` with a `null` name now merge + +In v1 a `null`/empty name **replaced the entire tree**. v2 **merges** +into the root instead, which is additive and far less surprising. + +```php +$config->set('existing', 'kept'); +$config->setArray(null, ['url' => 'http://lvh.me']); + +// v1: 'existing' was wiped (whole tree replaced) +// v2: $config->get('existing'); // 'kept' — merged at root +``` + +If you depended on the replace-all behaviour, use the new +[`replace()`](The-Library-Object.md#replacing-the-whole-tree) method. + +### `setClass()` with an object uses runtime values + +Given an instance, v2 imports the object's **current** public property +values (v1 imported class defaults in both cases). + +```php +$db = new Database(); +$db->host = '10.0.0.5'; +$config->setClass($db); + +// v2: $config->get('database.host'); // '10.0.0.5' +``` + +## API changes + +### The `Config` facade is static-only + +v1's facade exposed an instance API (`__construct`, `__destruct`, +`__get`, `__call`, `__debugInfo`). That coupling could leave the shared +singleton in an unusable state. v2 removes the instance API: `Config` is +a pure static utility with a `private` constructor. + +```php +// v1 (no longer supported) +$c = new Config(); +$c->get('x'); + +// v2 +Config::get('x'); +Config::reset(); // discard the shared instance (e.g. between tests) +``` + +If you held a `Config` instance, switch to static calls, or inject a +[`Library`](The-Library-Object.md) where you want an object. + +### `remove()` is available everywhere + +In v1 `remove()` existed only on `Classes`. v2 implements it on the +shared base, so [`Library`](The-Library-Object.md) and the +[`Config` facade](The-Config-Facade.md) expose it too. + +```php +Config::remove('app.debug'); +$library->remove('db.pass'); +``` + +### `Library::set(null, …)` removed + +v1 let you call `set(null, $array)` as a replace-all shortcut. v2's +`set()` matches the interface (`string $key`); use +[`replace()`](The-Library-Object.md#replacing-the-whole-tree) instead. + +### Loaders throw `ConfigException` + +v1 loaders threw a generic `\Exception`. v2 throws +[`ConfigException`](Exceptions.md) (a `\RuntimeException`). Broaden or +update your catch blocks: + +```php +// v1 +catch (\Exception $e) { /* … */ } + +// v2 (more specific) +catch (\InitPHP\Config\Exceptions\ConfigException $e) { /* … */ } +``` + +## New in v2 + +- [`Library::replace()`](The-Library-Object.md#replacing-the-whole-tree) — discard and reinstall the tree. +- [`Config::reset()`](The-Config-Facade.md#resetting-between-runs) — drop the shared instance. +- [`ConfigException`](Exceptions.md) — a dedicated, well-messaged exception type. +- `AbstractConfig` — a shared base behind `Library` and `Classes`. +- A test suite, PHPStan (level 8), PHP-CS-Fixer, and CI across PHP 8.1–8.4 (at the time of 2.0.0). + +## Upgrade checklist + +1. Bump your platform to **PHP 8.2+** (2.0.0 itself runs on 8.1, but the current code requires 8.2). +2. `composer require initphp/config:^2.0` (pulls `parameterbag:^2.0`). +3. Replace any `new Config()` usage with static `Config::` calls. +4. Audit `setArray(null, …)` / `setFile(null, …)` — they now merge; use + `replace()` if you wanted replace-all. +5. Verify `setDir(name, …)` consumers now read **prefixed** keys. +6. Update loader `catch` blocks to `ConfigException` (or + `\RuntimeException`). + +## Related reading + +- [The Config Facade](The-Config-Facade.md) +- [Loaders](Loaders.md) +- [Exceptions](Exceptions.md) +- ParameterBag's own [Migration Guide](https://github.com/InitPHP/ParameterBag/wiki/Migration-Guide). diff --git a/docs/Object-Access.md b/docs/Object-Access.md new file mode 100644 index 0000000..31e6d3c --- /dev/null +++ b/docs/Object-Access.md @@ -0,0 +1,91 @@ +# Object Access + +A [`Library`](The-Library-Object.md) exposes top-level configuration entries +as **read-only nested objects** through PHP's magic property access. It +is a convenience for reading deep config without dotted strings. + +> Object access is a feature of `Library` only. The +> [`Classes`](Configuration-Classes.md) base does not provide it, and the +> [`Config` facade](The-Config-Facade.md) is static — there is no instance +> to read properties from. + +## Reading a subtree as an object + +```php +use InitPHP\Config\Library; + +$config = new Library(); +$config->set('db.host', 'localhost') + ->set('db.user', 'root'); + +$db = $config->db; // stdClass + +$db->host; // 'localhost' +$db->user; // 'root' +``` + +Nesting works to any depth: + +```php +$config->set('services.cache.driver', 'redis'); + +$config->services->cache->driver; // 'redis' +``` + +## Scalars and missing keys + +- A **scalar** top-level entry is returned as-is. +- An **unknown** key returns `null`. + +```php +$config->set('name', 'InitPHP'); + +$config->name; // 'InitPHP' (scalar, returned directly) +$config->unknown; // null +``` + +## How it works + +`Library::__get($name)` looks the key up in the underlying store. If the +value is an array it is converted, recursively, into a nested +`stdClass`; scalars pass through unchanged; an absent key yields `null`. + +```php +// Equivalent ways to read the same value: +$config->get('db.host'); // via the dotted-path API +$config->db->host; // via object access +``` + +## Casing + +Because the store is case-insensitive, the object's property names are +the **lower-cased** form of the keys: + +```php +$config->set('DB.Host', 'localhost'); + +$config->db->host; // 'localhost' +// $config->DB->Host would not match — keys are normalised to lower-case. +``` + +## It is a snapshot, not a live view + +`__get` builds a fresh object from the current data each time it is +called. Mutating the returned object does **not** write back into the +configuration: + +```php +$config->set('db.host', 'localhost'); + +$db = $config->db; +$db->host = 'changed'; // touches the local copy only + +$config->get('db.host'); // 'localhost' (unchanged) +``` + +To change configuration, use [`set()`](The-Library-Object.md#the-readwrite-surface). + +## Related reading + +- [The Library Object](The-Library-Object.md) — the full object API. +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) — the dotted-string equivalent. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..7425314 --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,125 @@ +# Quick Start + +A five-minute tour of the three entry points. Every snippet runs as-is. + +## 1. Configuration as a class + +Declare configuration as public properties and read it back through the +shared API: + +```php +use InitPHP\Config\Classes; + +final class AppConfig extends Classes +{ + public string $url = 'http://lvh.me'; + public string $name = 'LocalHost'; + + /** @var array */ + public array $db = [ + 'host' => 'localhost', + 'user' => 'root', + ]; +} + +$config = new AppConfig(); + +$config->get('url'); // 'http://lvh.me' +$config->get('db.host'); // 'localhost' (nested array → dotted path) +$config->get('details', 'Not Found'); // 'Not Found' (default — key absent) +$config->has('name'); // true +``` + +See [Configuration Classes](Configuration-Classes.md) for the full story. + +## 2. The Library object + +`Library` is an injectable object you fill at runtime. All write methods +return `$this`, so they chain: + +```php +use InitPHP\Config\Library; + +$config = new Library(); + +$config->set('site.url', 'http://lvh.me') + ->set('site.db.host', 'localhost') + ->set('site.db.user', 'root'); + +$config->get('site.url'); // 'http://lvh.me' +$config->get('site.db.host'); // 'localhost' +$config->get('SITE.DB.HOST'); // 'localhost' (case-insensitive) +$config->all(); // ['site' => ['url' => ..., 'db' => [...]]] +``` + +You can also seed it at construction: + +```php +$config = new Library([ + 'app' => ['name' => 'demo'], + 'db' => ['host' => 'localhost'], +]); +``` + +See [The Library Object](The-Library-Object.md). + +## 3. The Config facade + +`Config` forwards every static call to a single, process-wide `Library` +instance — register configuration once, read it anywhere: + +```php +use InitPHP\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) +``` + +See [The Config Facade](The-Config-Facade.md). + +## Loading from files and classes + +The `Library` object (and therefore the `Config` facade) can import +configuration from several sources: + +```php +// A PHP file that returns an array +Config::setFile('db', __DIR__ . '/config/db.php'); + +// Every *.php file in a directory, under a common prefix +Config::setDir('app', __DIR__ . '/config'); + +// A class's public properties +Config::setClass(\App\Config\Database::class); + +Config::get('db.host'); +Config::get('app.cache.driver'); +Config::get('database.host'); +``` + +See [Loaders](Loaders.md) for each method in depth. + +## Reading values as objects + +A `Library` exposes top-level entries as nested, read-only objects: + +```php +$config = new Library(); +$config->set('db.host', 'localhost')->set('db.user', 'root'); + +$config->db->host; // 'localhost' +$config->db->user; // 'root' +``` + +See [Object Access](Object-Access.md). + +## Where to go next + +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) — how keys are parsed and normalised. +- [Loaders](Loaders.md) — `setArray`, `setFile`, `setDir`, `setClass`. +- [API Reference](API-Reference.md) — the exhaustive method list. +- [Exceptions](Exceptions.md) — what can go wrong, and how to handle it. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index cd2e6b6..0000000 --- a/docs/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# InitPHP Config — Documentation - -Developer documentation for the `initphp/config` package. Each guide is -self-contained and every example is runnable against the current API. - -## Contents - -1. [Getting Started](getting-started.md) — install, the three entry points, your first read/write. -2. [Keys: Dotted Paths & Case-Insensitivity](keys.md) — how keys are parsed and normalised. -3. [Configuration Classes](configuration-classes.md) — the `Classes` base class. -4. [The Library Object](library.md) — the full loader API (`setArray`, `setFile`, `setDir`, `setClass`) plus object access. -5. [The Static Facade](facade.md) — the process-wide `Config` singleton. -6. [Error Handling](error-handling.md) — `ConfigException` and its failure modes. - -## At a glance - -```php -use InitPHP\Config\Config; -use InitPHP\Config\Library; - -// Static facade — shared, process-wide instance. -Config::setArray('db', ['host' => 'localhost']); -Config::get('db.host'); // "localhost" - -// Injectable object — isolated instance. -$config = new Library(['db' => ['host' => '127.0.0.1']]); -$config->get('db.host'); // "127.0.0.1" -``` - -## The shared contract - -`Classes`, `Library`, and the `Config` facade all expose the same -read/write surface defined by -[`ConfigInterface`](../src/Interfaces/ConfigInterface.php): - -| Method | Returns | Notes | -| ------ | ------- | ----- | -| `get(string $key, mixed $default = null)` | `mixed` | `$default` when the key is absent. | -| `set(string $key, mixed $value)` | `self` | Creates intermediate arrays on demand. | -| `has(string $key)` | `bool` | A stored `null` still counts as present. | -| `remove(string $key)` | `self` | No-op when the key is absent. | -| `all()` | `array` | The whole tree as a plain array. | diff --git a/docs/Recipe-Database-Config.md b/docs/Recipe-Database-Config.md new file mode 100644 index 0000000..5f502bb --- /dev/null +++ b/docs/Recipe-Database-Config.md @@ -0,0 +1,113 @@ +# Recipe: Database Config + +**Goal:** keep database credentials in a dedicated PHP file, load them +through the package, and read them safely when opening a connection. + +## The file + +```php +// config/db.php +return [ + 'host' => '127.0.0.1', + 'port' => 3306, + 'name' => 'app', + 'user' => 'app', + 'pass' => '', + 'charset' => 'utf8mb4', +]; +``` + +## Loading and reading + +```php +use InitPHP\Config\Library; + +$config = new Library(); +$config->setFile('db', __DIR__ . '/config/db.php'); + +$config->get('db.host'); // '127.0.0.1' +$config->get('db.port'); // 3306 +$config->get('db.charset', 'utf8'); // 'utf8mb4' +``` + +Keys are case-insensitive, so a file written with upper-case keys +(`'HOST' => …`) is still read as `db.host`. See +[Keys & Dotted Paths](Keys-and-Dotted-Paths.md). + +## Opening a PDO connection + +Read each value with a sensible default at the point of use — that is +where validation belongs: + +```php +$dsn = sprintf( + 'mysql:host=%s;port=%d;dbname=%s;charset=%s', + $config->get('db.host', '127.0.0.1'), + (int) $config->get('db.port', 3306), + $config->get('db.name', 'app'), + $config->get('db.charset', 'utf8mb4'), +); + +$pdo = new PDO( + $dsn, + $config->get('db.user', 'root'), + $config->get('db.pass', ''), + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], +); +``` + +## Reading the block as an object + +If you prefer object syntax, pull the whole subtree via +[object access](Object-Access.md) (Library only): + +```php +$db = $config->db; // stdClass + +$db->host; // '127.0.0.1' +$db->name; // 'app' +``` + +## Keeping secrets out of the repo + +Commit a safe `db.php` with defaults, and merge a git-ignored local file +on top for real credentials. To **merge** (rather than replace) the `db` +block, load the override at the **root** with a `null` name and nest the +keys under `db` inside the file: + +```php +// config/db.local.php (git-ignored) +return [ + 'db' => [ + 'pass' => 'realsecret', // only the keys you override + ], +]; +``` + +```php +use InitPHP\Config\Exceptions\ConfigException; + +$config->setFile('db', __DIR__ . '/config/db.php'); // committed defaults under 'db' + +try { + // null name → recursive merge at the root, so 'db.*' siblings survive + $config->setFile(null, __DIR__ . '/config/db.local.php'); +} catch (ConfigException) { + // No local overrides present — defaults stand. +} + +$config->get('db.pass'); // 'realsecret' +$config->get('db.host'); // '127.0.0.1' (committed default preserved) +``` + +> **Why not load the override under the `db` name again?** Loading a file +> under a **named** key (`setFile('db', …)`) **replaces** the entire `db` +> subtree. Recursive merging only happens for a `null`/empty name, which +> merges at the root — hence the nested `['db' => …]` shape above. See +> [Loaders → setArray](Loaders.md#setarray). + +## Related reading + +- [Loaders → setFile](Loaders.md#setfile) +- [Object Access](Object-Access.md) +- [Exceptions](Exceptions.md) — handling a missing or malformed file. diff --git a/docs/Recipe-Environment-Aware-Config.md b/docs/Recipe-Environment-Aware-Config.md new file mode 100644 index 0000000..9d3e700 --- /dev/null +++ b/docs/Recipe-Environment-Aware-Config.md @@ -0,0 +1,102 @@ +# Recipe: Environment-Aware Config + +**Goal:** load a base configuration directory, then merge +environment-specific overrides (e.g. `local`, `production`) on top, so a +single tree reflects the active environment. + +## The layout + +``` +config/ +├── app.php # base defaults +├── db.php # base defaults +└── environments/ + ├── local.php # overrides for local + └── production.php +``` + +```php +// config/app.php +return [ + 'name' => 'InitPHP App', + 'debug' => false, + 'timezone' => 'UTC', +]; + +// config/db.php +return [ + 'host' => '127.0.0.1', + 'name' => 'app', + 'user' => 'app', + 'pass' => '', +]; + +// config/environments/local.php +return [ + 'app' => ['debug' => true], + 'db' => ['pass' => 'devsecret'], +]; +``` + +## Loading it + +Load the base directory first, then merge the environment file at the +root. Because [`setFile()`](Loaders.md#setfile) with a `null` name **merges +recursively**, sibling keys are preserved and only the overridden leaves +change. + +```php +use InitPHP\Config\Exceptions\ConfigException; +use InitPHP\Config\Library; + +$env = getenv('APP_ENV') ?: 'production'; + +$config = new Library(); +$config->setDir(null, __DIR__ . '/config', ['environments']); // base, skip the env folder + +try { + $config->setFile(null, __DIR__ . "/config/environments/{$env}.php"); // overrides merged at root +} catch (ConfigException) { + // No override file for this environment — base config stands. +} + +$config->get('app.debug'); // true on local, false otherwise +$config->get('db.pass'); // 'devsecret' on local +$config->get('db.host'); // '127.0.0.1' (base value preserved) +$config->get('app.name'); // 'InitPHP App' (base value preserved) +``` + +> `setDir(null, …)` loads each `*.php` file under its base name +> (`app.php` → `app`, `db.php` → `db`). The `['environments']` exclude +> keeps the per-environment **folder** name out of the scan — folders are +> ignored by `setDir`, but excluding it documents intent and guards a +> stray `environments.php`. + +## Sharing it globally + +If you prefer global access, register the same tree on the +[facade](The-Config-Facade.md) during bootstrap: + +```php +use InitPHP\Config\Config; + +Config::setDir(null, __DIR__ . '/config', ['environments']); +Config::setFile(null, __DIR__ . "/config/environments/{$env}.php"); + +// Anywhere later: +Config::get('app.timezone'); +``` + +## Why merge (not replace)? + +A `null`/empty name on `setArray`/`setFile` performs a **recursive +merge**, so an override file only needs to specify the keys it changes. +Replacing would force every environment file to restate the entire tree. +If you ever do want a clean slate, call +[`replace()`](The-Library-Object.md#replacing-the-whole-tree). + +## Related reading + +- [Loaders](Loaders.md) — `setDir` and `setFile` in detail. +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) — how merged keys resolve. +- [Exceptions](Exceptions.md) — handling a missing override file. diff --git a/docs/Recipe-Typed-Config-Class.md b/docs/Recipe-Typed-Config-Class.md new file mode 100644 index 0000000..4b5d973 --- /dev/null +++ b/docs/Recipe-Typed-Config-Class.md @@ -0,0 +1,136 @@ +# Recipe: Typed Config Class + +**Goal:** define application configuration as a typed PHP class so you +get IDE autocompletion, static-analysis coverage, and a single source of +truth — while still reading it through the uniform +[`ConfigInterface`](API-Reference.md#configinterface) API. + +## Define the class + +Extend [`Classes`](Configuration-Classes.md) and declare your settings as +public properties with defaults: + +```php +namespace App\Config; + +use InitPHP\Config\Classes; + +final class AppConfig extends Classes +{ + public string $name = 'InitPHP App'; + public string $env = 'production'; + public bool $debug = false; + public string $timezone = 'UTC'; + + /** @var array */ + public array $db = [ + 'host' => '127.0.0.1', + 'port' => 3306, + 'name' => 'app', + 'charset' => 'utf8mb4', + ]; + + /** @var array */ + public array $cache = [ + 'driver' => 'file', + 'ttl' => 3600, + ]; +} +``` + +## Read it + +```php +use App\Config\AppConfig; + +$config = new AppConfig(); + +$config->get('name'); // 'InitPHP App' +$config->get('db.host'); // '127.0.0.1' +$config->get('db.port'); // 3306 +$config->get('cache.driver'); // 'file' + +$config->has('db.charset'); // true +$config->get('db.ssl', false); // false (default — key absent) +``` + +Nested array properties become dotted paths automatically; see +[Keys & Dotted Paths](Keys-and-Dotted-Paths.md). + +## Override at runtime + +Because a config class shares the full read/write surface, you can adjust +values after construction — handy for tests or per-request tweaks: + +```php +$config->set('debug', true); +$config->set('db.host', 'db.internal'); + +$config->get('debug'); // true +$config->get('db.host'); // 'db.internal' +``` + +## Inject it + +Type-hint against the interface so consumers stay decoupled and testable: + +```php +use InitPHP\Config\Interfaces\ConfigInterface; +use App\Config\AppConfig; + +$container->set(ConfigInterface::class, fn () => new AppConfig()); + +final class Mailer +{ + public function __construct(private ConfigInterface $config) {} + + public function fromAddress(): string + { + return $this->config->get('mail.from', 'no-reply@example.com'); + } +} +``` + +In a test, pass any `ConfigInterface` — including a plain +[`Library`](The-Library-Object.md) seeded with just the keys under test: + +```php +use InitPHP\Config\Library; + +$mailer = new Mailer(new Library(['mail' => ['from' => 'test@example.com']])); +$mailer->fromAddress(); // 'test@example.com' +``` + +## Visibility rules + +`Classes` imports **public and protected** property defaults (not +private). Use a protected property for a value you want available as +config but not as part of the public class surface: + +```php +final class AppConfig extends Classes +{ + public string $name = 'InitPHP App'; + protected string $secret = 'shared-internally'; // imported as 'secret' + private string $token = 'never-imported'; // NOT imported +} +``` + +See [Configuration Classes → What gets imported](Configuration-Classes.md#what-gets-imported). + +## When to prefer this over file loaders + +| Typed class | File / directory loaders | +| --- | --- | +| Config known at author time | Config supplied by ops / env | +| Autocompletion + static analysis | Dynamic, discovered at runtime | +| One class, version-controlled | Many files, environment overrides | + +The two compose well: define stable defaults as a class, and layer +runtime overrides with a [`Library`](The-Library-Object.md) when needed. + +## Related reading + +- [Configuration Classes](Configuration-Classes.md) +- [The Library Object](The-Library-Object.md) — for runtime/injected config. +- [Environment-Aware Config](Recipe-Environment-Aware-Config.md) — file-based overrides. diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..39b154c --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,64 @@ +# Recipes + +Practical, copy-pasteable patterns built on top of the public API. Each +recipe is self-contained and links back into the reference material for +the methods it uses. + +| Recipe | Solves | +| --- | --- | +| [Environment-Aware Config](Recipe-Environment-Aware-Config.md) | A base config directory with per-environment overrides merged on top. | +| [Database Config](Recipe-Database-Config.md) | Loading database credentials from a PHP file and reading them safely. | +| [Typed Config Class](Recipe-Typed-Config-Class.md) | Strongly-typed, IDE-friendly configuration defined as code. | + +If you have built something on top of the package that other users +might benefit from, please +[open an issue](https://github.com/InitPHP/Config/issues/new) with a +sketch — recipe contributions are welcomed. + +## Pattern sketches + +Short snippets that don't need a full page. + +### Fallback chain across several keys + +```php +use InitPHP\Config\Interfaces\ConfigInterface; + +function configWithFallback(ConfigInterface $config, array $keys, $default = null) +{ + foreach ($keys as $key) { + if ($config->has($key)) { + return $config->get($key); + } + } + + return $default; +} + +$dsn = configWithFallback( + $config, + ['database.dsn', 'db.dsn', 'DATABASE_URL'], + 'sqlite::memory:', +); +``` + +### Snapshot and restore + +```php +$snapshot = $config->all(); +// ... mutate during a unit of work ... +$config->replace($snapshot); // restore the earlier state +``` + +### Read a subtree as an array or an object + +```php +$db = $config->get('db'); // ['host' => '…', 'user' => '…'] +$db = $config->db; // stdClass: $db->host, $db->user (Library only) +``` + +## Related reading + +- [Loaders](Loaders.md) — the source loaders these recipes build on. +- [The Library Object](The-Library-Object.md) — the injectable object. +- [The Config Facade](The-Config-Facade.md) — the global static layer. diff --git a/docs/facade.md b/docs/The-Config-Facade.md similarity index 52% rename from docs/facade.md rename to docs/The-Config-Facade.md index 5f0a180..172203a 100644 --- a/docs/facade.md +++ b/docs/The-Config-Facade.md @@ -1,9 +1,9 @@ -# The Static Facade +# The Config Facade -[`InitPHP\Config\Config`](../src/Config.php) is a static facade over a -single, lazily created, process-wide [`Library`](library.md) instance. It -lets you register configuration once and read it from anywhere without -passing an object around. +`InitPHP\Config\Config` is a static facade over a single, lazily created, +process-wide [`Library`](The-Library-Object.md) instance. It lets you +register configuration once and read it from anywhere without passing an +object around. ```php use InitPHP\Config\Config; @@ -11,7 +11,7 @@ use InitPHP\Config\Config; Config::setArray('site', ['url' => 'http://lvh.me']); // ...elsewhere in the request, no wiring required: -Config::get('site.url'); // "http://lvh.me" +Config::get('site.url'); // 'http://lvh.me' ``` ## Available calls @@ -21,7 +21,7 @@ instance: ```php Config::set('app.name', 'InitPHP'); -Config::get('app.name'); // "InitPHP" +Config::get('app.name'); // 'InitPHP' Config::has('app.name'); // true Config::remove('app.name'); Config::all(); @@ -32,9 +32,13 @@ Config::setDir('app', __DIR__ . '/config'); Config::setClass(\App\Config\Database::class); Config::replace(['fresh' => 'tree']); -Config::version(); // "2.0.0" +Config::version(); // '2.0.0' ``` +The calls are forwarded through `__callStatic`, so the +[`@method`](API-Reference.md#config) annotations on the class give your IDE +full autocompletion. + ## Fluent calls return the Library Methods that would return `$this` on a `Library` return the underlying @@ -51,9 +55,9 @@ $library->get('a'); // 1 ## Resetting between runs -Because the instance is process-wide, long-running workers and especially -**tests** need a way to start clean. `Config::reset()` discards the shared -instance; the next call creates a fresh, empty one. +Because the instance is process-wide, long-running workers — and +especially **tests** — need a way to start clean. `Config::reset()` +discards the shared instance; the next call creates a fresh, empty one. ```php final class SomeTest extends \PHPUnit\Framework\TestCase @@ -71,14 +75,28 @@ final class SomeTest extends \PHPUnit\Framework\TestCase } ``` +Calling `reset()` when no instance exists yet is safe — it is a no-op. + +## The facade cannot be instantiated + +`Config` is a pure static utility: its constructor is `private`, so +`new Config()` throws an `Error`. Use the static methods, or inject +a [`Library`](The-Library-Object.md) when you want an object. + ## Facade or object? -| Use the facade when… | Use a `Library` when… | +| Use the facade when… | Use a [`Library`](The-Library-Object.md) when… | | --- | --- | | You want zero wiring and global reach. | You practice dependency injection. | | Configuration is truly process-global. | You need isolated instances (e.g. multi-tenant). | | Convenience outweighs testability concerns. | You want easy, reset-free test isolation. | The facade is a convenience layer — under the hood it is the exact same -[`Library`](library.md), so behaviour (dotted paths, case-insensitivity, -exceptions) is identical. +[`Library`](The-Library-Object.md), so behaviour (dotted paths, +case-insensitivity, exceptions) is identical. + +## Related reading + +- [The Library Object](The-Library-Object.md) — the instance behind the facade. +- [Loaders](Loaders.md) — the loader methods exposed through the facade. +- [API Reference](API-Reference.md#config) — the facade's method map. diff --git a/docs/The-Library-Object.md b/docs/The-Library-Object.md new file mode 100644 index 0000000..f94e9b8 --- /dev/null +++ b/docs/The-Library-Object.md @@ -0,0 +1,140 @@ +# The Library Object + +`InitPHP\Config\Library` is the package's main entry point: an injectable +object that holds a configuration tree and knows how to populate it from +several sources. Inject it where you need isolated, testable +configuration — as opposed to the global [`Config` facade](The-Config-Facade.md). + +```php +use InitPHP\Config\Library; + +$config = new Library(); // empty +$config = new Library(['db' => []]); // seeded from an array +``` + +## The read/write surface + +`Library` implements [`ConfigInterface`](API-Reference.md#configinterface): + +```php +$config->set('app.name', 'InitPHP'); // returns $this — chainable +$config->get('app.name'); // 'InitPHP' +$config->get('app.locale', 'en'); // 'en' (default — key absent) +$config->has('app.name'); // true +$config->remove('app.name'); // returns $this +$config->all(); // the whole tree as an array +``` + +See [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) for how keys are parsed. + +## Loaders + +`Library` can import configuration from arrays, PHP files, directories, +and class/object properties. Each loader returns `$this`, so they chain +with everything else: + +```php +$config + ->setArray('site', ['url' => 'http://lvh.me']) + ->setFile('db', __DIR__ . '/config/db.php') + ->setDir('app', __DIR__ . '/config') + ->setClass(\App\Config\Database::class); +``` + +Each one is documented in detail on the [Loaders](Loaders.md) page: + +| Method | Loads from | +| --- | --- | +| [`setArray()`](Loaders.md#setarray) | An associative array. | +| [`setFile()`](Loaders.md#setfile) | A PHP file that returns an array. | +| [`setDir()`](Loaders.md#setdir) | Every `*.php` file in a directory. | +| [`setClass()`](Loaders.md#setclass) | A class's / object's public properties. | + +## Replacing the whole tree + +`set()` writes a single key; `replace()` discards the whole tree and +installs a new one: + +```php +$config->set('old', 'value'); +$config->replace(['fresh' => 'data']); + +$config->has('old'); // false +$config->get('fresh'); // 'data' +``` + +## Object-style access + +Top-level entries can be read as nested, read-only `stdClass` objects: + +```php +$config->set('db.host', 'localhost')->set('db.user', 'root'); + +$config->db->host; // 'localhost' +$config->db->user; // 'root' +$config->name; // a scalar entry is returned as-is +$config->unknown; // null for an unknown key +``` + +This is covered on the [Object Access](Object-Access.md) page. + +## Lifecycle + +```php +$config->version(); // the package version, e.g. '2.0.0' +$config->close(); // clear the tree (the instance stays usable) +``` + +`close()` empties the configuration but keeps the instance ready for +reuse — the dotted-path and case-insensitive behaviour is preserved: + +```php +$config->set('a.b', 'c'); +$config->close(); + +$config->all(); // [] +$config->set('x.y', 'z'); // still works +$config->get('x.y'); // 'z' +``` + +The object's destructor calls `close()` automatically, so there is +normally nothing to clean up by hand. + +## Dependency injection + +Because `Library` is a plain object, it slots into any container. Prefer +type-hinting against the interface so consumers can be tested with a +stub: + +```php +use InitPHP\Config\Interfaces\ConfigInterface; +use InitPHP\Config\Library; + +$container->set(ConfigInterface::class, function () { + $config = new Library(); + $config->setDir('app', __DIR__ . '/config'); + + return $config; +}); + +final class ReportService +{ + public function __construct(private ConfigInterface $config) {} + + public function timezone(): string + { + return $this->config->get('app.timezone', 'UTC'); + } +} +``` + +> **Heads-up:** `ConfigInterface` covers `get`/`set`/`has`/`remove`/`all`. +> If a consumer needs the loaders (`setFile`, `setDir`, …) or object +> access, type-hint against `Library` instead. + +## Related reading + +- [Loaders](Loaders.md) — every loader, with examples and error cases. +- [Object Access](Object-Access.md) — reading subtrees as objects. +- [The Config Facade](The-Config-Facade.md) — the static convenience layer. +- [Exceptions](Exceptions.md) — what loaders throw on failure. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..6441515 --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,8 @@ +**`initphp/config`** · MIT License · part of the [InitPHP](https://github.com/InitPHP) family + +[Source](https://github.com/InitPHP/Config) · +[Issues](https://github.com/InitPHP/Config/issues) · +[Discussions](https://github.com/orgs/InitPHP/discussions) · +[Packagist](https://packagist.org/packages/initphp/config) · +[Contributing](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) · +[Security Policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..d99a83d --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,29 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) + +**Core Concepts** +- [Keys & Dotted Paths](Keys-and-Dotted-Paths.md) +- [Configuration Classes](Configuration-Classes.md) +- [The Library Object](The-Library-Object.md) +- [The Config Facade](The-Config-Facade.md) + +**Loading Configuration** +- [Loaders](Loaders.md) +- [Object Access](Object-Access.md) + +**Reference** +- [API Reference](API-Reference.md) +- [Exceptions](Exceptions.md) + +**Practical Guides** +- [Recipes](Recipes.md) +- [— Environment-Aware Config](Recipe-Environment-Aware-Config.md) +- [— Database Config](Recipe-Database-Config.md) +- [— Typed Config Class](Recipe-Typed-Config-Class.md) + +**Migration & Help** +- [Migration Guide (v1 → v2)](Migration-Guide.md) +- [FAQ](FAQ.md) diff --git a/docs/configuration-classes.md b/docs/configuration-classes.md deleted file mode 100644 index 0884009..0000000 --- a/docs/configuration-classes.md +++ /dev/null @@ -1,69 +0,0 @@ -# Configuration Classes - -[`InitPHP\Config\Classes`](../src/Classes.php) is an abstract base class -that turns a subclass's properties into a configuration tree. It is the -most natural fit for configuration that ships with your application as -code. - -## Defining a config class - -```php -use InitPHP\Config\Classes; - -final class AppConfig extends Classes -{ - public string $url = 'http://lvh.me'; - public string $name = 'LocalHost'; - - /** @var array */ - public array $db = [ - 'host' => 'localhost', - 'user' => 'root', - ]; -} -``` - -## Reading it back - -```php -$config = new AppConfig(); - -$config->get('url'); // "http://lvh.me" -$config->get('name'); // "LocalHost" -$config->get('db.host'); // "localhost" (nested array → dotted path) -$config->get('db.user'); // "root" - -$config->has('URL'); // true (case-insensitive) -$config->all(); // ['url' => ..., 'name' => ..., 'db' => [...]] -``` - -## Updating at runtime - -A config class is not frozen — you can `set` and `remove` after -construction: - -```php -$config->set('db.pass', 'secret'); -$config->get('db.pass'); // "secret" - -$config->remove('db.pass'); -$config->has('db.pass'); // false -``` - -## What gets imported - -- The property **default values** declared on the class are imported. -- Both **public and protected** properties are included (they are visible - from the `Classes` base in the inheritance chain); **private** - properties of the subclass are not. -- The internal `parameterBag` infrastructure property is **never** part of - the tree. - -```php -$config->has('parameterBag'); // false -``` - -> **Note:** this differs from [`Library::setClass()`](library.md#setclass), -> which imports **public** properties only. The difference is intentional: -> `Classes` inspects itself from within the hierarchy, whereas -> `setClass()` inspects an unrelated class from the outside. diff --git a/docs/error-handling.md b/docs/error-handling.md deleted file mode 100644 index 40784f8..0000000 --- a/docs/error-handling.md +++ /dev/null @@ -1,59 +0,0 @@ -# Error Handling - -All loader failures throw a single, dedicated exception type: -[`InitPHP\Config\Exceptions\ConfigException`](../src/Exceptions/ConfigException.php). -It extends the SPL `RuntimeException`, so existing -`catch (\RuntimeException)` blocks keep working. - -```php -use InitPHP\Config\Config; -use InitPHP\Config\Exceptions\ConfigException; - -try { - Config::setFile('db', '/path/to/missing.php'); -} catch (ConfigException $e) { - error_log($e->getMessage()); -} -``` - -## Failure modes - -Each failure has a dedicated named constructor with a consistent message: - -| Trigger | Named constructor | Message | -| --- | --- | --- | -| `setFile()` path does not exist | `ConfigException::fileNotFound()` | `Configuration file "…" was not found.` | -| `setFile()` target lacks a `.php` extension | `ConfigException::notAPhpFile()` | `Configuration file "…" must have a ".php" extension.` | -| `setFile()` file does not return an array | `ConfigException::fileMustReturnArray()` | `Configuration file "…" must return an array.` | -| `setDir()` path is not a directory | `ConfigException::notADirectory()` | `"…" is not a valid directory.` | -| `setDir()` directory cannot be read | `ConfigException::directoryNotReadable()` | `Could not read the directory "…".` | -| `setClass()` class name does not exist | `ConfigException::classNotFound()` | `Class "…" was not found.` | - -## What does *not* throw - -These are intentionally lenient and never raise: - -- **Reading a missing key** — `get()` returns the supplied `$default` - (`null` by default). -- **Removing a missing key** — `remove()` is a no-op. -- **`setArray()` / `setFile()` with a `null` name** — merges at the root - rather than failing. - -```php -Config::get('does.not.exist'); // null -Config::get('does.not.exist', 'fallback'); // "fallback" -Config::remove('does.not.exist'); // no-op, no exception -``` - -## Example: tolerating an optional file - -```php -use InitPHP\Config\Config; -use InitPHP\Config\Exceptions\ConfigException; - -try { - Config::setFile('local', __DIR__ . '/config/local.php'); -} catch (ConfigException) { - // Optional override file — safe to ignore when absent. -} -``` diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index 9497477..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,59 +0,0 @@ -# Getting Started - -## Installation - -```bash -composer require initphp/config -``` - -Requirements: **PHP 8.1+** and [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) `^2.0` -(installed automatically by Composer). - -## The three entry points - -The package gives you three ways to work with the same configuration -model. They all implement -[`ConfigInterface`](../src/Interfaces/ConfigInterface.php), so the -`get`/`set`/`has`/`remove`/`all` surface is identical everywhere. - -| Entry point | Best for | Lifetime | -| ----------- | -------- | -------- | -| [`Classes`](configuration-classes.md) | Strongly-typed, code-defined config | Per instance | -| [`Library`](library.md) | Dependency-injected config you load at runtime | Per instance | -| [`Config`](facade.md) | Quick global access without wiring | Process-wide singleton | - -## Your first read and write - -```php -use InitPHP\Config\Library; - -$config = new Library(); - -$config->set('app.name', 'InitPHP') - ->set('app.debug', true); - -$config->get('app.name'); // "InitPHP" -$config->get('app.debug'); // true -$config->get('app.locale', 'en'); // "en" (default — key absent) -$config->has('app.name'); // true -$config->all(); // ['app' => ['name' => 'InitPHP', 'debug' => true]] -``` - -## Seeding data at construction - -`Library` accepts an initial tree: - -```php -$config = new Library([ - 'app' => ['name' => 'InitPHP'], - 'db' => ['host' => 'localhost'], -]); - -$config->get('db.host'); // "localhost" -``` - -## Next steps - -- Learn how keys are parsed in [Keys: Dotted Paths & Case-Insensitivity](keys.md). -- Load configuration from files and directories in [The Library Object](library.md). -- Use the package globally with [The Static Facade](facade.md). diff --git a/docs/keys.md b/docs/keys.md deleted file mode 100644 index ab1bbee..0000000 --- a/docs/keys.md +++ /dev/null @@ -1,59 +0,0 @@ -# Keys: Dotted Paths & Case-Insensitivity - -Every entry point stores data in a single nested tree. Two rules govern -how a string key maps onto that tree. - -## Dotted paths - -A dot (`.`) separates levels of nesting. Writing a dotted key creates the -intermediate arrays automatically. - -```php -use InitPHP\Config\Library; - -$config = new Library(); -$config->set('db.connections.mysql.host', 'localhost'); - -$config->get('db.connections.mysql.host'); // "localhost" -$config->get('db.connections.mysql'); // ['host' => 'localhost'] -$config->get('db'); // ['connections' => ['mysql' => ['host' => 'localhost']]] -``` - -Reading a path that stops at a scalar before consuming every segment -returns the default rather than descending into the scalar: - -```php -$config->set('app.name', 'InitPHP'); -$config->get('app.name.first', 'n/a'); // "n/a" -``` - -## Case-insensitivity - -Keys are folded to lower-case internally, so the case you use when reading -does not have to match the case you used when writing. - -```php -$config->set('App.Database.Host', 'localhost'); - -$config->get('app.database.host'); // "localhost" -$config->get('APP.DATABASE.HOST'); // "localhost" -$config->has('app.DATABASE.host'); // true -``` - -This applies to keys imported from files, arrays and classes too — for -example a file returning `['HOST' => 'localhost']` loaded under `db` is -read back as `db.host`. - -## `null` values vs. missing keys - -`has()` is the authoritative existence check: a key whose stored value is -`null` is still considered present. - -```php -$config->set('feature.flag', null); - -$config->has('feature.flag'); // true -$config->get('feature.flag', 'fallback'); // null (the stored value wins) -$config->has('feature.missing'); // false -$config->get('feature.missing', 'fallback'); // "fallback" -``` diff --git a/docs/library.md b/docs/library.md deleted file mode 100644 index 42aa563..0000000 --- a/docs/library.md +++ /dev/null @@ -1,180 +0,0 @@ -# The Library Object - -[`InitPHP\Config\Library`](../src/Library.php) is the package's main -entry point: an injectable object that holds a configuration tree and -knows how to populate it from several sources. Inject it where you need -isolated, testable configuration (as opposed to the global -[facade](facade.md)). - -```php -use InitPHP\Config\Library; - -$config = new Library(); // empty -$config = new Library(['db' => []]); // seeded -``` - -## Loaders - -### `setArray()` - -```php -public function setArray(?string $name, array $assoc = []): self; -``` - -Import an associative array. With a `$name` the array is nested under that -key; with `null` or `''` it is **merged into the root** (existing keys are -preserved, colliding keys are overwritten). - -```php -$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" - -// Merge at the root: -$config->set('existing', 'kept'); -$config->setArray(null, ['url' => 'http://lvh.me']); -$config->get('existing'); // "kept" -$config->get('url'); // "http://lvh.me" -``` - -### `setFile()` - -```php -public function setFile(?string $name, string $path): self; -``` - -Load a PHP file that **returns** an associative array. As with -`setArray()`, a `null`/`''` name merges into the root. - -```php -// config/db.php -return [ - 'HOST' => 'localhost', - 'USER' => 'root', -]; -``` - -```php -$config->setFile('db', __DIR__ . '/config/db.php'); -$config->get('db.host'); // "localhost" (keys folded to lower-case) -``` - -Throws [`ConfigException`](error-handling.md) when the file is missing, -does not have a `.php` extension, or does not return an array. - -### `setDir()` - -```php -public function setDir(?string $name, string $path, array $exclude = []): self; -``` - -Load every top-level `*.php` file in a directory. Each file is stored -under a key derived from its base name (`db.php` → `db`). A `$name` -becomes a common prefix. `$exclude` lists base names to skip — with or -without the `.php` suffix, matched case-insensitively. - -```php -// config/db.php -> ['HOST' => 'localhost'] -// config/site.php -> ['URL' => 'http://lvh.me'] -// config/secrets.php -> ['KEY' => '...'] - -$config->setDir('app', __DIR__ . '/config', ['secrets']); - -$config->get('app.db.host'); // "localhost" -$config->get('app.site.url'); // "http://lvh.me" -$config->has('app.secrets'); // false (excluded) -``` - -Throws [`ConfigException`](error-handling.md) when the path is not a -readable directory. - -### `setClass()` - -```php -public function setClass(string|object $classOrObject): self; -``` - -Import the **public** properties of a class or object under the class's -short name (namespace stripped). A class *name* imports property -*defaults*; an *instance* imports the *current* values. - -```php -namespace App\Config; - -class Database -{ - public string $host = 'localhost'; - public int $port = 3306; -} -``` - -```php -// By class name — defaults: -$config->setClass(\App\Config\Database::class); -$config->get('database.host'); // "localhost" - -// By instance — runtime values: -$db = new \App\Config\Database(); -$db->host = '10.0.0.5'; -$config->setClass($db); -$config->get('database.host'); // "10.0.0.5" -``` - -Throws [`ConfigException`](error-handling.md) when a class name is given -but no such class exists. - -> Unlike [`Classes`](configuration-classes.md), `setClass()` imports -> **public** properties only. - -## Replacing everything - -```php -public function replace(array $data): self; -``` - -`set()` writes a single key; `replace()` discards the whole tree and -installs a new one. - -```php -$config->set('old', 'value'); -$config->replace(['fresh' => 'data']); - -$config->has('old'); // false -$config->get('fresh'); // "data" -``` - -## Object-style access - -Top-level entries can be read as nested, read-only `stdClass` objects: - -```php -$config->set('db.host', 'localhost')->set('db.user', 'root'); - -$config->db->host; // "localhost" -$config->db->user; // "root" - -$config->name; // a scalar entry is returned as-is -$config->unknown; // null for an unknown key -``` - -## Lifecycle - -```php -public function version(): string; // the package version, e.g. "2.0.0" -public function close(): void; // clear the tree (the instance stays usable) -``` - -`close()` empties the configuration but keeps the instance ready for -reuse — the dotted-path and case-insensitive behaviour is preserved: - -```php -$config->set('a.b', 'c'); -$config->close(); -$config->all(); // [] -$config->set('x.y', 'z'); // still works -$config->get('x.y'); // "z" -```