Skip to content

Instantly share code, notes, and snippets.

@lmammino
Created February 21, 2014 14:55
Show Gist options
  • Save lmammino/9135633 to your computer and use it in GitHub Desktop.
Save lmammino/9135633 to your computer and use it in GitHub Desktop.
UidGenerator Class
<?php
namespace LMammino\Generator;
class Uid
{
/**
* @var string
*/
protected $salt;
/**
* @param string $salt
*/
public function __construct($salt)
{
$this->salt = $salt;
}
/**
* Generates an uid of the given length
*
* @param int $len
* @return string
*/
public function generate($len=8)
{
$hex = md5($this->salt . uniqid());
$pack = pack('H*', $hex);
$tmp = base64_encode($pack);
$uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp);
$len = max(4, min(128, $len));
while (strlen($uid) < $len) {
$uid .= $this->generate(22);
}
return substr($uid, 0, $len);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment