phossa2 / config
A simple, easy to use, yet powerful configuration management library for PHP.
README
PLEASE USE phoole/config library instead
phossa2/config is a simple, easy to use, yet powerful configuration management library for PHP. The design idea was inspired by another github project mrjgreen/config but some cool features added.
It requires PHP 5.4, supports PHP 7.0+ and HHVM. It is compliant with PSR-1, PSR-2, PSR-4.
Installation
Install via the composer
utility.
composer require "phossa2/config=2.*"
or add the following lines to your composer.json
{ "require": { "phossa2/config": "2.*" } }
Features
-
Simple interface,
get($id, $default = null)
andhas($id)
. -
One central place for all config files for ease of management.
config/ | |___ production/ | | | |___ host1/ | | |___ db.php | | |___ redis.php | | | |___ db.php | |___ dev/ | | | |___ redis.php | |___ db.php | |___ db.php |___ redis.php |___ system.php
-
Use an environment value, such as
production
orproduction/host1
for switching between different configurations. -
Use of references in configuration value is fully supported, such as
${system.tmpdir}
. -
On demand configuration loading (lazy loading).
-
Hierachy configuration structure with dot notation like
db.auth.host
. -
Array access for ease of use. e.g.
$config['db.user'] = 'www';
. -
Reference lookup delegation and config chaining.
-
Support
.php
,.json
,.ini
,.xml
and.serialized
type of config files.
Usage
-
Usually application running environment is different on different servers. A good practice is setting environment in a
.env
file somewhere on the host, and put all configuration files in one centralconfig/
directory.A sample
.env
file,# installation base BASE_DIR=/www # app directory APP_DIR=${BASE_DIR}/app # config directory CONFIG_DIR=${APP_DIR}/config # app env for current host APP_ENV=production/host1
In a sample
bootstrap.php
file,use Phossa2\Config\Config; use Phossa2\Env\Environment; use Phossa2\Config\Loader\ConfigFileLoader; // load environment from '.env' file (new Environment())->load(__DIR__ . '/.env'); // create config instance with the config file loader $config = new Config( new ConfigFileLoader( getenv('CONFIG_DIR'), getenv('APP_ENV') ) ); // object access of $config $db_config = $config->get('db'); // array access of $config $config['db.user'] = 'www';
-
Central config directory and configuration grouping
-
Configuration grouping
Configurations are gathered into one directory and are grouped into files and subdirectories for ease of management.
For example, the
config/system.php
holdssystem.*
configurations// system.php return [ 'tmpdir' => '/usr/local/tmp', // ... ];
Later,
system
related configs can be retrieved as// object acess of config $dir = $config->get('system.tmpdir'); // array access of $config $dir = $config['system.tmpdir'];
Or being used in other configs as references.
-
Configuration files loading order
If the environment is set to
production/host1
, the config files loading order are,-
config/config/*.php
-
config/production/*.php
-
config/production/host1/*.php
Configuration values are overwritten and replaced those from later loaded files.
-
-
-
References make your configuration easy to manage.
For example, in the
system.php
// group: system return [ 'tmpdir' => '/var/local/tmp', ... ];
In your
cache.php
file,// group: cache return [ // a local filesystem cache driver 'local' => [ 'driver' => 'filesystem', 'params' => [ 'root_dir' => '${system.tmpdir}/cache', // use reference here 'hash_level' => 2 ] ], ... ];
You may reset the reference start and ending matching pattern as follows,
// now reference is something like '%{system.tmpdir}%' $config->setReferencePattern('%{', '}%');
-
Config
class implementsArrayAccess
interface. So config values can be accessed just like an array.// test if (!isset($config['db.auth.user'])) { // set $config['db.auth.user'] = 'www'; }
Hierachy configuration structure with dot notation like
db.auth.host
.// returns the db config array $db_config = $config->get('db'); // returns a string $db_host = $config->get('db.auth.host');
Both flat notation and array notation are supported and can co-exist at the same time.
// db config file return [ // array notation 'auth' => [ 'host' => 'localhost', 'port' => 3306 ], // flat notation 'auth.user' => 'dbuser' ];
-
Reference lookup delegation and config chaining
-
Config delegation
Reference lookup delegation is similar to the delegation idea of Interop Container Delegate Lookup
-
Calls to the
get()
method should only return an entry if the entry is part of the config registry. If the entry is not part of the registry, aNULL
will be returned as described inConfigInterface
. -
Calls to the
has()
method should only return true if the entry is part of the config registry. If the entry is not part of the registry, false should be returned. -
If the fetched entry has dependencies (references), instead of performing the reference lookup in this config registry, the lookup is performed on the delegator.
-
Important By default, the lookup SHOULD be performed on the delegator only, not on the config registry itself.
$config1 = new Config(); $config2 = new Config(); $delegator = new Delegator(); // add some values $config1['db.user'] = '${system.user}'; $config2['system.user'] = 'root'; // reference unresolved in $config1 var_dump($config1['db.user'] === '${system.user}'); // true // add both configs to the delegator $delegator->addConfig($config1); $delegator->addConfig($config2); // reference resolved thru the delegator var_dump($config1['db.user'] === 'root'); // true
Delegator
class implements theConfigInterface
andArrayAccess
interfaces, thus can be used just like a normal config.$dbUser = $delegator['db.user'];
-
-
Config chaining
Config chaining can be achieved via multiple-level delegations. For example,
// configs $config1 = new Config(); $config2 = new Config(); // delegators $delegator1 = new Delegator(); $delegator2 = new Delegator(); // register $config1 with $delegator1 $delegator1->addConfig($config1); // chaining $delegator2->addConfig($delegator1); $delegator2->addConfig($config2); // get from the chain $db = $delegator2->get('db');
-
APIs
-
-
get(string $id, $default = null): mixed
$default
is used if no config value is found.The return value might be a
string
,array
or evenobject
. -
has(string $id): bool
Test if
$id
exists or not. Returns aboolean
value.
-
-
-
set(string $id, mixed $value): bool
Set the configuration manually in this session. The value will NOT be reflected in any config files unless you modify config file manually.
$value
may be astring
,array
orobject
.This feature can be disabled by
// disable writing to the $config $config->setWritable(false);
-
setWritable(bool $writable): bool
Enable or disable the
set()
functionality. Returnstrue
on success. -
isWritable(): bool
Test to see if current config writable or not.
-
-
-
setReferencePattern(string $start, string $end): $this
Reset the reference start chars and ending chars. The default are
'${'
and'}'
-
hasReference(string $string): bool
Test to see if there are references in the
$string
-
deReference(string $string): mixed
Dereference all the references in the
$string
. The result might bestring
,array
or evenobject
. -
deReferenceArray(mixed &$data): $this
Recursively dereference everything in the
$data
.$data
might bestring
orarray
. Other data type will be ignored and untouched.
-
-
-
addConfig(ConfigInterface $config): $this
Added one
Phossa2\Config\Interfaces\ConfigInterface
instance to the delegator.
-
-
-
setErrorType(int $type): $this
Set either
Config::ERROR_IGNORE
,Config::ERROR_WARNING
orConfig::ERROR_EXCEPTION
for the config.
-
Change log
Please see CHANGELOG from more information.
Testing
$ composer test
Contributing
Please see CONTRIBUTE for more information.
Dependencies
-
PHP >= 5.4.0
-
phossa2/shared >= 2.0.21