PHP code example of qs9000 / think-uuidv7
1. Go to this page and download the library: Download qs9000/think-uuidv7 library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
qs9000 / think-uuidv7 example snippets
return [
'think\\Service' => qs9000\\thinkuuidv7\\Service::class,
];
return [
// 缓存驱动 (对应 config/cache.php 中的 stores)
'driver' => env('UUIDV7_DRIVER', 'file'),
// 分片 ID (0-255),每个服务器设置唯一值
'shard_id' => (int) env('UUIDV7_SHARD_ID', 0),
// Redis 序列号 key 前缀
'key_prefix' => env('UUIDV7_KEY_PREFIX', 'uuidv7:seq'),
];
use qs9000\thinkuuidv7\UuidV7Facade as Uuidv7;
// 生成单个 UUID
$uuid = Uuidv7::generate();
// "0191a51a-b2c3-7d89-0123-456789abcdef"
// 获取 UuidV7 对象
$uuidObj = Uuidv7::make();
echo $uuidObj->getUuid(); // UUID 字符串
echo $uuidObj->getTimestampMs(); // 时间戳 (毫秒)
echo $uuidObj->getShardId(); // 分片 ID
echo $uuidObj->getDatetime()->format('Y-m-d H:i:s.u'); // DateTime 对象
// 批量生成
$uuids = Uuidv7::makeBatch(100);
// 验证 UUID
if (Uuidv7::validate($uuid)) {
// ...
}
// 提取时间戳
$timestamp = Uuidv7::timestamp($uuid); // 毫秒时间戳
$datetime = Uuidv7::datetime($uuid); // DateTimeImmutable 对象
// 解析完整信息
$uuidObj = Uuidv7::parse($uuid);
// UUID 字符串转二进制(写入数据库)
$binary = Uuidv7::toBinary($uuid);
// "\x01\x91\xa5\x1a\xb2\xc3..."
// 二进制转 UuidV7 对象(从数据库读取)
$uuidObj = Uuidv7::fromBinary($binary);
use qs9000\thinkuuidv7\UuidV7Type;
class User extends Model
{
protected $type = [
'id' => UuidV7Type::class,
];
}
use think\migration\Migrator;
class CreateUsersTable extends Migrator
{
public function up(): void
{
$table = $this->table('users');
$table->addColumn('id', 'binary', ['limit' => 16]) // 16 字节
->addColumn('name', 'string')
->create();
}
}
// 从 UUID 提取时间戳
$uuid = '0191a51a-b2c3-7d89-0123-456789abcdef';
$timestamp = Uuidv7::timestamp($uuid); // 1776503423651
// .env
UUIDV7_SHARD_ID=0
// config/cache.php
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
// ...
],
],
// .env
UUIDV7_DRIVER=redis
bash
# 生成单个 UUID
php think uuidv7
# 生成批量 UUID
php think uuidv7 -n 10
# 生成指定 shard_id 的 UUID
php think uuidv7 -s 5