better / nanoid
PHP 版本的 nanoid 的副本
0.0.1
2020-09-21 15:29 UTC
Requires
- php: >=7.1
This package is not auto-updated.
Last update: 2024-09-26 17:01:23 UTC
README
概述
替换 hidehalo/nanoid-php 以支持 PHP 7.1+
一个小巧(179字节)、安全且适合URL的唯一字符串ID生成器,用于JavaScript
安全。它使用加密强随机API,并保证了符号的正确分布。
小巧。仅179字节(压缩后)。无依赖。它使用Size Limit来控制大小。
紧凑。它使用的符号比UUID(A-Za-z0-9_-)多,并且在只有21个符号中就有与36个符号相同数量的唯一选项。
安装
通过Composer
composer require better/nanoid
用法
正常
主要模块使用URL友好的符号(A-Za-z0-9_-),并返回一个21个字符的ID(以具有与UUID v4相同的碰撞概率)。
use Better\Nanoid\Client; use Better\Nanoid\GeneratorInterface; $client = new Client(); # default random generator echo $client->produce($size = 32); # more secure generator with more entropy echo $client->produce($size = 32, true);
自定义字母表或长度
$client = new Client('0123456789abcdefg'); $client->produce();
字母表必须包含256个符号或更少。否则,生成器将不安全。
自定义随机字节生成器
# PS: anonymous class is new feature when PHP_VERSION >= 7.0 $client = new Client(); echo $client->produceUsing(new class implements GeneratorInterface { /** * @inheritDoc */ public function random(int $size): string { $ret = []; while ($size--) { $ret[] = mt_rand(0, 255); } return $ret; } });
random
回调必须接受数组大小并返回一个包含随机数字的数组。
致谢
许可
MIT 许可证(MIT)。请参阅 许可文件 以获取更多信息。