PHP中通過Hashids將整數(shù)轉(zhuǎn)化為唯一字符串
需要在前臺隱藏 ID 的話,可以考慮使用此產(chǎn)品,生成的 id 比較高大上,比較像 Youtube、Youku、Weibo之類的 id 名,比如:XNjkxMTc0MDQ4
官網(wǎng):http://hashids.org/php/Laravel 5 包:https://github.com/vinkla/hashids
PHP中的簡單實(shí)用示例:
$hashids = new HashidsHashids(’this is my salt’);$id = $hashids->encode(1, 2, 3);$numbers = $hashids->decode($id);
當(dāng)然,包很全,還有 Composer package、Laravel 4 package、Laravel 5 package、CodeIgniter spark、Symfony bundle、Kohana module、Wordpress plugin、CakePHP component、Silex package、Craft plugin featu等等。在官網(wǎng)可以找到鏈接
還支持 JavaScript, Ruby, Python, Java, Scala, PHP, Perl, Swift, Objective-C, C, C++11, Go, Lua, Elixir, ColdFusion, Groovy, Kotlin, Nim, VBA, CoffeeScript and for Node.js & .NET 語言
Laravel 5 使用
使用比較簡單,而且文檔說明得已經(jīng)比較詳細(xì)了。
按文檔說明安裝完包后,執(zhí)行
php artisan vendor:publish
操作來生成配置文件,配置文件路徑:confighashids.php:
’alphabet’=> ’your-alphabet-string’
配置項是你打算讓加密后的字符串里出現(xiàn)什么字符,我用的是 A-Z、a-z、0-9,后來發(fā)現(xiàn)好像與字符順序有關(guān)系,生成出來的隨機(jī)字符串大小寫與數(shù)字分布不太均勻,就使用 PHP 的 shuffle() 函數(shù)打亂一下順序生成了一組新的 alphabet,之后看起來就比較高大上了。
使用示例:
// You can alias this in config/app.php.use VinklaHashidsFacadesHashids;Hashids::encode(4815162342);// We’re done here - how easy was that, it just works!Hashids::decode(’doyouthinkthatsairyourebreathingnow’);// This example is simple and there are far more methods available.
相關(guān)文章:
