alopez / php-configuration-loader
一个简单的PHP类,旨在简化配置文件的处理。
v1.0.0
2017-04-05 17:41 UTC
Requires
- php: >=7.0
Requires (Dev)
- mikey179/vfsstream: ^1.6
- phpunit/phpunit: ^6.0
This package is not auto-updated.
Last update: 2024-09-20 20:31:28 UTC
README
配置加载器是一个类,允许您浏览配置目录并轻松获取PHP配置文件中的值。
安装
只需使用以下命令行
composer require alopez/php-configuration-loader
基本用法
在这个包中,您需要了解三个类
ConfigurationLoader
:主要类,用于加载并返回数据。SingleConfiguration
:一个简单的容器,用于存储您的值。GroupConfiguration
:一个容器,可以被命名并包含多个SingleConfiguration对象。
配置对象
单例和组配置都有两个属性:name
和value
。这两个类之间的唯一区别在于GroupConfiguration是为了包含多个SingleConfiguration定义而设计的,下面是一个示例
// A random configuration file lost in your directories $name = 'foo'; $value = 'fooValue'; return new \ConfigurationLoader\SingleConfiguration($name, $value);
如果您有多个设置(例如:多个数据库访问),则声明一个GroupConfiguration将很有用
// Databases definitions use ConfigurationLoader\GroupConfiguration; use ConfigurationLoader\SingleConfiguration; $name = 'db'; return new GroupConfiguration($name, [ new SingleConfiguration('database1', [ 'host' => 'bla', 'user' => 'bla', 'password' => 'bla', 'bla' => 'bla' ] ), new SingleConfiguration('database2', [ 'host' => 'bla2', 'user' => 'bla2', 'password' => 'bla2', 'bla' => 'bla2' ] ) ] );
配置加载器
配置加载器可以很容易地声明,无需任何参数。您可以指定配置目录,并精确指定一个标志(默认为true),以告诉实例自动分析整个目录。如果此标志设置为“false”,配置目录的数据将通过get()
方法(见以下示例)可用。否则,您必须通过load
方法加载它。
使用SingleConfiguration实例的示例
$loader = new \ConfigurationLoader\ConfigurationLoader($configPath, $lazyOrNot); // The path must be considering that the current directory is your conf folder, // You must not precise '.php' extension. $filepath = 'path/to/your/file/without/.extension'; // If not lazy you have to load the file (it will also return the values you want to get) // Let's say you want to load the file containing our newly created 'foo' SingleConfiguration: $data = $loader->load($filepath); // will echo 'fooValue' var_dump($data); // Once data is already load you can use get in order to get the configuration // It also will return 'fooValue' $data = $loader->get('foo')
使用GroupConfiguration实例(假设加载器已经声明为延迟加载)
$loader->load('dbconf'); $data = $loader->get('db'); var_dump($data); // var_dump will return a formatted array with the following format: array( 'database1' => array(...), 'database2' => array(...) )
注意:如果您将加载器声明为带延迟加载标志的true
,但稍后仍想加载数据,则可以使用loadDirectory
方法,该方法将加载构造函数中指定的目录。
处理本地文件
加载器能够区分.local.php
文件和.php
文件。如果您创建foo.php
和foo.local.php
,则load
方法将首先获取foo.local.php
的内容,并忽略foo.php
。
// foo.php return new \ConfigurationLoader\SingleConfiguration('foo', 'foo'); // foo.local.php return new \ConfigurationLoader\SingleConfiguration('foo', 'bar'); // index.php $loader = new \ConfigurationLoader\ConfigurationLoader($configPath); $loader->load('foo'); // will return 'bar' var_dump($loader->get('foo'));