jameslevi / silhouette
是一个支持多种配置文件格式的简单配置管理库。
v1.0.1
2021-05-06 18:05 UTC
Requires
- php: >=5.3.0
- jameslevi/objectify: ^1.0
- jameslevi/string: ^1.0
This package is not auto-updated.
Last update: 2024-09-20 11:08:07 UTC
README
是一个支持多种配置文件格式的简单配置管理库。
功能
- 支持 php 数组和 json 格式。
- 提供了一个门面实现,以便优雅地访问配置数据。
- 易于与其他框架集成,甚至无需框架。
安装
- 您可以通过 composer 安装。
composer require jameslevi/silhouette
- 在您的代码的上部包含自动加载器。
require_once __DIR__.'/vendor/autoload.php';
入门
- 将配置类导入到您的项目中。
use Graphite\Component\Silhouette\Config;
- 在 php 或 json 中创建一个新的配置文件。但在这个例子中,让我们尝试一个返回数组的 php 文件。
<?php return [ 'enable' => true, 'port' => 3306, 'host' => 'localhost', 'username' => 'root', 'password' => 'abcd', 'database' => 'users', 'max-rows' => 10000, ];
- 实例化一个新的配置对象。
$db = new Config(__DIR__ . "/config/db.php");
- 您现在可以使用 "get" 方法获取数据。
$db->get('enable'); // This will return true.
您也可以使用对象键获取数据。
$db->username; // This will return "root".
- 您也可以将新值添加到配置中。
$db->add('charset', 'utf-8'); // This will add "charset" as new config data.
- 您可以使用 "set" 方法编辑配置数据。
$db->set('database', 'photos'); // This will change the value of the key database.
您也可以使用对象键设置数据。
$db->database = 'photos'; // This will change the value of database from "users" to "photos".
- 您可以使用 "has" 方法检查关键字是否存在。
$db->has('password'); // Returns true.
- 您可以使用 "remove" 方法删除配置数据。
$db->remove('enable'); // This will remove "enable" from your configuration object.
- 您可以将配置数据返回为数组。
$db->toArray();
- 您还可以返回配置数据的 json 格式。
$db->toJson();
配置注入
您还可以创建一个不加载配置文件的配置对象。
$db = new Config([ 'enable' => true, 'port' => 3306, 'host' => 'localhost', 'username' => 'root', 'password' => 'abcd', 'database' => 'users', 'max-rows' => 10000, ]);
门面
- 创建一个扩展 silhouette 门面类的类,然后通过传递配置路径来覆盖父构造函数。
<?php namespace App\Config; use Graphite\Component\Silhouette\Facade; class DB extends Facade { public function __construct() { parent::__construct('config/db.php'); } }
- 您现在可以通过调用它的静态方法来获取每个配置。
DB::enable() // Returns the value of enable property.
您必须调用蛇形命名的属性,将其转换为驼峰式。
DB::maxRows() // Returns the value 10000.
- 您可以通过提供方法调用的第一个参数来编辑配置值。
DB::enable(false) // Change the value of "enable" to false.
- 您可以使用配置 "上下文" 来添加、编辑或删除配置数据。
DB::context()->add('min_rows', 100); // This will add new configuration property. DB::context()->set('min_rows', 110); // This will set the value of "min_rows". DB::context()->remove('min-rows'); // This will remove "min_rows" from the data object.
静默配置对象
仅返回数据的配置对象。
// Create a new database configuration object. $config = new Config(__DIR__ . '/config/db.php', true); // You cannot add new data to your muted configuration. $config->add('driver', 'mysql');
您还可以在门面中静默配置对象。
<?php namespace App\Config; use Graphite\Component\Silhouette\Facade; class DB extends Facade { public function __construct() { parent::__construct('config/db.php', true); } }
贡献
有关问题、担忧和建议,您可以通过 nerdlabenterprise@gmail.com 发送电子邮件给 James Crisostomo。
许可
此软件包是一个开源软件,许可协议为 MIT 许可。