codezero/configurator

此包已被废弃,不再维护。没有建议的替代包。

将配置数据注入到您的类中

3.0.1 2015-02-05 16:18 UTC

This package is auto-updated.

Last update: 2020-09-11 05:29:49 UTC


README

Build Status Latest Stable Version Total Downloads License

此包允许您轻松地将配置文件注入到自己的类中。

安装

下载此包或通过Composer安装

"require": {
	"codezero/configurator": "3.*"
}

用法

定义配置

指定一个数组...

$config = [
    'my_setting' => 'some value',
    'my_other_setting' => 'some other value'
];

或引用一个配置文件...

$config = '/path/to/configFile.php';

该配置文件可能看起来像这样

<?php
return [
    'my_setting' => 'some value',
    'my_other_setting' => 'some other value'
];

在您的类中使用Configurator

在您的类中注入一个Configurator实现。如果没有提供,将实例化默认的一个。`$configurator->load()`方法将返回一个Configuration对象,如果无法加载有效的数组,则抛出ConfigurationException

use CodeZero\Configurator\Configurator;
use CodeZero\Configurator\DefaultConfigurator;

class MyClass {

    private $config;

    public function __construct($config, Configurator $configurator = null)
    {
        $configurator = $configurator ?: new DefaultConfigurator();
        $this->config = $configurator->load($config);
    }
}

实例化您的类

创建您类的实例,传入配置数组或文件

$myClass = new MyClass($config);

在您的类中使用Configuration

获取配置值

$mySetting = $this->config->get('my_setting');
$myOtherSetting = $this->config->get('my_other_setting');

在运行时设置配置值

$this->config->set('my_setting', 'some new value');

就这样...

Laravel 5 使用

IoC 绑定

如果您使用Laravel,则可以设置一个绑定,它会自动解析带有其配置的类。假设您有一个类Acme\MyApp\MyClass

App::bind('Acme\MyApp\MyClass', function($app)
{
	// Specify an array...
    $config = [
        'my_setting' => 'some value',
        'my_other_setting' => 'some other value'
    ];

	// Or refer to a configuration file...
	$config = '/path/to/configFile.php';

    return new \Acme\MyApp\MyClass($config);
});

使用Laravel的Config基础设施

如果您不想在绑定中硬编码数组或文件路径,而是想使用Laravel的Config基础设施怎么办?让我们假设您在config/myapp.php中创建了一个Laravel配置文件。您可以在绑定中使用这个文件

$config = $app['config']->get("myapp");

就这么简单...

Analytics