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

2. Generating a Unique Code

$code = $generator->generate($length, $column, $table, $prefix = "");
The code uses a custom character set (digits 2-9 and uppercase letters, omitting ambiguous ones) for readability.

3. How It Works

  1. Generates a random code of the specified length (plus optional prefix).
  2. Checks the database to ensure the code does not already exist in the specified column/table.
  3. If the code exists, it recursively generates a new one until a unique code is found.
  4. 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

6. References