Hashids 是一個用于生成短、唯一的非連續ID的庫,它可以將整數(如數據庫中的自增ID)轉換為唯一的字符串。在 PHP 中,你可以使用 hashids/hashids
這個包來實現這個功能。
首先,安裝 Hashids:
composer require hashids/hashids
接下來,我們來看一下 Hashids 的基本用法:
<?php
require_once 'vendor/autoload.php';
use Hashids\Hashids;
$hashids = new Hashids();
$id = 12345;
$hash = $hashids->encode($id); // 轉換為字符串
echo $hash . PHP_EOL; // 輸出字符串
$decodedId = $hashids->decode($hash)[0]; // 解碼回整數
echo $decodedId . PHP_EOL; // 輸出整數
現在,我們來分析 Hashids 的源碼。首先,創建一個新的 Hashids 實例時,會傳入一些參數,如下所示:
public function __construct(
string $salt = '',
int $minHashLength = 0,
string $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
) {
// ...
}
$salt
:用于加密的鹽值,可以為空。$minHashLength
:生成的哈希字符串的最小長度。$alphabet
:用于生成哈希字符串的字符集。接下來,我們來看一下 encode()
和 decode()
方法的實現。這里只列出關鍵部分:
public function encode(...$numbers): string
{
// ...
while (count($numbers)) {
$number = array_shift($numbers);
$buffer = '';
do {
$buffer .= $this->alphabet[$number % $this->alphabetLength];
$number = ($number - ($number % $this->alphabetLength)) / $this->alphabetLength;
} while ($number > 0);
$result = strrev($buffer) . $result;
}
// ...
return $result;
}
public function decode(string $hash): array
{
// ...
$hashArray = str_split(strrev($hash));
foreach ($hashArray as $i => $char) {
$number += strpos($this->alphabet, $char) * pow($this->alphabetLength, $i);
}
// ...
return $result;
}
encode()
方法將整數轉換為字符串,它首先計算余數并將其添加到緩沖區,然后將結果反轉并與之前的結果拼接。decode()
方法則是將字符串反轉后,計算每個字符在字母表中的位置,然后將其相加得到原始整數。
修改建議:
$hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()');
$hashids = new Hashids('my_salt');
$hashids = new Hashids('', 10);
總之,Hashids 是一個很好的庫,可以幫助你生成短、唯一的非連續ID。你可以根據需要對其進行修改和優化。