Config is a file configuration loader that supports PHP, INI, XML, JSON, YML, Properties and serialized files and string

Related tags

Configuration config
Overview

Config

Latest version Software License Build Status Coverage Status Quality Score Total Downloads Gitter

Config is a file configuration loader that supports PHP, INI, XML, JSON, YML, Properties and serialized files and strings.

Requirements

Config requires PHP 5.5.9+.

IMPORTANT: If you want to use YAML files or strings, require the Symfony Yaml component in your composer.json.

Installation

The supported way of installing Config is via Composer.

$ composer require hassankhan/config

Usage

Config is designed to be very simple and straightforward to use. All you can do with it is load, get, and set.

Loading files

The Config object can be created via the factory method load(), or by direct instantiation:

use Noodlehaus\Config;
use Noodlehaus\Parser\Json;

// Load a single file
$conf = Config::load('config.json');
$conf = new Config('config.json');

// Load values from multiple files
$conf = new Config(['config.json', 'config.xml']);

// Load all supported files in a directory
$conf = new Config(__DIR__ . '/config');

// Load values from optional files
$conf = new Config(['config.dist.json', '?config.json']);

// Load a file using specified parser
$conf = new Config('configuration.config', new Json);

Files are parsed and loaded depending on the file extension or specified parser. If the parser is specified, it will be used for all files. Note that when loading multiple files, entries with duplicate keys will take on the value from the last loaded file.

When loading a directory, the path is globed and files are loaded in by name alphabetically.

Warning: Do not include untrusted configuration in PHP format. It could contain and execute malicious code.

Loading string

Configuration from string can be created via the factory method load() or by direct instantiation, with argument $string set to true:

use Noodlehaus\Config;
use Noodlehaus\Parser\Json;
use Noodlehaus\Parser\Yaml;

$settingsJson = <<
   
{
  "application": {
    "name": "configuration",
    "secret": "s3cr3t"
  },
  "host": "localhost",
  "port": 80,
  "servers": [
    "host1",
    "host2",
    "host3"
  ]
}
FOOBAR;

$settingsYaml = <<
   
application:
    name: configuration
    secret: s3cr3t
host: localhost
port: 80
servers:
- host1
- host2
- host3

FOOBAR;

$conf = Config::load($settingsJson, new Json, true);
$conf = new Config($settingsYaml, new Yaml, true);

Warning: Do not include untrusted configuration in PHP format. It could contain and execute malicious code.

Getting values

Getting values can be done in three ways. One, by using the get() method:

// Get value using key
$debug = $conf->get('debug');

// Get value using nested key
$secret = $conf->get('security.secret');

// Get a value with a fallback
$ttl = $conf->get('app.timeout', 3000);

The second method, is by using it like an array:

// Get value using a simple key
$debug = $conf['debug'];

// Get value using a nested key
$secret = $conf['security.secret'];

// Get nested value like you would from a nested array
$secret = $conf['security']['secret'];

The third method, is by using the all() method:

// Get all values
$data = $conf->all();

Setting values

Although Config supports setting values via set() or, via the array syntax, any changes made this way are NOT reflected back to the source files. By design, if you need to make changes to your configuration files, you have to do it manually.

$conf = Config::load('config.json');

// Sample value from our config file
assert($conf['secret'] == '123');

// Update config value to something else
$conf['secret'] = '456';

// Reload the file
$conf = Config::load('config.json');

// Same value as before
assert($conf['secret'] == '123');

// This will fail
assert($conf['secret'] == '456');

Saving config

It is possible to save the config back to a file in any of the supported formats except PHP.

$config = Config::load('config.json');

$ini = $config->toString(new Ini()); // Encode to string if you want to save the file yourself

$config->toFile('config.yaml');
$config->toFile('config.txt', new Serialize()); // you can also force the writer

Using with default values

Sometimes in your own projects you may want to use Config for storing application settings, without needing file I/O. You can do this by extending the AbstractConfig class and populating the getDefaults() method:

class MyConfig extends AbstractConfig
{
    protected function getDefaults()
    {
        return [
            'host' => 'localhost',
            'port'    => 80,
            'servers' => [
                'host1',
                'host2',
                'host3'
            ],
            'application' => [
                'name'   => 'configuration',
                'secret' => 's3cr3t'
            ]
        ];
    }
}

Merging instances

You may want merging multiple Config instances:

$conf1 = Config::load('conf1.json');
$conf2 = Config::load('conf2.json');
$conf1->merge($conf2);

Examples of supported configuration files

Examples of simple, valid configuration files can be found here.

Testing

$ phpunit

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Support for string parser

    Support for string parser

    It add support for parsing strings and specifying file and string parsers. It closes #108 and closes #51. It also closes #109. It also fixes some styling and tests.

    Documentation is also updated.

    enhancement 
    opened by filips123 21
  • [2.0] __DIR__ in PHP file gets wrong path

    [2.0] __DIR__ in PHP file gets wrong path

    In my PROJECT_ROOT/config/app.config.php:

    <?php
    
    return [ 
        'manifest' => __DIR__ . '/../public/build/manifest.json',
        // ...
    ];
    

    Now __DIR__ is evaluated to PROJECT_ROOT/vendor/hassankhan/config/src/Parser due to the eval() in https://github.com/hassankhan/config/blob/f33748ba6b2d2353e4c93ad830bfb26a2a00d2b2/src/Parser/Php.php#L37

    Previous in version 1.x, it's evaluated to PROJECT_ROOT/config which is expected because of using require $file; implementation.


    I notice that all files are now always evaluated as strings.

    https://github.com/hassankhan/config/blob/f33748ba6b2d2353e4c93ad830bfb26a2a00d2b2/src/Config.php#L97

    Could we provide a way to just require a PHP file? I don't think most people would like to load a PHP FILE config as a string and then evaluate it since it could be simply loaded with require and provide better results.


    https://github.com/hassankhan/config/blob/f33748ba6b2d2353e4c93ad830bfb26a2a00d2b2/src/Parser/Php.php#L30-L33

    Just another concern. What if I have ?> in a string such as

    <?php
    
    return [
        'condition1' => '?>count',
        'condition2' => 'count<?',
        'php_starting_tag' => '<?php',
    ];
    

    It could be simplified into $config = str_replace(['<?php', '<?', '?>'], '', $config); by the way.

    bug 
    opened by jfcherng 8
  • Add support for writing configuration files

    Add support for writing configuration files

    Add support for writing configuration files. This would be useful so developers could make user-friendly installers for configuration files.

    For INI, XML, JSON, YAML and other formats, this should not be hard, because they already support writing. For PHP files, this could be harder.

    Example of writing config from start:

    // Instantiation
    $conf = new Config();
    
    // Setting value using key
    $conf->set('debug', true);
    $conf['debug'] = true;
    
    // Setting value using nested key
    $conf->set('security.secret', 'eXaMpLe');
    $conf['security.secret'] = 'eXaMpLe';
    $conf['security']['secret'] = 'eXaMpLe';
    
    // Setting all values from array
    $settings = array(
        'debug' => true,
        'security' => array(
            'secret' => 'eXaMpLe',
            'password' => '1234'
        ),
        'app.timeout' => 3000,
        'app.name' => 'Website'
    );
    $conf->set('', $settings);
    $conf->all() = $settings;
    $conf = $settings;
    
    // Writing to file
    $conf->write('config.json');
    

    Example of writing using existing config:

    // Instantiation
    $conf = new Config('config.json');
    
    // Setting value using key
    $conf['debug'] = true;
    
    // Writing to existing file (file should now have all previous settings and new ones)
    $conf->write();
    
    // Writing to new file (file should now have all previous settings from other file and new ones)
    $conf->write('config.yml');
    
    enhancement 
    opened by filips123 8
  • Defaults not loading

    Defaults not loading

    It seems that the Config class is missing an array_merge() like the AbstractConfig does.

    Right now if I add a default configuration, it will get ignore since $this->data is not merge with the getDefaults() method.

    opened by ti0rafa 8
  • Implement ArrayAccess

    Implement ArrayAccess

    Not sure if you'd want this in the library, but we could implement the ArrayAccess interface to allow for array-style get-set operations. The following would both be the same thing:

    $config->get('key');
    $config['key'];
    
    opened by hassankhan 8
  • Adding container-interop compatibility

    Adding container-interop compatibility

    Hey!

    This pull request is a proposal to add "container-interop" compatibility to "config". As you can see, this pull request is... wooh... 3 lines long :)

    Config already complies with container-interop's ContainerInterface. The only thing we have to do is add the interface.

    Why would we want to do that?

    Container-interop is a common interface for dependency injection containers. Containers usually store services, but they can also store parameters. container-interop does not do any distinction between services and parameters. In container-interop vocabulary, containers are used to store "entries" (they can be either services or parameters... or whatever!)

    Config could therefore be considered as a container providing config parameters. And this is absolutely great, because this means that any container compatible with container-interop (and there are a bunch of them!) would be able to fetch data from the Config container (one of the big ideas of container-interop is to allow a container to fetch parameters/service from other containers through delegate dependency lookup)

    In short, this pull request makes it possible to use Config really easily with a hug range of different projects.

    Disclaimer: I'm one of container-interop authors, and I'm also the editor of PSR-11 (with @mnapoli) that is currently in discussion and planning to transform container-interop into a PSR.

    opened by moufmouf 7
  • Add neon support

    Add neon support

    Similar to issue #16. Syntax here: http://ne-on.org/ It's made by/for Nette framework. These both issues would make this package usable for almost every framework.

    I'd be for standalone repositories with suggestion in composer:

    • noddlehaus/config-yaml
    • noddlehaus/config-neon

    I can send PR for this support.

    opened by TomasVotruba 7
  • config file numeric keys  reset

    config file numeric keys reset

    config file:

    <?php
    return [
        "1001"=>[
            'appsecret'=>"46fc45f1300d15bd89347b9ec0f02f58",
        ]
    ];
    

    print_r(Config::load($configFile)->all());

    Array
    (
        [0] => Array
        (
            [appsecret] => 46fc45f1300d15bd89347b9ec0f02f58
        )
    )
    

    code tracking

    ./config/src/AbstractConfig.php line 40

    public function __construct(array $data)
    {
        $this->data = array_merge($this->getDefaults(), $data);
    }
    

    array_merge:

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

    question 
    opened by baiy 6
  • Remove Cache Property?

    Remove Cache Property?

    Demo Code

    $this->config->set('database', array(
        'host' => 'localhost',
        'name' => 'mydatabase'
     ));
    
    $this->config->set('database.host', '127.0.0.1');
    $this->config->get('database'); //cache 
    
    $this->config->set('database.port', 3306);
    $this->config->get('database'); //cache
    

    Reset cache data when use the function set? Recursive cache list and match it? Feeling is a daunting job.

    opened by ftwbzhao 6
  • Add array and dir support in the constructor.

    Add array and dir support in the constructor.

    Now the Config class accepts also:

    • an array of files from which it gets all the keys using array_replace_recursive;
    • a directory of files.

    It refers to #18.

    opened by DavidePastore 6
  • handle blank .json files without throwing error

    handle blank .json files without throwing error

    code:

    $conf = Config::load('config.json');

    ^ config.json is a blank file, empty.

    result: Fatal error: Uncaught Noodlehaus\Exception\ParseException: Syntax error in config.json:15 Stack trace: #0 \config-2.2.0\vendor\hassankhan\config\src\Parser\Json.php(29): Noodlehaus\Parser\Json->parse(NULL, 'config.json') #1 \config-2.2.0\vendor\hassankhan\config\src\Config.php(114): Noodlehaus\Parser\Json->parseFile('config.json') #2 \config-2.2.0\vendor\hassankhan\config\src\Config.php(79): Noodlehaus\Config->loadFromFile('config.json', Object(Noodlehaus\Parser\Json)) #3 \config-2.2.0\vendor\hassankhan\config\src\Config.php(64): Noodlehaus\Config->__construct('config.json', NULL, false) #4 \config-2.2.0\vendor\autoload.php(51): Noodlehaus\Config::load('config.json') #5 {main} thrown in config.json on line 15

    enhancement 
    opened by samsong 3
  • XML Writer fails on XML content with attributes

    XML Writer fails on XML content with attributes

    The XML writer doesn't work on XML that contains attributes. I discovered this trying to modify my phpunit.xml.

    Here's a passing test case with one of the project's own mocks:

    $raw = <<<RAW
    <?xml version="1.0" encoding="UTF-8"?>
    <config>
        <application>
            <name>configuration</name>
            <secret>s3cr3t</secret>
        </application>
        <host>localhost</host>
        <port>80</port>
        <servers>
            <server1>host1</server1>
            <server2>host2</server2>
            <server3>host3</server3>
        </servers>
    </config>
    RAW;
    $config = new \Noodlehaus\Config($raw, new \Noodlehaus\Parser\Xml(), TRUE);
    $xml = $config->toString(new \Noodlehaus\Writer\Xml(), TRUE);
    print $xml;
    

    Result:

    <?xml version="1.0"?>
    <config>
      <application>
        <name>configuration</name>
        <secret>s3cr3t</secret>
      </application>
      <host>localhost</host>
      <port>80</port>
      <servers>
        <server1>host1</server1>
        <server2>host2</server2>
        <server3>host3</server3>
      </servers>
    </config>
    

    Add an attribute to any element in the XML, and it will fail:

    $raw = <<<RAW
    <?xml version="1.0" encoding="UTF-8"?>
    <config test="example">
        <application>
            <name>configuration</name>
            <secret>s3cr3t</secret>
        </application>
        <host>localhost</host>
        <port>80</port>
        <servers>
            <server1>host1</server1>
            <server2>host2</server2>
            <server3>host3</server3>
        </servers>
    </config>
    RAW;
    $config = new \Noodlehaus\Config($raw, new \Noodlehaus\Parser\Xml(), TRUE);
    $xml = $config->toString(new \Noodlehaus\Writer\Xml(), TRUE);
    var_dump($xml);
    

    Result:

    <?xml version="1.0"?>
    
    bug 
    opened by TravisCarden 1
  • Fix unsetting offset

    Fix unsetting offset

    Fixes unsetting offset. Fixes #123.

    Methods unset, offsetUnset and remove now delete offset from data and cache array. I used 1. solution from here.

    We should now discuss if changing the interface is really such a breaking change. Are there actually any developers who actually implemented their own AbstractConfig? We can probably release as the minor/normal version, but just add in the release notes that interface is changed.

    opened by filips123 3
Releases(3.1.0)
  • 3.1.0(Dec 20, 2022)

    What's Changed

    • Drop support for the end of life PHP versions by @nbayramberdiyev in https://github.com/hassankhan/config/pull/149
    • Remove .travis.yml file by @peter279k in https://github.com/hassankhan/config/pull/152
    • Let assertEquals change into assertSame by @peter279k in https://github.com/hassankhan/config/pull/153
    • Fix namespaces in tests & allow tests to run on PHP 8.2 by @nbayramberdiyev in https://github.com/hassankhan/config/pull/154
    • Add release notes for 3.1.0 by @DavidePastore in https://github.com/hassankhan/config/pull/157

    New Contributors

    • @nbayramberdiyev made their first contribution in https://github.com/hassankhan/config/pull/149

    Full Changelog: https://github.com/hassankhan/config/compare/3.0.1...3.1.0

    Source code(tar.gz)
    Source code(zip)
  • 3.0.1(Mar 26, 2022)

    What's Changed

    • Fix merge by @DavidePastore in https://github.com/hassankhan/config/pull/147
    • Add release notes for 3.0.1 by @DavidePastore in https://github.com/hassankhan/config/pull/148

    Full Changelog: https://github.com/hassankhan/config/compare/3.0.0...3.0.1

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Dec 30, 2021)

    Added

    • Move CI to GitHub actions (#132, #136 and #137)
    • PHP 8.0 support, adding it to the build matrix (#138 and #139)
    • PHP 8.1 support, adding it to the build matrix (#135, #140 and #141)
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Dec 7, 2020)

    Added

    • Serialization support (#127)
    • Support for Properties files (#128)

    Fixed

    • Test enhancement (#126)
    • Typehint on Xml parser, parse method (#130)
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Sep 1, 2019)

  • 2.0.2(Apr 6, 2019)

  • 2.0.1(Feb 2, 2019)

  • 1.1.0(Aug 22, 2018)

  • 1.0.1(Mar 31, 2018)

  • 1.0.0(Mar 3, 2018)

    Added

    • Merge support (#96)
    • Set PHP 5.5.9 as minimum required version (#75 and #99)

    Fixed

    • Fix PHP 5.6 test (#100)
    • Edit PHP versions tested on Travis (#101)
    • Add more info about the symfony/yaml requirement (#97 and #102)

    Breaking changes

    • PHP 5.3 and 5.4 are no longer supported.
    Source code(tar.gz)
    Source code(zip)
Owner
Hassan Khan
Developer Advocate @cubedevinc
Hassan Khan
A better YAML configuration file management virion for PocketMine-MP 4

BetterConfig WARNING: This virion is under development and haven't been tested. Do not use this virion unless you know what you're doing. Contribution

KygekTeam International 1 Apr 30, 2022
This library can parse a TypeSchema specification either from a JSON file, or from PHP classes using reflection and annotations.

This library can parse a TypeSchema specification either from a JSON file, or from PHP classes using reflection and annotations. Based on this schema it can generate source code and transform raw JSON data into DTO objects. Through this you can work with fully typed objects in your API for incoming and outgoing data.

Apioo 54 Jul 14, 2022
SurfShark Shadowsocks/Clash Config Generator

Instructions This script was written to build a proxy list of Surfshark service servers. Change Host2Ip for bypass censorship To work with the script,

Alireza Ahmand 18 Sep 26, 2022
Simple yet expressive schema-based configuration library for PHP apps

league/config helps you define nested configuration arrays with strict schemas and access configuration values with dot notation.

The League of Extraordinary Packages 282 Jan 6, 2023
LOAD is a PHP library for configuration loading to APCu

LOAD LOAD is a PHP library for configuration loading to APCu Sources Available sources for configuration loading are: PHP file Consul Environment vari

Beat Labs 4 Jan 18, 2022
An object-oriented option parser library for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking

GetOptionKit Code Quality Versions & Stats A powerful option parser toolkit for PHP, supporting type constraints, flag, multiple flag, multiple values

Yo-An Lin 140 Sep 28, 2022
Yaml Configuration support for CakePHP 3

implements most of the YAML 1.2 specification using Symfony Yaml Component to CakePHP 3 for parsing config files

Borhaneddine Guemidi 11 Nov 10, 2020
Map request on your DTO object with zero configuration.

Map request on your DTO object with zero configuration. Install composer require prugala/symfony-request-dto Usage Create a DTO that implements the in

Piotr Rugala 16 Dec 30, 2022
Symfony Dotenv parses .env files to make environment variables stored in them accessible via getenv(), $_ENV, or $_SERVER.

Dotenv Component Symfony Dotenv parses .env files to make environment variables stored in them accessible via $_SERVER or $_ENV. Getting Started $ com

Symfony 3.5k Jan 5, 2023
The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function that you can use instead of var_dump().

VarDumper Component The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function t

Symfony 7.1k Dec 23, 2022
A beautiful, fully open-source, tunneling service - written in pure PHP

Expose A completely open-source ngrok alternative - written in pure PHP. Documentation For installation instructions, in-depth usage and deployment de

Beyond Code 3.9k Dec 29, 2022
All PHP functions, rewritten to throw exceptions instead of returning false

Safe PHP This project is deprecated Because of how this project needs to be in sync with the official PHP documentation, maintaining a set of function

TheCodingMachine 2.1k Jan 2, 2023
PHP client library for the Square Connect APIs

Square Connect PHP SDK - RETIRED replaced by square/square-php-sdk NOTICE: Square Connect PHP SDK retired The Square Connect PHP SDK is retired (EOL)

Square 113 Dec 30, 2022
A PHP parser for TOML

TOML parser for PHP A PHP parser for TOML compatible with TOML v0.4.0. Support: Installation Requires PHP >= 7.1. Use Composer to install this package

Yo! Symfony 175 Dec 26, 2022
Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.

PHP dotenv Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically. Why .env? You should never store sensitive credentials

Vance Lucas 12.3k Jan 7, 2023
AWS SDK with readable code and async responses

AsyncAws client If you are one of those people that like the Amazon PHP SDK but hate the fact that you need to download Guzzle, PSR-7 and every AWS AP

Async AWS 375 Dec 24, 2022
Provide CSV, JSON, XML and YAML files as an Import Source for the Icinga Director and optionally ship hand-crafted additional Icinga2 config files

Icinga Web 2 Fileshipper module The main purpose of this module is to extend Icinga Director using some of it's exported hooks. Based on them it offer

Icinga 25 Sep 18, 2022
CrateKeyShopGUI Pocketmine-MP plugin which can be set in Config.yml file

CrateKeyShopGUI CrateKeyShopGUI Pocketmine-MP plugin which can be set in Config.yml file Depend FormAPI EconomyAPI PiggyCrate InvCrashFix Download Dow

null 4 Jan 7, 2022
phalcon config loader for yaml

Phalcon Config Loarder for Yaml Loads all the yml in the directory of the app/config. Version PHP: 7.0.x, 7.1.x, 7.2.x Phalcon: 3.x Composer { "r

Toshiyuki Ienaga 2 Oct 7, 2022