If you have more then 1 primary database servers - you have probably experienced the pain of primary key overlapping... Here is a super simple solution that will generate a hash of random letters and numbers.
Included is a sample ActiveRecord class (MyTable.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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | -------------------- dbHelper.php --------------------
class dbHelper
{
public static function createUID($len = 16)
{
$index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
$tc = strlen($index) - 1;
$pk = '';
for ($i = 0; $i < $len; $i++)
{
$pk .= $index[rand(0, $tc)];
}
return $pk;
}
public static function arCreateUID($obj, $len = 16)
{
$pk = $obj->get_primary_key(true);
while (empty($obj->$pk) || $obj->$pk === 'NULL')
{
$obj->$pk = self::createUID($len);
try
{
$r = $obj->find('first', array(
'conditions' => array($pk . '=?', $obj->$pk)
));
if (is_null($r))
{
break;
}
} catch (\ActiveRecord\RecordNotFound $e) {
break;
}
}
}
}
-------------------- MyTable.php --------------------
class MyTable extends \ActiveRecord\Model
{
static $before_create = array('create_uid');
public function create_uid()
{
dbHelper::arCreateUID($this);
}
}
|