UUID是通用唯一识别码(通用唯一标识符)的缩写。目的是让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要通过中央控制端来做辨识信息的指定。这样的话,每个人都可以创建不与其它人冲突的UUID,于是就不需考虑数据库创建时的名称重复问题。

UUID是由一组32位数的16进制数字所构成,是故UUID理论上的总数为16 ^ 32 = 2 ^ 128,约等于3.4 x 10 ^ 38。也就是说若每纳秒产生1兆个UUID,要花100亿年才会将所有UUID用完.UUID重复几率非常非常低,是故大可不必考虑重复冲突的问题。

像的Java和Python的都有专门库函数生成UUID,PHP也有第三方库可以用来生成UUID。

安装

我们使用的作曲家来安装UUID库。

composer require ramsey/uuid

使用

首先需要自动加载文件,然后直接调用UUID方法。

require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

try {

    // Generate a version 1 (time-based) UUID object
    $uuid1 = Uuid::uuid1();
    echo $uuid1->toString() . "\n"; // i.e. e4eaaaf2-d142-11e1-b3e4-080027620cdd

    // Generate a version 3 (name-based and hashed with MD5) UUID object
    $uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'helloweba.net');
    echo $uuid3->toString() . "\n"; // i.e. 11a38b9a-b3da-360f-9353-a5a725514269

    // Generate a version 4 (random) UUID object
    $uuid4 = Uuid::uuid4();
    echo $uuid4->toString() . "\n"; // i.e. 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a

    // Generate a version 5 (name-based and hashed with SHA1) UUID object
    $uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'helloweba.net');
    echo $uuid5->toString() . "\n"; // i.e. c4a760a8-dbcf-5254-a0d9-6a4474bd1b62

} catch (UnsatisfiedDependencyException $e) {

    // Some dependency was not met. Either the method cannot be called on a
    // 32-bit system, or it can, but it relies on Moontoast\Math to be present.
    echo 'Caught exception: ' . $e->getMessage() . "\n";

}

UUID有4个版本的算法,根据需求可以采用不同的算法.UUID可以用在产品序列号,拼接路径,服务器上的图片/文件名称,甚至订单号等。

该项目在github上上的地址为:HTTPS://github.com/ramsey/uuid。

本文转载于helloweba.   原文地址:https://www.helloweba.net/php/569.html

原文链接:https://www.jocat.cn/archives/8078,转载请注明出处。
0
显示验证码
没有账号?注册  忘记密码?