UniqueCodeGenerator Class Documentation
UniqueCodeGenerator (namespace: Nobanno) generates unique, random alphanumeric codes and ensures their uniqueness in a database table/column using ExPDO.
1. Constructor
use Nobanno\UniqueCodeGenerator;
use Nobanno\ExPDO;
$db = new ExPDO(...);
$generator = new UniqueCodeGenerator($db);
- __construct(ExPDO $ExPDO): Pass an
ExPDO database connection.
2. Generating a Unique Code
$code = $generator->generate($length, $column, $table, $prefix = "");
- $length: Number of random characters in the code (integer).
- $column: Column name to check for uniqueness (string).
- $table: Table name to check for uniqueness (string).
- $prefix: (Optional) String to prepend to the code.
The code uses a custom character set (digits 2-9 and uppercase letters, omitting ambiguous ones) for readability.
3. How It Works
- Generates a random code of the specified length (plus optional prefix).
- Checks the database to ensure the code does not already exist in the specified column/table.
- If the code exists, it recursively generates a new one until a unique code is found.
- Returns the unique code.
4. Example
// Generate a unique 8-character code for the 'invite_code' column in the 'users' table
$code = $generator->generate(8, 'invite_code', 'users');
// With a prefix
$code = $generator->generate(6, 'ref_code', 'referrals', 'REF-');
5. Notes & Best Practices
- Make sure the target column is indexed or unique in your database for best performance.
- For cryptographically secure codes, consider using
random_bytes and bin2hex (see code comments).
- Recursion is used for collision handling; for very high code volumes, consider a loop or limit attempts.
6. References