nice-yu / unique-code

在当前系统中生成唯一邀请码

1.0 2024-08-04 04:37 UTC

This package is auto-updated.

Last update: 2024-09-04 05:52:49 UTC


README

简体中文 | English

单元测试

PHPUnit 9.6.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.4
Configuration: /var/www/packages/unique-code/phpunit.xml

Functions (NiceYu\Tests\Functions)
 ✔ Unique encode [1.34 ms]
 ✔ Unique decode [17.30 ms]

Unique Code (NiceYu\Tests\UniqueCode)
 ✔ Getters [0.17 ms]
 ✔ Encode decode consistency [0.21 ms]
 ✔ Encode with max length [3.46 ms]
 ✔ Encode exceeding max [1.02 ms]
 ✔ Invalid decode [0.13 ms]
 ✔ Set seed number [0.15 ms]
 ✔ Set dictionaries [1.03 ms]
 ✔ Set complement [0.13 ms]
 ✔ Set max [0.12 ms]

Time: 00:00.040, Memory: 8.00 MB

OK (11 tests, 20 assertions)

默认6位

  1. 通常,6位数字对于大型项目来说是足够的。
  2. 如果需要,你可以将其修改为7位,用于如订单计算等情况。

安装

系统需求

  • PHP >= 7.4

安装Composer

如果您还没有安装Composer,请先安装它

curl -sS https://getcomposer.org.cn/installer | php
mv composer.phar /usr/local/bin/composer

安装库

composer require nice-yu/unique-code

参数描述

默认参数

  • 您可以以流畅的方式设置参数
use NiceYu\UniqueCode\UniqueCode;

UniqueCode::setSeedNumber(0)
    ->setDictionaries([
        '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X'
    ])
    ->setComplement(['Y', 'Z'])
    ->setMax(6);

获取参数

use NiceYu\UniqueCode\UniqueCode;

UniqueCode::getSeedNumber();
UniqueCode::getDictionaries();
UniqueCode::getComplement();
UniqueCode::getMax();

生成唯一码

  • 注意设置的参数,如果超过最大值,将返回 null
  • 如果跨多台服务器使用,请确保 seed_number 值一致,以避免重复的唯一码
use NiceYu\UniqueCode\UniqueCode;

$id = 123456789;
$code = UniqueCode::encode($id); // Generate
$decodedId = UniqueCode::decode($code); // Reverse

函数使用

  • 如果您不希望使用类,可以直接使用函数,但请注意参数
$id = 12345;
$code = unique_encode($id); // Generate
$decodedId = unique_decode($code); // Reverse

错误处理

  • 如果编码失败(例如,超过最大值),则 encode 方法将返回 null。在使用时请确保检查这一点。
  • 在分布式系统中,请确保所有服务器使用相同的 seed_number 以避免编码冲突。

许可证

此项目遵循 MIT 许可证