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);
}