Core\Uuid::v4
Creates a new random UUID, such as f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4. A UUID is a 128-bit identifier that you can create anywhere without asking a database or another server for the next number. 122 of the bits come from a secure random number generator, so two calls never give the same UUID in practice, and nobody can guess the next one.
The other six bits are fixed. The first digit of the third group is always 4, which says that this is a version 4 UUID. A version 4 UUID contains no date or time, so it is safe to show to other people. When you need IDs that sort by the time they were created, use Core\Uuid::v7 instead.
The examples below show the parts of a new UUID that never change, check that many new UUIDs are all different, and give each new order its own ID.
Return value
Returns Core\Uuid. A new Uuid. Nobody can guess it, and it contains no date or time, so it is safe to show to other people.
Examples
Create a new id
<?nvs// Shows how to create a new random UUID and which of its characters are always the same.
// `Core\Uuid::v4` creates a new UUID. Its digits are different on every run.string $id = Core\Uuid::v4()->toString();
// The text is always 36 characters long. This prints 36.echo Core\Str::length($id), "\n";
// The third group always starts with the version of the UUID. This prints 4.echo Core\Str::slice($id, 14, 1), "\n";
// The groups are always 8, 4, 4, 4 and 12 digits long. This prints 8 4 4 4 12.array<string> $lengths = [];foreach (Core\Str::split($id, '-') as string $group) { $lengths[] = Core\Str::length($group) as string;}echo Core\Str::join($lengths, ' '), "\n";3648 4 4 4 12Every call gives a new id
<?nvs// Shows that every call to `Core\Uuid::v4` gives a different UUID.
// This loop creates 10000 UUIDs. Each one is a key in `$seen`, so a repeated UUID// would not add a new key.array<bool> $seen = [];int $i = 0;while ($i < 10000) { $seen[Core\Uuid::v4()->toString()] = true; $i = $i + 1;}
// All 10000 UUIDs are different. This prints 10000.echo Core\Arr::count($seen), "\n";10000Give each new order an id
<?nvs// Shows how to give each new order its own ID before it is saved anywhere.
class Order{ public function constructor(public Core\Uuid $id, public string $customer) {}}
// The ID is created with the order, so no database is needed to choose it.array<Order> $orders = [ new Order(Core\Uuid::v4(), 'Anna'), new Order(Core\Uuid::v4(), 'Ben'),];
// A link to the order contains its ID as text. This prints 44.string $link = '/orders/' . $orders[1]->id->toString();echo Core\Str::length($link), "\n";
// Later, the ID is read back from the link and the order is found again.// This prints Ben.Core\Uuid $asked = Core\Uuid::parse(Core\Str::slice($link, 8, 36));foreach ($orders as Order $order) { if ($order->id->toString() == $asked->toString()) { echo $order->customer, "\n"; }}44Ben