上一篇我们将了 UID 的发号器,那这一篇我们将要去实现用户的注册入库和简单的查询。
首先我们要实现数据表的识别。
app/common.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| if(!function_exists('table_name')) {
function table_name(string $name, ?int $uid = null) { $support_table = [ 'users' => 16, ];
if(!isset($support_table[$name])) { return $name; }
if(is_null($uid)) { $uid = (int) 1; }
if((int) $uid === 0) { throw new \Exception('UID 值异常'); }
return sprintf('%s_%x', $name, $uid % $support_table[$name]); } }
|
app/controller/Auth.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <?php namespace app\controller;
use app\BaseController; use think\facade\Db; use think\helper\Str;
class Auth extends BaseController {
public function register() { $redis = get_redis();
$uid = $redis->lpop('generate:uid');
if(is_null($uid)) { return '无法获取 UID'; }
$table_name = table_name('users', $uid);
Db::table($table_name)->insert([ 'id' => $uid, 'nickname' => '随机生成' . Str::random(), ]);
return '注册成功'; } }
|

app/controller/Users.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <?php namespace app\controller;
use app\BaseController; use app\Request; use think\facade\Db;
class Users extends BaseController { public function index(Request $request) { $uid = 1 ?? $request->uid;
$table_name = table_name('users', $uid);
$data = Db::table($table_name) ->where('id', $uid) ->find();
var_dump($data); } }
|