hassankhan / config

Config is a lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files
MIT License
971 stars 136 forks source link

Request: Enhancement (group by file name when Multiple File load) #73

Open tmgast opened 8 years ago

tmgast commented 8 years ago

Regarding an old issue #18:

It was asked how to handle when multiple config files share a variable name.

If you're loading in multiple config files, wouldn't it make more sense to contain each loaded file as its own array within the config container?

loading files:
- config/environment.php
- config/services.php
- config/database.php

These should be accessible in the following way:

$app->config = new Config(__DIR__ . '/../config');
$app->config->get('environment.name'); // the name variable is returned from the environment config
$app->config->get('database.server'); // the server variable is returned from the database config

Currently, all the config options are mashed together in a single array, which overwrites any duplicates.

Example: server.php

<?php

return [
    "system" => "debian",
    "apache" => [
        "location" => "/usr/bin/apache"
    ]
];

environments.php

<?php

return [
    "local" => [
        "domain" => "dev"
    ],
    "production" => [
        "domain" => "domain.com"
    ]
];

Outputs:

{
    "local":{
        "domain":"dev"
    },
    "production":{
        "domain":"domain.com"
    },
    "system":"debian",
    "apache":{
        "location":"\/usr\/bin\/apache"
    }
}

However, I would like it to output:

{
    "environments":{
        "local":{
            "domain":"dev"
        },
        "production":{
            "domain":"domain.com"
        },
    },
    "server": {
        "system":"debian",
        "apache":{
            "location":"\/usr\/bin\/apache"
        }
    }
}
hassankhan commented 8 years ago

Hi, currently it should work if you manually pass in each file to the constructor, passing directories is not currently supported. Good idea for the future though.

marcuschaplais commented 8 years ago

@tmgast You can do this with https://github.com/m1/vars fyi

hassankhan commented 8 years ago

As I said before, would be a great idea for the next version. Another idea is you could have a main config.php that is something like this:

<?php

return [
    'server' => require_once('server.php'),
    'environments' => require_once('environments.php')
]
samrap commented 7 years ago

You might want to take a look at https://github.com/samrap/gestalt .

It is a lot more flexible on how it loads configurations from files and even allows you to define custom loaders using an interface. It solves the multiple variable names by using the filename(s) as the root key(s) and nesting the values inside.