44

使用PHP生成通用唯一识别码(UUID)

 5 years ago
source link: https://www.helloweba.net/php/569.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

查看演示 下载源码

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

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

安装

我们使用composer来安装uuid库。

composer require ramsey/uuid

使用

首先require自动加载文件,然后直接调用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。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK