sergeymakinen/yii2-config

This package is abandoned and no longer maintained. No replacement package was suggested.

Versatile config loader for Yii 2

v2.1.0 2018-02-12 18:40 UTC

This package is auto-updated.

Last update: 2021-02-15 21:12:36 UTC


README

Versatile config loader for Yii 2. You can define a single config definition file in your favorite language which will define a configuration for all your application tiers (console, backend, frontend, etc).

Code Quality Build Status Code Coverage SensioLabsInsight

Packagist Version Total Downloads Software License

Table of contents

Installation

The preferred way to install this extension is through composer.

Either run

composer require "sergeymakinen/yii2-config:^2.0"

or add

"sergeymakinen/yii2-config": "^2.0"

to the require section of your composer.json file.

Usage

First you need to define your config: it may be a PHP array right in the file you plan to include it in but it's better to place it in a file which can be in any supported format. Just like it's done in the example.

Then your entry scripts have to be modified to load the config. It's how it can look like for a console tier yii file (consider a tier as a type) in a Yii 2 basic project template:

#!/usr/bin/env php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';

$config = sergeymakinen\yii\config\Config::fromFile(__DIR__ . '/config/config.php', ['tier' => 'console']);

$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

And for a backend tier backend/web/index.php file in a Yii 2 advanced application template:

<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';

$config = sergeymakinen\yii\config\Config::fromFile(__DIR__ . '/../../common/config/config.php', ['tier' => 'backend']);

(new yii\web\Application($config))->run();

Example config

Consider this config:

<?php

return [
    'configDir' => __DIR__,
    'cacheDir' => dirname(__DIR__) . '/runtime/config',
    'enableCaching' => YII_ENV_PROD,
    'dirs' => [
        '',
        '{env}',
    ],
    'files' => [
        [
            'class' => 'sergeymakinen\yii\config\PhpBootstrapLoader',
            'path' => 'bootstrap.php',
        ],
        'common.php',
        '{tier}.php',
        'web:@components.urlManager.rules' => 'routes.php',
        '@components.log.targets' => 'logs.php',
        '@params' => 'params.php',
    ],
];

Config will look for the following config files in CONFIG_DIR and CONFIG_DIR/ENV directories:

  • bootstrap.php and bootstrap-local.php for a PHP code
  • common.php and common-local.php
  • TIER.php and TIER-local.php
  • routes.php and routes-local.php when the tier is web will be merged as:
[
    'components' => [
        'urlManager' => [
            'rules' => [
                // routes.php and routes-local.php contents
            ]
        ]
    ]
]
  • logs.php and logs-local.php will be merged as:
[
    'components' => [
        'log' => [
            'targets' => [
                // logs.php and logs-local.php contents
            ]
        ]
    ]
]
  • params.php and params-local.php when the tier is web will be merged as:
[
    'params' => [
        // params.php and params-local.php contents
    ]
]

Shortcuts

As you can see in the example section there are different ways to specify a config file configuration. To be able to write less, some common options can be written in a single string instead of an array.

'TIER:ENV@KEY' => 'PATH' will be resolved as (you can omit any part you don't need):

[
    'tier' => 'TIER',
    'env' => 'ENV',
    'key' => 'KEY',
    'path' => 'PATH',
]

Samples:

Shortcut Result
'bar'
[
    'path' => 'bar',
]
'foo' => 'bar'
[
    'env' => 'foo',
    'path' => 'bar',
]
'foo@baz' => 'bar'
[
    'env' => 'foo',
    'key' => 'baz',
    'path' => 'bar',
]
'loren:foo@baz' => 'bar'
[
    'tier' => 'loren',
    'env' => 'foo',
    'key' => 'baz',
    'path' => 'bar',
]

Supported config formats

INI

Extension: ini

Loader class: sergeymakinen\yii\config\IniLoader

Example:

[config]
class = yii\db\Connection
dsn = "mysql:host=localhost;dbname=yii2basic"
username = root
password = ""
charset = utf8

JSON

Extension: json

Loader class: sergeymakinen\yii\config\JsonLoader

Example:

{
    "class": "yii\\db\\Connection",
    "dsn": "mysql:host=localhost;dbname=yii2basic",
    "username": "root",
    "password": "",
    "charset": "utf8"
}

PHP array

Extension: php

Loader class: sergeymakinen\yii\config\PhpArrayLoader

Example:

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2basic',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];

PHP bootstrap

Extension: php

Loader class: sergeymakinen\yii\config\PhpBootstrapLoader

Attention: you need to explicitly set the class name to use this loader:

[
    'class' => 'sergeymakinen\config\PhpBootstrapLoader',
    'path' => 'mybootstrapfile.php',
    // ...
]

Example:

<?php

Yii::$container->set(yii\grid\GridView::class, function ($container, $params, $config) {
    if (Yii::$app->controller instanceof yii\debug\controllers\DefaultController) {
        $defaults = [];
    } else {
        $defaults = [
            'layout' => '<div class="table-responsive">{items}</div><div class="grid-view-footer clearfix"><div class="pull-left">{summary}</div><div class="pull-right">{pager}</div></div>',
            'tableOptions' => ['class' => 'table table-striped'],
        ];
    }
    return new yii\grid\GridView(array_merge($defaults, $config));
});

YAML

Extension: yml, yaml

Loader class: sergeymakinen\yii\config\YamlLoader

Attention: you need to install the Symfony YAML library:

Either run

composer require "symfony/yaml:^2.8 || ^3.2"

or add

"symfony/yaml": "^2.8 || ^3.2"

to the require section of your composer.json file.

Example:

class: 'yii\db\Connection'
dsn: 'mysql:host=localhost;dbname=yii2basic'
username: root
password: ''
charset: utf8

Extending

For example let's try to write a simple XML loader:

use yii\helpers\Json;

class XmlLoader extends sergeymakinen\yii\config\ArrayLoader
{
    /**
     * {@inheritdoc}
     */
    public function loadFile($path)
    {
        $xml = simplexml_load_string(file_get_contents($path), 'SimpleXMLElement', LIBXML_NOCDATA);
        return Json::decode(Json::encode($xml));
    }
}

If you wish to use the loader automatically for XML files then add the following entry to the loaders property array of Config:

'xml' => 'XmlLoader'