New in Symfony 6.2: New Uid Features
November 17, 2022 • Published by Javier Eguiluz
Symfony 6.2 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
The Uid component provides an object-oriented API to generate and represent UIDs such as UUID and ULID. In Symfony 6.2 we're adding some features to it.
MaxUuid and MaxUlid
In Symfony 6.2 we're introducing two new classes called MaxUlid
and MaxUuid
which represent the highest possible value of both UUID and ULID. You can use
those objects to get the max values string representation, to compare them to
other UID objects, etc.
If you are curious, these are the maximum values possible:
1 2
Max UUID: 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'
Max ULID: '7ZZZZZZZZZZZZZZZZZZZZZZZZZ'
Time-based Uid Interface
Some UIDs include a date/time as part of their value. In Symfony 6.2 we're introducing the following interface so you can get this date/time value more easily:
1 2 3 4
interface TimeBasedUidInterface
{
public function getDateTime(): \DateTimeImmutable;
}
The interface is only implemented by the UID types/versions that include a date/time,
which are: Ulid
, UuidV1
, UuidV6
the new and UuidV7
.
Uid Conversion to Hexadecimal Values
UIDs include lots of methods to convert their value into different formats
(toBase32()
, toBase58()
, toRfc4122()
, etc.) In Symfony 6.2 we're
introducing a new toHex()
method which returns the binary value as an
hexadecimal string:
1 2 3 4 5 6
use Symfony\Component\Uid\Uuid;
$uuid = Uuid::v4()
// e.g. (string) $uuid = 'd6b3345b-2905-4048-a83c-b5988e765d98'
$hex = $uuid->toHex();
// $hex = '0xd6b3345b29054048a83cb5988e765d98'
The hexadecimal string returned by toHex()
is ready to use in other parts of
your application, such as storing or querying UIDs in binary format in the database.
UuidV7 and UuidV8 Support
The UUID specification continues adding new formats to generate values suited for different scenarios. They recently added UUID Version 7 and UUID Version 8 formats and Symfony 6.2 adds support for them:
1 2 3 4 5 6
use Symfony\Component\Uid\Uuid;
$uuid = Uuid::v7();
// e.g. (string) $uuid = '017f22e2-79b0-7cc3-98c4-dc0c0c07398f'
$uuid = Uuid::v8();
// e.g. (string) $uuid = '216fff40-98d9-81e3-a5e2-0800200c9a66'
Conceptually, UUID v7 is very similar to ULID: they're monotonic, sortable, unguessable, and embed a ms-unix-timestamp.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.