phoole/config

A slim configuration loader library for PHP.

1.1.0 2019-11-19 07:06 UTC

This package is auto-updated.

Last update: 2024-04-19 16:44:51 UTC


README

Build Status Scrutinizer Code Quality Code Climate PHP 7 Latest Stable Version License

A slim configuration loader library for PHP. It loads PHP, JSON, YAML config files, easy to use, yet powerful. It requires PHP 7.2+ and is compliant with PSR-1, PSR-4, PSR-12.

Installation

Install via the composer utility.

composer require "phoole/config=1.*"

or add the following lines to your composer.json

{
    "require": {
       "phoole/config": "1.*"
    }
}

Features

  • Simple interface, get($id), has($id), with($id, $value).

  • 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
    
  • May use an environment value, such as production or production/host1 for switching between different configurations.

  • Use of references in configuration value is fully supported, such as ${system.tmpdir}.

  • Get environment values using $config->get('ENV.USER') or ${ENV.USER}

  • Hierarchy configuration structure with dot notation like db.auth.host.

  • Support .php, .json, .yml(need yaml extension installed) type of config files.

Usage

  • Use environment value

    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 central config/ 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 Phoole\Config\Config;
    use Phoole\Env\Environment;
    
    // load server environment from '.env' file
    (new Environment())->load(__DIR__ . '/.env');
    
    // create config instance with the config file loader
    $config = new Config(getenv('CONFIG_DIR'), getenv('APP_ENV'));
    
    // object access of $config
    $db_config = $config->get('db');
  • 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 holds system.* configurations

      // system.php
      return [
          'tmpdir' => '/usr/local/tmp',
          // ...
      ];

      Later, system related configs can be retrieved as

      $dir = $config->get('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 (assume config files are *.php),

      1. config/config/*.php

      2. config/production/*.php

      3. config/production/host1/*.php

      Configuration values are overwritten and replaced those from later loaded files.

  • Use of references

    References make your configuration easy to manage.

    For example, in the system.php

    return [
        'tmpdir' => '/var/local/tmp',
        ...
    ];

    In your cache.php file,

    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('%{', '}%');
  • Access environment values

    Environment values can be accessed through special node 'ENV'. e.g.

    $tmpdir = $config->get('ENV.APP_TMPDIR');

    or in reference format,

    return [
        'tmpdir' => '${ENV.APP_TMPDIR}'
    ];
  • DOT notation

    Hierarchy 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'
    ];
  • After initial loading, $config is immutable. If you want to add new conf values. You may use,

    $newconf = $config->with('redis', ['host' => 'localhost']);

    where $newconf is a new configuration object.

APIs

  • ConfigInterface API

    • get(string $id): mixed

      The return value might be a string, array, or even object. Returns null if not found.

    • has(string $id): bool

      Test if $id exists or not. Returns a boolean value.

    • with(string $id, mixed $value): Config

      Returns a new config object with $id set.

  • ReferenceInterface API

    • setReferencePattern(string $start, string $end): $this

      Reset the reference start chars and ending chars. The default are '${' and '}'

Testing

$ composer test

Dependencies

  • PHP >= 7.2.0

License