Code Monkey home page Code Monkey logo

config's Introduction

Config

Join our Community Become a Sponsor One-time Donation
Latest Stable Version Total Downloads License

PHP library for simple configuration management -- Created by Chris Kankiewicz (@PHLAK)


Introduction

Config is a simple PHP configuration management library supporting multiple configuration file formats and an expressive API.

Supported file formats:

  • PHP
  • INI
  • JSON
  • TOML
  • YAML
  • XML

Requirements

Install with Composer

composer require phlak/config

Initializing the Client

First, import Config:

use PHLAK\Config\Config;

Then instantiate the class:

$config = new Config($context, $prefix = null);

Where $context is one of the following:

  • A path to a supported file type
  • A directory path containing one or more supported file types
  • An array of configuration options

And $prefix is a string to be used as a key prefix for options of this Config object.

Configuration File Formats

PHP

A PHP configuration file must have the .php file extension, be a valid PHP file and and return a valid PHP array.

Example PHP file
<?php

return [
    'driver' => 'mysql',
    'drivers' => [
        'sqlite' => [
            'database' => 'database.sqlite',
            'prefix' => ''
        ],
        'mysql' => [
            'host' => 'localhost',
            'database' => 'blog',
            'username' => 'blogger',
            'password' => 'hunter2',
            'charset' => 'utf8',
            'prefix' => ''
        ]
    ]
];

INI

An INI configuration file must have the .ini file extension and be a valid INI file.

Example INI file
driver = mysql

[drivers]

sqlite[database] =  database.sqlite
sqlite[prefix] =

mysql[host] = localhost
mysql[database] = blog
mysql[username] = blogger
mysql[password] = hunter2
mysql[charset] = utf8
mysql[prefix] =

JSON

A JSON configuration file must have the .json file extension and contain a valid JSON object.

Example JSON file
{
    "driver": "mysql",
    "drivers": {
        "sqlite": {
            "database": "database.sqlite",
            "prefix": ""
        },
        "mysql": {
            "host": "localhost",
            "database": "blog",
            "username": "blogger",
            "password": "hunter2",
            "charset": "utf8",
            "prefix": ""
        }
    }
}

TOML

A TOML configuration file must have the .toml file extension and be a valid TOML file.

Example TOML file
driver = 'mysql'

[drivers.sqlite]
database = 'database.sqlite'
prefix = ''

[drivers.mysql]
host = 'localhost'
database = 'blog'
username = 'blogger'
password = 'hunter2'
charset = 'utf8'
prefix = ''

YAML

A YAML configuration file must have the .yaml file extension, be a valid YAML file.

Example YAML file
driver: mysql

drivers:

  sqlite:
    database: database.sqlite
    prefix:

  mysql:
    host: localhost
    database: blog
    username: blogger
    password: hunter2
    charset: utf8
    prefix:

XML

A XML configuration file must have the .xml file extension and contain valid XML.

Example XML file
<?xml version='1.0'?>

<database>
    <driver>mysql</driver>
    <drivers>
        <sqlite>
            <database>database.sqlite</database>
            <prefix></prefix>
        </sqlite>
        <mysql>
            <host>localhost</host>
            <database>blog</database>
            <username>blogger</username>
            <password>hunter2</password>
            <charset>utf8</charset>
            <prefix></prefix>
        </mysql>
    </drivers>
</database>

Usage

__construct

Create a new Config object.

Config::__construct( mixed $context [, string $prefix = null ] ) : Config
$context
Raw array of configuration options or path to a configuration file or directory containing one or more configuration files
$prefix
A key under which the loaded config will be nested

Examples

Create a new Config object from a YAML file.

$config = new Config('path/to/conifg.yaml');

Create a new Config object from a directory of config files.

$config = new Config('path/to/conifgs/');

Create a new Config object from an array.

$config = new Config([
    'hostname' => 'localhost',
    'port' => 12345
]);

set

Store a config value with a specified key.

Config::set( string $key, mixed $value ) : bool
$key
Unique configuration option key
$value
Config item value

Example

$config->set('hostname', 'localhost');
$config->set('port', 12345);

get

Retrieve a configuration option via a provided key.

Config::get( string $key [, mixed $default = null ] ) : mixed
$key
Unique configuration option key
$value
Config item value

Examples

// Return the hostname option value or null if not found.
$config->get('hostname');

Define a default value to return if the option is not set.

// Returns 'localhost' if hostname option is not set
$config->get('hostname', 'localhost');

has

Check for the existence of a configuration item.

Config::has( string $key ) : bool
$key
Unique configuration option key

Example

$config = new Config([
    'hostname' => 'localhost'
]);

$config->has('hostname'); // Returns true
$config->has('port');     // Returns false

append

Append a value onto an existing array configuration option.

Config::append( string $key, mixed $value ) : bool
$key
Unique configuration option key
$value
Config item value

Example

Append baz to the tags config item array.

$config->set('tags', ['foo', 'bar'])
$config->append('tags', 'baz'); // ['foo', 'bar', 'baz']

prepend

Prepend a value onto an existing array configuration option.

Config::append( string $key, mixed $value ) : bool
$key
Unique configuration option key
$value
Config item value

Example

Prepend baz to the tags config item array.

$config->set('tags', ['foo', 'bar'])
$config->append('tags', 'baz'); // ['baz', 'foo', 'bar']

unset

Unset a configuration option via a provided key.

Config::unset( string $key ) : bool
$key
Unique configuration option key

Example

$config->unset('hostname');

load

Load configuration options from a file or directory.

Config::load( string $path [, string $prefix = null [, bool $override = true ]] ) : self
$path
Path to configuration file or directory
$prefix
A key under which the loaded config will be nested
$override
Whether or not to override existing options with values from the loaded file

Examples

Load a single additional file.

$conifg->load('path/to/config.php');

Load an additional file with a prefix.

$config->load('databaes.php', 'database');

Load an additional file without overriding existing values.

$config->load('additional-options.php', null, false);

merge

Merge another Config object into this one.

Config::merge( Config $config [, bool $override = true ] ) : self
$config
Instance of Config
$override
Whether or not to override existing options with values from the merged config object

Examples

Merge $anotherConfig into $config and override values in $config with values from $anotherConfig.

$anotherConfig = new Config('some/config.php');

$config->merge($anotherConfig);

Merge $anotherConfig into $config without overriding any values. Duplicate values in $anotherConfig will be lost.

$anotherConfig = new Config('some/config.php');

$config->merge($anotherConfig, false);

split

Split a sub-array of configuration options into it's own Config object.

Config::split( string $key ) : Config
$key
Unique configuration option key

Example

$config = new Config([
    'foo' => 'foo',
    'bar' => [
        'baz' => 'barbaz'
    ],
]);

$barConfig = $config->split('bar');

$barConfig->get('baz');  // Returns 'barbaz'

toArray

Return the entire configuration as an array.

Config::toArray( void ) : array

Example

$config = new Config(['foo' => 'foo']);

$config->toArray(); // Returns ['foo' => 'foo']

Troubleshooting

For general help and support join our GitHub Discussion or reach out on Twitter.

Please report bugs to the GitHub Issue Tracker.

Copyright

This project is liscensed under the MIT License.

config's People

Contributors

brutto avatar dependabot-preview[bot] avatar dependabot[bot] avatar externaluse avatar peter279k avatar phlak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

config's Issues

Invalid .json Syntax & Error Handling

I'm using this in a couple of WordPress plugins. It would be nice if it not throw an Exception if the file syntax is invalid. Example:

$config = new Config\Config('/path/to/app/config.json');

If config.json has invalid syntax, it throws a nasty exception.

I'm not sure how I would address this, but maybe you could return an Exception() object if there is an error. I'm just brainstorming...

$config = new Config\Config('/path/to/app/my_config.json');

if( is_object( $config ) && get_class( $config ) == 'Exception' ) {
  // Let the user know
  echo $config->GetMessage();
} else {
  // Do magical things
}

Better maybe better?:

$config = new Config\Config('/path/to/app/my_config.json');

if( $result = $config->get_error() ) {
  // Show some sort of pretty panel/notice
  echo 'An error has occurred: ' . $result;
} else {
  // Do magical things
}

Thank you,
Daniel

Invalid JSON syntax exception

8.3 & 8.4

Can you add support for 8.3 and 8.4 is only a few months away so keep this in mind too.

Upgrade symfony/yaml

Hello,
could you please upgrade symfony/yaml in your library?
from:
"symfony/yaml": "^3.0 || ^4.0 || ^5.0",
to:
"symfony/yaml": "^3.0 || ^4.0 || ^5.0 || ^6.0",
Because now it doesn't allow us to use latest symfony/yaml v6.0 and php 8.2
Thanks!

Index arrays in config is not overrided correctly

Hello!
Trying to use your lib, but faced a problem:

require 'vendor/autoload.php';

use PHLAK\Config\Config;

$array1 = [
	'assoc_key' => 'testvalue',
	'key' => [1,2,3,4],
];
$array2 = [
	'assoc_key' => 'override',
	'key' => ['somevalue'],
];

$config1 = new Config($array1);
$config2 = new Config($array2);
print_r($config1->merge($config2)->toArray());

It returns:

Array
(
    [assoc_key] => override
    [key] => Array
        (
            [0] => somevalue
            [1] => 2
            [2] => 3
            [3] => 4
        )

)

But should return:

Array
(
    [assoc_key] => override
    [key] => Array
        (
            [0] => somevalue
        )

)

Append/prepend values onto a config array item

$config = new Config([
    'whitelist' => [
        'ips' => [
            '127.0.0.1',
            '192.168.0.1'
        ]
    ]
]);

$config->append('whitelist.ips', '10.10.0.1');

Should result in

[
    'whitelist' => [
        'ips' => [
            '127.0.0.1',
            '192.168.0.1',
            '10.10.0.1'
        ]
    ]
]

This should also be able to accept an array of values.

Improve InvalidFileException messages

Currently InvalidFileException does not contain a message when thrown. This could be improved by including the name of or path to the file which is invalid. See #2

For example:

Invalid file detected at $path

or

Unable to parse file at $path

'Config' Namespace

I'm wondering if using the namespace Config could run into conflicts.

Perhaps Phlak\Config?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.