tr33m4n/utilities

基本工具集合

v1.3.2 2021-11-16 10:08 UTC

This package is auto-updated.

Last update: 2024-09-12 20:44:55 UTC


README

用于在其他模块中使用的基本工具类集合。

\tr33m4n\Utilities\Data\DataCollection

一个简单的、可迭代的用于存储数据的集合

  • $dataCollection->set 将一个项目设置到数据集合中
  • $dataCollection->get 从数据集合中获取一个项目
  • $dataCollection->add 将一个键值对数组添加到数据集合中
  • $dataCollection->has 检查一个项目是否存在于数据集合中
  • $dataCollection->setAll 批量设置项目到数据集合中
  • $dataCollection->getAll 获取所有针对数据集合设置的项

也可以在实例化时传递一个项目数组来填充数据集合。集合也可以迭代,例如

<?php

$dataCollection = new DataCollection([
    'test1' => 'test1',
    'test2' => 'test2'
]);

/**
 * Or 
 * 
 * $dataCollection = DataCollection::from([
 *      'test1' => 'test1',
 *      'test2' => 'test2'
 * ]);
 */

foreach ($dataCollection as $key => $value) {
    echo "$key : $value\n";
}

\tr33m4n\Utilities\Config\ConfigProvider

一个简单的配置解析器和提供者。这个类继承了一个数据集合的所有功能,然而当这个类被实例化时,它将配置文件聚合到一个嵌套的配置集合结构中。配置路径可以通过构造函数传递或通过设置全局常量 ROOT_CONFIG_PATH 定义。当解析文件时,ROOT_CONFIG_PATH 路径将始终优先,所以如果你在构造函数路径和全局路径中有一个同名配置文件,全局的将覆盖它。

配置提供者附带了一个PHP文件适配器 \tr33m4n\Utilities\Config\Adapter\PhpFileAdapter。在实例化类时可以传递一个替代文件适配器。

使用默认适配器的典型配置文件可能看起来像

<?php
// Filename: test1.php

return [
    'test1' => 'test1',
    'test2' => 123,
    'test3' => [
        'test1' => 'test1',
        'test2' => 123,
        'test3' => [
            'test1' => 'test1',
            'test2' => [
                'test1' => 'deep_value'
            ],
            'test3' => [
                'test1' => 'test1'
            ]
        ]
    ]
];

在解析这个配置结构时,文件名将被用作根数组的键,每个数组项将被转换为一个新的 \tr33m4n\Utilities\Config\ConfigCollection,这看起来可能像

[
    'test1' => new ConfigCollection([
        'test1' => 'test1',
        'test2' => 123,
        'test3' => new ConfigCollection([
            'test1' => 'test1',
            'test2' => 123,
            'test3' => new ConfigCollection([
                'test1' => 'test1',
                'test2' => new ConfigCollection([
                    'test1' => 'deep_value'
                ]),
                'test3' => new ConfigCollection([
                    'test1' => 'test1'
                ])
            ])
        ])
    ])
];

这些值可以通过数据集合的 get 方法访问。例如

<?php

$deepValue = $this->configProvider->get('test1')
    ->get('test3')
    ->get('test3')
    ->get('test2')
    ->get('test1');

// $deepValue = 'deep_value'

为了方便,还提供了一个全局辅助函数 config,它允许访问配置提供者的单个实例(在注册表中设置)。使用这个方法访问 deep_value 可能看起来像

<?php

$deepValue = config('test1')->get('test3')
    ->get('test3')
    ->get('test2')
    ->get('test1');

// $deepValue = 'deep_value'