March 25, 2020 Javier Eguiluz

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