lawondyss/config

创建自定义配置类的基类。比关联数组更好用 :-)

2.0.2 2023-11-12 11:34 UTC

This package is auto-updated.

Last update: 2024-09-12 13:24:16 UTC


README

创建自定义配置类的基类。比关联数组更好用 :-)

安装

通过 Composer

composer require lawondyss/config

使用

class DbConfig extend Lawondyss\Config
{
  public string $driver;
  public string $host;
  public string $database;
  public string $username;
  public string $password;
  public string $charset;
}

$dbConfig = DbConfig::fromArray([
  'driver' => 'mysqli',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'root',
  'password' => 'root',
  'charset' => 'utf8'
]);

简单获取和设置单个选项。

$charset = $dbConfig->charset;
$dbConfig->charset = 'latin1';

实现数组访问。

$pass = $dbConfig['password']; 
$dbConfig['password'] = '*****';

如果需要默认值,则在类中定义。

class DbConfig extend Lawondyss\Config
{
  public string $driver = 'mysqli';
  public string $host = 'localhost';
  public string $database;
  public string $username;
  public string $password;
  public string $charset = 'utf8';
}

$defaultConfig = new DbConfig;

可以与自定义选项合并。

$lipsumDbConfig = $defaultConfig->withOptions([
  'database' => 'lipsum',
  'username' => 'lorem',
  'password' => 'ipsum',
]);

如果其他代码将选项作为关联数组使用

$dibi = new Dibi\Connection($lipsumDbConfig->toArray());

许可

MIT