New in Symfony 5.1: Uid component

Contributed by
Grégoire Pineau and Nicolas Grekas in #35940 and #36042.

UIDs (universally unique identifiers) such as UUIDs are increasingly popular in web development. They are used in URLs, as cache keys, as primary keys in databases, etc.

In Symfony 5.1 we've introduced a new component called Uid which generates some of these UIDs and provides utilities for them. The first version of the component supports both UUIDs and ULIDs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Uid\Ulid;

// generating a random UUID type 4 (all UUID types are supported)
$uuid = Uuid::v4();

// generating a UUID Type 6 (which is not part of the standard, but it's
// supported by the component because it's popular enough)
$uuid = Uuid::v6();

// generating a ULID (there's only one type of them)
$ulid = new Ulid();

The component also provides the essential utilities you need when handling UIDs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// checking if some UUID is null
use Symfony\Component\Uid\NilUuid;
if ($uuid instanceof NilUuid) {
    // ...
}

// comparing UUIDs
$uuid1 = Uuid::v1();
$uuid4 = Uuid::v4();
$uuid1->equals($uuid4); // false

// converting to different formats
$ulid = Ulid::fromString('01E439TP9XJZ9RPFH3T1PYBCR8');
$ulid->toBinary();  // string(16) "..." (binary contents can't be printed)
$ulid->toBase32();  // string(26) "01E439TP9XJZ9RPFH3T1PYBCR8"
$ulid->toBase58();  // string(22) "1BKocMc5BnrVcuq2ti4Eqm"
$ulid->toRfc4122(); // string(36) "0171069d-593d-97d3-8b3e-23d06de5b308"

Read the Uid component docs to learn about all the provided features.

An important thing to consider is that this component does not replace full-featured libraries such as ramsey/uuid. The component only provides the minimum features you need to handle UIDs. Moreover, the component supports several UID types and we may add more types in the future (if they are popular enough and make sense in the scenarios targeted by Symfony applications).

Comments

Great job. A question why not create a method for valid if is null inside de class Uuid, because in that way I don't need to know the namespace "Symfony\Component\Uid\NilUuid". Something like this:

// checking if some UUID is null
if (Uuid::isNull($uuid)) {
// ...
}
As always you rocks guys!!! I have one question..will the component include compatibility with Doctrine?? I mean, will the component include the Doctrine custom type in order to be able define and handle fields of type uuid for example.
@Nilmar the isNull() method was removed here: https://github.com/symfony/symfony/pull/36066

@Francisco Javier yes, we want to integrate this component with many other components. Here is the plan: https://github.com/symfony/symfony/issues/36102
Login with SymfonyConnect to post a comment