Home > Article > PHP Framework > How Laravel generates a four-digit unique invitation code based on user ID
The following tutorial column will introduce to you how Laravel generates a four-digit unique invitation code based on the user ID. I hope it will be helpful to friends in need! Create a new file app/Services/InviteCodeService.php
<?php namespace App\Services;// 邀请码服务class InviteCodeService{
protected $key,$num;
public function __construct()
{
$this->key = 'abcdefghjkmnpqrstuvwxyz123456789';
// 注意这个key里面不能出现数字0 否则当 求模=0 会重复的
// 多少进制
$this->num = strlen($this->key);
}
// 传递用户id生成唯一邀请码
public function enCode(int $user_id)
{
$code = ''; // 邀请码
while ($user_id > 0) { // 转进制
$mod = $user_id % $this->num; // 求模
$user_id = ($user_id - $mod) / $this->num;
$code = $this->key[$mod] . $code;
}
$code = str_pad($code, 4, '0', STR_PAD_LEFT); // 不足用0补充
return $code;
}
// 邀请码获取用户id 一般都不需要用到
function deCode($code)
{
if (strrpos($code, '0') !== false)
$code = substr($code, strrpos($code, '0') + 1);
$len = strlen($code);
$code = strrev($code);
$user_id = 0;
for ($i = 0; $i key, $code[$i]) * pow($this->num, $i);
return $user_id;
}}
Editapp/Providers/AppServiceProvider.php
use App\Services\InviteCodeService;
public function register()
{
$this->app->singleton('invite_code',InviteCodeService::class);
}
Test uniqueness
$max_num = 200000;
$codes = [];
for ($i = 1; $i enCode($i);
$i = 1;
foreach ($codes as $code){
$userId = app('invite_code')->deCode($code); // 邀请码获取用户id
if( $userId != $i)
dd("邀请码解密错误".$i);
$i++;
}
$unique_count = count(array_unique($codes));
dd($unique_count); // 不重复的总数
20w
There is no duplication of data, and the invitation code solution
is also correct. Note
$this->key There cannot be duplicate strings. For example: c Repeat. ##About $this->key// $this->key = 'abcdefghjkmnpqrstuvwxyz123456789'; // 没打乱的$this->key = 'kh8sjpdazetnmb5yw7rq4gc9fuv3216x'; // 打乱的
$this->key There is no limit to the length, but it is best not to be too short.
user id is 4 to the third power (256) What will happen if it exceeds 256? The invitation code becomes only 5 digits... , not good-looking. For user experience, don’t add i
$this->key These letters are easy to confuse users. i : l
l : 1
o : 0 (Of course 0
cannot appear) is very similar.
Ps
ExampleAssume
For example: User ID
255
256 The invitation code is 5 digits. 500 The invitation code is 5 digits.
......(So if there is a limit on the number of invitation codes, you will know what to do if you are smart)
What is the maximum user ID with a 4-digit hexadecimal invitation code?
BullshitBecause I wanted to use the invitation code function, my first reaction was:
The above is the detailed content of How Laravel generates a four-digit unique invitation code based on user ID. For more information, please follow other related articles on the PHP Chinese website!