jzkf/yii2-helpers

A collection of helper functions for Yii2 framework

Installs: 9

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Type:yii2-extension

pkg:composer/jzkf/yii2-helpers

2.0.5 2025-12-20 10:47 UTC

This package is auto-updated.

Last update: 2025-12-20 11:57:51 UTC


README

一个为 Yii2 框架提供的辅助函数集合包。

安装

通过 Composer 安装

composer require jzkf/yii2-helpers

本地开发安装

如果你想在本地开发中使用这个包,可以在项目的 composer.json 中添加:

{
    "repositories": [
        {
            "type": "path",
            "url": "/path/to/yii2-helpers"
        }
    ],
    "require": {
        "jzkf/yii2-helpers": "*"
    }
}

然后运行:

composer require jzkf/yii2-helpers

使用

安装后,所有函数会自动加载,无需手动引入。函数在全局命名空间中可用。

示例

// 判断是否为成人
if (is_adult('110101199001011234')) {
    echo "是成人";
}

// 获取环境变量
$debug = is_debug();

// 判断是否为微信
if (is_wechat()) {
    echo "微信浏览器";
}

// 生成 UUID
$uuid = uuid();

// 格式化字节大小
echo format_bytes(1024); // 输出: 1 KB

// 分转元
echo cent_to_yuan(10000); // 输出: 100.00

// 安全输出手机号
echo mask_phone_number('13800138000'); // 输出: 138****8000

函数分类

数组操作

  • is_multi_dimensional_array($array) - 判断是否为多维数组
  • generate_tree($items, $parent_id, $childKey, $primaryKey) - 递归生成树形结构
  • assoc_array_unique($arr, $key) - 根据键删除二维数组中的重复项

字符串处理

  • substr_utf8($string, $length, $etc) - UTF-8 安全截取字符串
  • remove_empty_lines($text) - 删除空行
  • remove_style_attributes($text) - 删除 style 属性
  • mask_id_card($id_number) - 安全输出身份证号
  • mask_phone_number($phone_number) - 安全输出手机号
  • empty_to_null($string) - 字符串为空转为null

环境判断

  • is_debug() - 是否调试模式
  • is_dev() - 是否开发环境
  • is_prod() - 是否生产环境
  • is_wechat() - 是否微信浏览器
  • is_wechat_mini_program() - 是否微信小程序
  • parse_user_agent($user_agent) - 解析用户代理信息

工具函数

  • env($key, $default) - 获取环境变量
  • uuid() - 生成 UUID
  • generate_uuid($version, $namespace, $name) - 生成指定版本的 UUID
  • format_bytes($bytes, $precision) - 格式化文件大小
  • cent_to_yuan($num, $scale) - 分转换为元
  • yuan_to_cent($num, $scale) - 元转换为分
  • generate_slug($length) - 生成随机字符串
  • mask_digits_or_string($input, $start, $length, $mask) - 安全输出字符

其他函数

  • get_client_ip($return_str) - 获取客户端IP
  • is_json_string($stringData) - 校验JSON字符串
  • array_to_html_table($data, $tableOptions, $head_type) - 数组生成HTML表格
  • dd($var) - 调试输出并终止程序

设置相关函数

这些函数依赖 \common\services\SettingService 类。如果该类不存在,函数会返回默认值:

  • get_setting($key, $default) - 获取系统设置
  • get_site_name() - 获取站点名称
  • get_template_path() - 获取模板主题
  • get_pc_theme() - 获取PC主题
  • get_h5_theme() - 获取H5主题

注意:如果你的项目中没有 SettingService 类,这些函数仍然可以工作,但会返回默认值。你可以在项目中实现 SettingService 类来提供实际的设置值。

依赖

  • PHP >= 8.1.0
  • Yii2 >= 2.0.45
  • ramsey/uuid >= 4.2
  • mobiledetect/mobiledetectlib >= 4.8.06

可选依赖

  • \common\services\SettingService - 用于设置相关的函数(如果不存在,函数会返回默认值)

开发

项目结构

yii2-helpers/
├── src/
│   └── functions.php    # 所有辅助函数
├── composer.json        # Composer 配置
├── README.md           # 说明文档
└── .gitignore         # Git 忽略文件

许可证

BSD-3-Clause

支持

如有问题或建议,请提交 Issue 或 Pull Request。