Laravel-生成唯一固定长度邀请码
前段时间有朋友反馈存在重复情况,所以仔细想了一下可以使用递归函数进行二次排查的方法来解决这个问题,以laravel框架为例。
第一步在控制器中生成验证码。
//调用模型 生成邀请码
$dealer=new Dealer;
$code=$this->getcode($dealer);
//控制区内的私有方法调用模型内方法
private function getcode($model) {
$code = $model->CreateCode();
//把接收的邀请码再次返回给模型
if ($model->recode($code)) {
//不重复 返回验证码
return $code;
} else {
//重复 再次生成
while(true) {
$this->getcode($model);
}
}
}
/**
* 模型内生成邀请码 并返回控制器
* @param $uid
* @return string
*/
public function CreateCode() {
$code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rand = $code[rand(0,25)]
.strtoupper(dechex(date('m')))
.date('d').substr(time(),-5)
.substr(microtime(),2,5)
.sprintf('%02d',rand(0,99));
for(
$a = md5( $rand, true ),
$s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
$d = '',
$f = 0;
$f < 6;
$g = ord( $a[ $f ] ),
$d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
$f++
);
return $d;
}
/**
* 判断验证码是否存在数据库中
*/
public function recode($code) {
if ($this->where('code','=',$code)->first()) {
return false;
}
return true;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
测试过,有重复~