uuid扩展及实现思路

uuid扩展介绍

生成唯一标识码,这个标识码是128位无符号整数,由五个16进制组成,五个之间使用破折号进行连接
应用在分布式系统中,记录用户信息唯一标识值、多商户唯一标识符、或者是需要唯一码的需求功能

安装使用

官方地址
https://github.com/ramsey/uuid
官方文档
https://uuid.ramsey.dev/en/latest/

composer require ramsey/uuid=3.9.3

//加载第三方类库
use Ramsey\Uuid\Uuid;
//调用uuid类
$uuid = Uuid::uuid4();
//输出生成的uuid码
echo $uuid->toString();

uuid4方法的实现思路

random_bytes函数配合bin2hex()函数使用
random_bytes 返回任意字节字符串,ascii值
bin2hex 把ASCII字符串转换为十六进制值

echo bin2hex(random_bytes(16));

uuid4方法源码分析

UuidFactory类中uuid4方法

public function uuid4(){
    //$this->randomGenerator属性获取RandomBytesGenerator对象调用generate方法
    //generate这个方法调用random_bytes(16)方法
    //生成ascii字符串
    $bytes = $this->randomGenerator->generate(16);
    
    //把ASCII字符串转换为十六进制值
    $hex = bin2hex($bytes);    
    
    //处理hex数据
    return $this->uuidFromHashedName($hex, 4);
}

//下面方法就是生成uuid标识符的主要方法
protected function uuidFromHashedName($hash, $version){    
    $timeHi = BinaryUtils::applyVersion(substr($hash, 12, 4), $version);    
    $clockSeqHi = BinaryUtils::applyVariant(hexdec(substr($hash, 16, 2)));    
    
    $fields = [ 'time_low' => substr($hash, 0, 8),    'time_mid' => substr($hash, 8, 4),    'time_hi_and_version' => str_pad(dechex($timeHi), 4, '0', STR_PAD_LEFT),    'clock_seq_hi_and_reserved' => str_pad(dechex($clockSeqHi), 2, '0', 
STR_PAD_LEFT),    'clock_seq_low' => substr($hash, 18, 2),    'node' => substr($hash, 20, 12),];

    return $this->uuid($fields);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值