Designing Order Numbers for E-commerce Systems

$uniqueOrderKey = uniqid(date('Ymd')); echo $uniqueOrderKey;


</div>This might output something like: <div>```

201907205d32de71e6002

public static function generateCounter($storeId = 0, $type = null, $useTransaction = true, $padLength = 15, $currentTime = null) { if (empty($type)) { throw new \Exception('Type label cannot be empty.'); }

if (empty($currentTime)) {
    $currentTime = time();
}

// Adjust length based on type
if ($type == 5) {
    $formattedTime = date('Ymd', $currentTime);
    $padLength = 11;
} else {
    $formattedTime = date('Ym', $currentTime);
}

$remainingLength = $padLength - strlen($formattedTime);
$tagMapping = self::getTagMapping($type);
$compositeName = $formattedTime . '_' . $tagMapping;

if ($useTransaction) {
    DB::beginTransaction();
}

try {
    $counterRecord = Counter::where('name', $compositeName)->first(['value', 'id']);
    
    if (empty($counterRecord)) {
        $newCounter = new Counter();
        $newCounter->name = $compositeName;
        $newCounter->type = $type;
        $newCounter->tag = $tagMapping;
        $newCounter->save();
        $counterRecord = Counter::where('name', $compositeName)->first(['value', 'id']);
    }

    $recordArray = $counterRecord->toArray();

    // Lock to prevent race conditions
    Counter::where('id', $recordArray['id'])->lockForUpdate()->first();

    $updatedValue = (float)$recordArray['value'] + 3;
    Counter::where('name', $compositeName)->update(['value' => $updatedValue]);

    $finalString = $formattedTime . str_pad($updatedValue, $remainingLength, '0', STR_PAD_LEFT);

    if ($useTransaction) {
        DB::commit();
    }

    return $finalString;
} catch (\Exception $e) {
    if ($useTransaction) {
        DB::rollBack();
    }
    throw new \Exception($e->getMessage());
}

}

public static function getTagMapping($type = null) { $mappingArray = [ '5' => 'contract', '10' => 'sales_order_number', '20' => 'purchase_order_number', '30' => 'logistics_order_number', '40' => 'inbound_order_number', '50' => 'outbound_order_number', '60' => 'purchase_point_number', '70' => 'express_number', '75' => 'return_express_number', '80' => 'sale_voucher_number', '90' => 'batch_number', '100' => 'purchase_settle_number', '110' => 'sales_settle_number', '120' => 'sales_point_number', '130' => 'k3_pay_number' ];

if (empty($type)) {
    return $mappingArray;
}

return $mappingArray[$type];

}


</div>This implementation uses database transactions and locks to safely generate unique order numbers while handling concurrent requests.</div>

Tags: PHP MySQL E-commerce

Posted on Mon, 18 May 2026 23:03:18 +0000 by datafan