Zend Framework 生成唯一字符串 [英] Zend Framework generate unique string

查看:24
本文介绍了Zend Framework 生成唯一字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个唯一的 4-6 个字符长的 AlphaNumeric 字符串,以便与每个记录(用户)一起保存在 db 中.db 字段具有唯一索引,因此尝试保存预先存在的字符串会产生错误.现在我正在生成一个随机字符串并使用 try-catch,因此在添加新记录时,如果它抛出异常,我会生成另一个随机字符串并尝试再次保存,并且代码不断尝试,直到成功添加记录.整个解决方案不仅看起来沉重而且丑陋,所以我想改变它.我对优雅的解决方案感兴趣,因此欢迎提供任何帮助/指导.

I want to generate a unique 4-6 char long AlphaNumeric string to save in db with each record(user). The db field has a unique index, so trying to save a pre-existing string generates an error. Right now I am generating a random string and using try-catch, so when adding a new record if it throws an exception, I generate another random string and attempt to save again, and the code keep trying until it adds a record successfully. This whole solution not only looks heavy but also ugly, so I want to change it. I am interested in an elegant solution, so any help/guidance is welcome.

推荐答案

使用给定的信息:

  • id 必须是唯一的
  • id 不能是数字
  • id 不能代表一个连续的系列
  • 用户不会输入id

PHP 函数 uniqid 正是您所需要的.虽然它返回一个 13 个字符长的十六进制值.

The PHP function uniqid is exactly what you need. Though it returns a 13 character long hexadecimal value.

** 编辑 **

是的,uniqid 会返回一个连续的数字,但我们可以轻松解决这个问题.考虑这个代码

Yes, uniqid will return a seamingly sequential number, but we can get around this easily. Consider this code

class IDGenerator {
   //const BIT_MASK = '01110011';

   static public function generate() {

      $id = uniqid();

      $id = base_convert($id, 16, 2);
      $id = str_pad($id, strlen($id) + (8 - (strlen($id) % 8)), '0', STR_PAD_LEFT);

      $chunks = str_split($id, 8);
      //$mask = (int) base_convert(IDGenerator::BIT_MASK, 2, 10);

      $id = array();
      foreach ($chunks as $key => $chunk) {
         //$chunk = str_pad(base_convert(base_convert($chunk, 2, 10) ^ $mask, 10, 2), 8, '0', STR_PAD_LEFT);
         if ($key & 1) {  // odd
            array_unshift($id, $chunk);
         } else {         // even
            array_push($id, $chunk);
         }
      }

      return base_convert(implode($id), 2, 36);
   }
}

echo IDGenerator::generate();

哪个会给出类似的结果

ivpa493xrx7
d173barerui
evpoiyjdryd
99ej19mnau2

由于没有添加或修改任何内容,除了改组周围的位,不应该有任何重复的值,一切似乎都是随机的.瞧!

Since there is nothing added or modified, except shuffling the bits around, there should not be any duplicated values and everything seems random. Voilà!

自从它最初发布以来,我就更新了这段代码.您可能会找到修订版 这里

I update this piece of code since the time it was originally posted. You may find the revised version here

这篇关于Zend Framework 生成唯一字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆