<?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 < $len; $i++)
            $user_id += strpos($this->key, $code[$i]) * pow($this->num, $i);
        return $user_id;
    }


}

laravel绑定到容器

编辑 app/Providers/AppServiceProvider.php

    use App\Services\InviteCodeService;
    public function register()
    {
        $this->app->singleton('invite_code',InviteCodeService::class);
    }

测试唯一性

      $max_num = 200000;

        $codes = [];
        for ($i = 1; $i <= $max_num; $i++)
            $codes[] =  app('invite_code')->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);  // 不重复的总数

要注意的

  • $this->key 不能出现数字 0
  • $this->key 不能有重复的字符串。 如: abccd c 重复。
  • $this->key 顺序可以打乱.

    // $this->key = 'abcdefghjkmnpqrstuvwxyz123456789'; // 没打乱的
    $this->key = 'kh8sjpdazetnmb5yw7rq4gc9fuv3216x'; // 打乱的
  • $this->key 长度不限制,但是最好别太短。

abcd: 最大的 用户id 是 4 的 3 次方 (256)超过 256 会怎么样?邀请码变成 5 位而已 ……. , 不好看。

  • 为用户体验,$this->key 字符串别加 i o l 这些字母,因为容易混淆用户。

    • i : l
    • l : 1
    • o : 0

(当然 0 是不能出现的) 很相似。

Ps: 生成的邀请码位数 取决于 用户id 可以被 取模多少次

Laravel根据用户id生成四位数唯一邀请码

文章目录