Zend Framework generate unique string

元气小坏坏 提交于 2020-01-03 13:07:43

问题


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.


回答1:


With the given information :

  • id must be unique
  • id must not be numeric
  • id must not represent a sequential series
  • id will not be input by the user

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


** Edit **

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();

Which will give results like

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à!

** Update (2014-02-24) **

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



来源:https://stackoverflow.com/questions/7457802/zend-framework-generate-unique-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!