unicity/unicity

此包已被废弃且不再维护。未建议替代包。

生成数据库友好GUID的库

0.1.3 2017-08-30 10:14 UTC

This package is auto-updated.

Last update: 2024-01-07 19:38:46 UTC


README

Build Status Scrutinizer Code Quality Code Coverage

简介

Unicity库用于生成全局唯一ID,并确保以下特性:

  • 高(但可控制)的熵/随机度
    • 这是为了避免ID猜测攻击所必需的。
  • 时间相关的ID(可控精度,合适的内部表示)
    • 使用合适的内部表示(大端模式)的时间相关ID是帮助我们保持数据库中插入顺序的良好助手。
    • 此外,使用时间相关的ID可以让我们使用B-Tree索引,而无需几乎每次插入时都重新创建索引,从而避免随机性。
  • 可以使用多种格式表示ID,包括紧凑的二进制字符串
    • Base64
    • 适应URL使用的Base64
    • 十六进制
    • 二进制字符串(最紧凑的形式,理想地保证小数据库索引)

安装

通过composer安装,就这样

composer require unicity/unicity

代码示例

工厂

<?php

use Unicity\GUIDFactory;

// A good place to start is to instantiate a factory that will help us to create
// or to unserialize GUIDs following the specified constraints.
// 

// The first parameter tells us how many timestamp-related bytes we want to use
//   (from 4 to 7 bytes, by default 7)
// The second parameter tells us how many randomness bytes we want to use
//   (from 2 to 9 bytes, by default 9)
$guidFactory = new \Unicity\GUIDFactory(5, 7);

一个需要注意的重要点是,为了测试和依赖注入的目的,你应该使用 Unicity\Interfaces\GUIDFactory 接口进行类型提示。

同样的规则也适用于GUID实例,最好是使用 Unicity\Interfaces\GUID 接口进行类型提示。

创建新的GUID实例

<?php

// This will create a completely new GUID following the constraints specified in the factory constructor
$newGUID = $guidFactory->create();

反序列化GUID

<?php

// This will unserialize (and validate) a GUID from an hexadecimal string
$recoveredGUID = $guidFactory->fromHexString('1234567890ab1234567890ab');

// This will unserialize (and validate) a GUID from a base64 string
$recoveredGUID = $guidFactory->fromBase64String('EjRWeJCrEjRWeJCr');

// This will unserialize (and validate) a GUID from a base64 (modified for URLs) string
$recoveredGUID = $guidFactory->fromBase64UrlString('EjRWeJCrEjRWeJCr');

// This will unserialize (and validate) a GUID from a binary bytes stream
$recoveredGUID = $guidFactory->fromBinaryString('1234567890ab');

序列化GUID

<?php

$hexString = $newGUID->asHexString();
$base64String = $newGUID->asBase64String();
$base64urlString = $newGUID->asBase64UrlString();
$bytesStream = $newGUID->asBinaryString();

比较GUID

<?php

if (!$requestGUID->equals($dbGUID)) {
    // block request
}