工具模块
kuiper/helper 是 Kuiper 框架的基础工具包,提供框架全量使用的配置容器(Config)、环境变量读取函数(env() / env_bool())与一组数组、字符串、枚举工具类。它不依赖框架其他包,可以被任何项目单独引入。
特性
- 点路径配置容器:
Config支持点路径读写嵌套数组,{XXX}占位符引用其他配置项 - 严格的环境变量读取:
env()保持默认值类型,env_bool()对非法布尔字面量显式抛异常 - 数组工具集:
Arrays覆盖分组、映射、抽取、展平、对象互转等高频操作 - 字符串工具集:
Text提供驼峰/蛇形转换、前后缀判断、截断等 - 枚举工具:
EnumHelper按 backing value 或名称取枚举值 - 可注入 trait:
ConfigAwareTrait/JsonSerializableTrait可复用到业务类
快速开始
点路径读写配置
Config 是一个支持点路径的配置容器,实现 ConfigInterface:
<?php
declare(strict_types=1);
use kuiper\helper\Config;
$config = Config::create([
'application' => [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
'servers' => ['web1', 'web2'],
],
]);
$config->get('application.database.host'); // 'localhost'
$config->get('application.database.host', 'db'); // 'localhost'(存在时不取默认值)
$config->get('application.cache.driver', 'array'); // 'array'(不存在时取默认值)
$config->has('application.database.host'); // true
// 下标语法混用:servers[0] 等价于 servers.0
$config->get('application.servers[0]'); // 'web1'
// 类型化取值:按强转语义转换(见 configuration.md)
$config->getInt('application.database.port'); // 3306
$config->getBool('application.database.host'); // true(非空非 '0' 字符串)
// 写入与追加速度
$config->set('application.cache.driver', 'redis');读取环境变量
框架配置文件统一用 env() 读取环境变量。注意它是函数,要用 use function 导入:
<?php
declare(strict_types=1);
use function kuiper\helper\env;
use function kuiper\helper\env_bool;
return [
'application' => [
'debug' => env_bool('APP_DEBUG', false),
'workers' => env('APP_WORKERS', 4),
],
];<?php
declare(strict_types=1);
use function kuiper\helper\env;
use function kuiper\helper\env_bool;
// env(): $_ENV → $_SERVER → getenv() 顺序取值;未设置时返回默认值(保留类型)
$level = env('LOGGING_LEVEL', 'info'); // 未设置时是字符串 'info'
// env_bool(): 只接受合法布尔字面量,非法值抛 InvalidArgumentException
$debug = env_bool('APP_DEBUG', false); // '1'/'true'/'on'/'yes' → true
// '0'/'false'/'off'/'no'/'' → false
// 'false '(带空格、大小写不敏感) 也能解析
// 'enable' 等非法值 → 抛异常,而不是当成 trueenv_bool() 的严格语义是刻意设计:"false"、"off" 这类字符串用宽松 (bool) 转换都会变成 true,配置写错会静默反转行为;非法字面量直接抛异常能把错误拦在启动期。
格式化异常信息
<?php
declare(strict_types=1);
use function kuiper\helper\describe_error;
try {
// ...
} catch (\Throwable $e) {
$logger->error(describe_error($e));
// 输出形如 "RuntimeException: boom in /app/src/Service.php:42"
}组件总览
Config 与 ConfigInterface
点路径配置容器,读写、类型化取值、三种合并策略、占位符替换。详见配置指南。
env() / env_bool() / describe_error()
定义在 kuiper\helper\functions.php,全局函数,建议 use function 导入。
| 函数 | 签名 | 行为要点 |
|---|---|---|
env() | env(string $name, bool|int|float|string|null $default = null) | 取值顺序 $_ENV → $_SERVER → getenv();命中时返回字符串;未设置返回默认值(保留类型)。php-fpm / php -S 的 variables_order 默认不含 E,超全局数组里没有环境变量,因此最后回落 getenv() |
env_bool() | env_bool(string $name, bool $default = false) | 未设置返回默认值;已设置按字面量解析(大小写不敏感、忽略首尾空白):1/true/on/yes 为真,0/false/off/no/空串 为假,其余抛 InvalidArgumentException |
describe_error() | describe_error(\Throwable $error): string | 格式化为 类名: 消息 in 文件:行号 |
Arrays
纯静态方法工具类,常用于把列表数据整形为业务需要的结构:
| 方法 | 说明 |
|---|---|
isEmpty() / isNotEmpty() | null 安全的空判断(接受 \Countable|array|null) |
assoc() / assocByField() | 以某字段(或回调结果)为键重建关联数组 |
toMap() | 以字段值或回调结果为键构建值映射 |
groupBy() / groupByField() | 按字段(或回调结果)分组 |
pull() / pullField() | 从列表中抽取某个键(或字段)组成新数组 |
select() / selectField() | 保留指定键(对象或数组皆可) |
exclude() / rename() | 排除键 / 重命名键 |
flatten() | 多维数组展平(可指定深度、保留键) |
filter() | 去除空值条目 |
toArray() | 对象转数组(可包含 getter、蛇形键名、递归) |
assign() | 把数组批量赋值到对象属性 |
merge() | 深合并多个数组 |
snakeCaseKeys() / mapKeys() | 批量转换键名 |
⚠️ *Field 变体只读对象属性:assocByField() / groupByField() / pullField() 用 is_object($elem) && isset($elem->$name) 取值,元素是数组时得到 null 或空键——数组元素用不带 Field 的版本(assoc() / groupBy() / pull(),按键名取)。
<?php
declare(strict_types=1);
use kuiper\helper\Arrays;
// 数组元素:按键名取,用不带 Field 的版本
$rows = [
['id' => 1, 'name' => 'alice', 'dept' => 'eng'],
['id' => 2, 'name' => 'bob', 'dept' => 'eng'],
['id' => 3, 'name' => 'carol', 'dept' => 'ops'],
];
Arrays::assoc($rows, 'id'); // [1 => [...], 2 => [...], 3 => [...]]
Arrays::groupBy($rows, 'dept'); // ['eng' => [...], 'ops' => [...]]
Arrays::pull($rows, 'name'); // ['alice', 'bob', 'carol']
// 对象元素:读对象属性,用 *Field 版本
$users = [new User(id: 1, name: 'alice'), new User(id: 2, name: 'bob')];
Arrays::assocByField($users, 'id'); // [1 => User#1, 2 => User#2]
Arrays::pullField($users, 'name'); // ['alice', 'bob']Text
| 方法 | 说明 |
|---|---|
stringify() | 任意值转字符串(数组用 print_r 形式,对象取 __toString 等) |
camelCase() / snakeCase() | 驼峰 ↔ 蛇形转换(可指定分隔符) |
startsWith() / endsWith() | 前后缀判断(默认忽略大小写) |
lower() / upper() | 大小写转换(多字节安全,默认 UTF-8) |
underscore() / humanize() | 下划线化 / 人类可读化 |
isInteger() / isEmpty() / isNotEmpty() | 类型与空判断 |
truncate() | 按最大长度截断并加省略号 |
EnumHelper
<?php
declare(strict_types=1);
use kuiper\helper\EnumHelper;
enum Status: string
{
case Active = 'active';
case Inactive = 'inactive';
}
EnumHelper::tryFrom(Status::class, 'active'); // Status::Active
EnumHelper::tryFrom(Status::class, 'deleted'); // null(不存在时返回默认值)
EnumHelper::tryFrom(Status::class, 1); // null(backing 类型不匹配)
EnumHelper::fromName(Status::class, 'Active'); // Status::Active(按 case 名)
EnumHelper::tryFromName(Status::class, 'Nope'); // null
EnumHelper::hasName(Status::class, 'Active'); // truetryFrom()按 backing value 取值:类型不匹配或不存在返回$default;非 backed 枚举抛InvalidArgumentExceptionfromName()按 case 名取值,不存在时抛InvalidArgumentException- 反射结果进程内缓存(枚举定义运行期不变)
ConfigAwareInterface / ConfigAwareTrait
业务类实现 ConfigAwareInterface 并 use ConfigAwareTrait,即可获得 setConfig() 注入入口(框架装配时自动注入):
<?php
declare(strict_types=1);
namespace App\Service;
use kuiper\helper\ConfigAwareInterface;
use kuiper\helper\ConfigAwareTrait;
use kuiper\helper\ConfigInterface;
class PricingService implements ConfigAwareInterface
{
use ConfigAwareTrait;
public function taxRate(): float
{
return $this->config->getFloat('application.tax.rate', 0.06);
}
}ComposerJson
读取并解析项目 composer.json 为 Config 对象:
<?php
declare(strict_types=1);
use kuiper\helper\ComposerJson;
$config = ComposerJson::read(); // 自动向上查找最近的 composer.json
$name = $config->get('name'); // 'kuiper/helper'detect() 从给定目录(默认当前目录)逐级向上找 composer.json,找不到时抛 InvalidArgumentException。
JsonSerializableTrait
给 DTO 补齐 \JsonSerializable 实现的公共 trait(kuiper 内部不使用,供外部项目复用):toArray() 遍历对象属性,\DateTimeInterface 属性格式化为 Y-m-d H:i:s,jsonSerialize() 直接复用 toArray();子类可覆盖 formatPropertyName() 自定义键名输出。
与其他模块的关系
- 框架所有
*Configuration类读取配置都通过ConfigInterface(依赖注入模块的装配层注入) - runtime 模块 把
$_ENV/$_SERVER注入配置的ENV.*命名空间,配置文件里可用{ENV.FOO}占位符引用环境变量