The UID Component

The UID Component

The UID component provides utilities to work with unique identifiers (UIDs) such as UUIDs and ULIDs.

New in version 5.1: The UID component was introduced in Symfony 5.1.

Installation

  1. $ composer require symfony/uid

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

UUIDs

UUIDs (universally unique identifiers) are one of the most popular UIDs in the software industry. UUIDs are 128-bit numbers usually represented as five groups of hexadecimal characters: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx (the M digit is the UUID version and the N digit is the UUID variant).

Generating UUIDs

Use the named constructors of the Uuid class or any of the specific classes to create each type of UUID:

  1. use Symfony\Component\Uid\Uuid;
  2. // UUID type 1 generates the UUID using the MAC address of your device and a timestamp.
  3. // Both are obtained automatically, so you don't have to pass any constructor argument.
  4. $uuid = Uuid::v1(); // $uuid is an instance of Symfony\Component\Uid\UuidV1
  5. // UUID type 4 generates a random UUID, so you don't have to pass any constructor argument.
  6. $uuid = Uuid::v4(); // $uuid is an instance of Symfony\Component\Uid\UuidV4
  7. // UUID type 3 and 5 generate a UUID hashing the given namespace and name. Type 3 uses
  8. // MD5 hashes and Type 5 uses SHA-1. The namespace is another UUID (e.g. a Type 4 UUID)
  9. // and the name is an arbitrary string (e.g. a product name; if it's unique).
  10. $namespace = Uuid::v4();
  11. $name = $product->getUniqueName();
  12. $uuid = Uuid::v3($namespace, $name); // $uuid is an instance of Symfony\Component\Uid\UuidV3
  13. $uuid = Uuid::v5($namespace, $name); // $uuid is an instance of Symfony\Component\Uid\UuidV5
  14. // the namespaces defined by RFC 4122 (see https://tools.ietf.org/html/rfc4122#appendix-C)
  15. // are available as PHP constants and as string values
  16. $uuid = Uuid::v3(Uuid::NAMESPACE_DNS, $name); // same as: Uuid::v3('dns', $name);
  17. $uuid = Uuid::v3(Uuid::NAMESPACE_URL, $name); // same as: Uuid::v3('url', $name);
  18. $uuid = Uuid::v3(Uuid::NAMESPACE_OID, $name); // same as: Uuid::v3('oid', $name);
  19. $uuid = Uuid::v3(Uuid::NAMESPACE_X500, $name); // same as: Uuid::v3('x500', $name);
  20. // UUID type 6 is not part of the UUID standard. It's lexicographically sortable
  21. // (like ULIDs) and contains a 60-bit timestamp and 63 extra unique bits.
  22. // It's defined in http://gh.peabody.io/uuidv6/
  23. $uuid = Uuid::v6(); // $uuid is an instance of Symfony\Component\Uid\UuidV6

New in version 5.3: The Uuid::NAMESPACE_* constants and the namespace string values ('dns', 'url', etc.) were introduced in Symfony 5.3.

If your UUID value is already generated in another format, use any of the following methods to create a Uuid object from it:

  1. // all the following examples would generate the same Uuid object
  2. $uuid = Uuid::fromString('d9e7a184-5d5b-11ea-a62a-3499710062d0');
  3. $uuid = Uuid::fromBinary("\xd9\xe7\xa1\x84\x5d\x5b\x11\xea\xa6\x2a\x34\x99\x71\x00\x62\xd0");
  4. $uuid = Uuid::fromBase32('6SWYGR8QAV27NACAHMK5RG0RPG');
  5. $uuid = Uuid::fromBase58('TuetYWNHhmuSQ3xPoVLv9M');
  6. $uuid = Uuid::fromRfc4122('d9e7a184-5d5b-11ea-a62a-3499710062d0');

New in version 5.3: The fromBinary(),fromBase32(), fromBase58() andfromRfc4122() methods were introduced in Symfony 5.3.

Converting UUIDs

Use these methods to transform the UUID object into different bases:

  1. $uuid = Uuid::fromString('d9e7a184-5d5b-11ea-a62a-3499710062d0');
  2. $uuid->toBinary(); // string(16) "\xd9\xe7\xa1\x84\x5d\x5b\x11\xea\xa6\x2a\x34\x99\x71\x00\x62\xd0"
  3. $uuid->toBase32(); // string(26) "6SWYGR8QAV27NACAHMK5RG0RPG"
  4. $uuid->toBase58(); // string(22) "TuetYWNHhmuSQ3xPoVLv9M"
  5. $uuid->toRfc4122(); // string(36) "d9e7a184-5d5b-11ea-a62a-3499710062d0"

Working with UUIDs

UUID objects created with the Uuid class can use the following methods (which are equivalent to the `uuid_*() method of the PHP extension):

  1. use Symfony\Component\Uid\NilUuid;
  2. use Symfony\Component\Uid\Uuid;
  3. // checking if the UUID is null (note that the class is called
  4. // NilUuid instead of NullUuid to follow the UUID standard notation)
  5. $uuid = Uuid::v4();
  6. $uuid instanceof NilUuid; // false
  7. // checking the type of UUID
  8. use Symfony\Component\Uid\UuidV4;
  9. $uuid = Uuid::v4();
  10. $uuid instanceof UuidV4; // true
  11. // getting the UUID datetime (it's only available in certain UUID types)
  12. $uuid = Uuid::v1();
  13. $uuid->getDateTime(); // returns a \DateTimeImmutable instance
  14. // comparing UUIDs and checking for equality
  15. $uuid1 = Uuid::v1();
  16. $uuid4 = Uuid::v4();
  17. $uuid1->equals($uuid4); // false
  18. // this method returns:
  19. // * int(0) if $uuid1 and $uuid4 are equal
  20. // * int > 0 if $uuid1 is greater than $uuid4
  21. // * int < 0 if $uuid1 is less than $uuid4
  22. $uuid1->compare($uuid4); // e.g. int(4)

New in version 5.3: The getDateTime() method was introduced in Symfony 5.3. In previous versions it was calledgetTime().

Storing UUIDs in Databases

If you use Doctrine, consider using the uuid Doctrine type, which converts to/from UUID objects automatically:

  1. // src/Entity/Product.php
  2. namespace App\Entity;
  3. use Doctrine\ORM\Mapping as ORM;
  4. /**
  5. * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
  6. */
  7. class Product
  8. {
  9. /**
  10. * @ORM\Column(type="uuid")
  11. */
  12. private $someProperty;
  13. // ...
  14. }

New in version 5.2: The UUID type was introduced in Symfony 5.2.

There is no generator to assign UUIDs automatically as the value of your entity primary keys, but you can use the following:

  1. namespace App\Entity;
  2. use Doctrine\ORM\Mapping as ORM;
  3. use Symfony\Component\Uid\Uuid;
  4. // ...
  5. class User implements UserInterface
  6. {
  7. /**
  8. * @ORM\Id
  9. * @ORM\Column(type="uuid", unique=true)
  10. */
  11. private $id;
  12. public function __construct()
  13. {
  14. $this->id = Uuid::v4();
  15. }
  16. public function getId(): Uuid
  17. {
  18. return $this->id;
  19. }
  20. // ...
  21. }

When using built-in Doctrine repository methods (e.g. findOneBy()), Doctrine knows how to convert these UUID types to build the SQL query (e.g.->findOneBy([‘user’ => $user->getUuid()])). However, when using DQL queries or building the query yourself, you’ll need to set uuid as the type of the UUID parameters:

  1. // src/Repository/ProductRepository.php
  2. // ...
  3. class ProductRepository extends ServiceEntityRepository
  4. {
  5. // ...
  6. public function findUserProducts(User $user): array
  7. {
  8. $qb = $this->createQueryBuilder('p')
  9. // ...
  10. // add 'uuid' as the third argument to tell Doctrine that this is a UUID
  11. ->setParameter('user', $user->getUuid(), 'uuid')
  12. // alternatively, you can convert it to a value compatible with
  13. // the type inferred by Doctrine
  14. ->setParameter('user', $user->getUuid()->toBinary())
  15. ;
  16. // ...
  17. }
  18. }

ULIDs

ULIDs (Universally Unique Lexicographically Sortable Identifier) are 128-bit numbers usually represented as a 26-character string: TTTTTTTTTTRRRRRRRRRRRRRRRR (where T represents a timestamp and R represents the random bits).

ULIDs are an alternative to UUIDs when using those is impractical. They provide 128-bit compatibility with UUID, they are lexicographically sortable and they are encoded as 26-character strings (vs 36-character UUIDs).

Note

If you generate more than one ULID during the same millisecond in the same process then the random portion is incremented by one bit in order to provide monotonicity for sorting. The random portion is not random compared to the previous ULID in this case.

Generating ULIDs

Instantiate the Ulid class to generate a random ULID value:

  1. use Symfony\Component\Uid\Ulid;
  2. $ulid = new Ulid(); // e.g. 01AN4Z07BY79KA1307SR9X4MV3

If your ULID value is already generated in another format, use any of the following methods to create a Ulid object from it:

  1. // all the following examples would generate the same Ulid object
  2. $ulid = Ulid::fromString('01E439TP9XJZ9RPFH3T1PYBCR8');
  3. $ulid = Ulid::fromBinary("\x01\x71\x06\x9d\x59\x3d\x97\xd3\x8b\x3e\x23\xd0\x6d\xe5\xb3\x08");
  4. $ulid = Ulid::fromBase32('01E439TP9XJZ9RPFH3T1PYBCR8');
  5. $ulid = Ulid::fromBase58('1BKocMc5BnrVcuq2ti4Eqm');
  6. $ulid = Ulid::fromRfc4122('0171069d-593d-97d3-8b3e-23d06de5b308');

New in version 5.3: The fromBinary(),fromBase32(), fromBase58() andfromRfc4122() methods were introduced in Symfony 5.3.

Converting ULIDs

Use these methods to transform the ULID object into different bases:

  1. $ulid = Ulid::fromString('01E439TP9XJZ9RPFH3T1PYBCR8');
  2. $ulid->toBinary(); // string(16) "\x01\x71\x06\x9d\x59\x3d\x97\xd3\x8b\x3e\x23\xd0\x6d\xe5\xb3\x08"
  3. $ulid->toBase32(); // string(26) "01E439TP9XJZ9RPFH3T1PYBCR8"
  4. $ulid->toBase58(); // string(22) "1BKocMc5BnrVcuq2ti4Eqm"
  5. $ulid->toRfc4122(); // string(36) "0171069d-593d-97d3-8b3e-23d06de5b308"

Working with ULIDs

ULID objects created with the Ulid class can use the following methods:

  1. use Symfony\Component\Uid\Ulid;
  2. $ulid1 = new Ulid();
  3. $ulid2 = new Ulid();
  4. // checking if a given value is valid as ULID
  5. $isValid = Ulid::isValid($ulidValue); // true or false
  6. // getting the ULID datetime
  7. $ulid1->getDateTime(); // returns a \DateTimeImmutable instance
  8. // comparing ULIDs and checking for equality
  9. $ulid1->equals($ulid2); // false
  10. // this method returns $ulid1 <=> $ulid2
  11. $ulid1->compare($ulid2); // e.g. int(-1)

New in version 5.3: The getDateTime() method was introduced in Symfony 5.3. In previous versions it was calledgetTime().

Storing ULIDs in Databases

If you use Doctrine, consider using the ulid Doctrine type, which converts to/from ULID objects automatically:

  1. // src/Entity/Product.php
  2. namespace App\Entity;
  3. use Doctrine\ORM\Mapping as ORM;
  4. /**
  5. * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
  6. */
  7. class Product
  8. {
  9. /**
  10. * @ORM\Column(type="ulid")
  11. */
  12. private $someProperty;
  13. // ...
  14. }

There’s also a Doctrine generator to help autogenerate ULID values for the entity primary keys:

  1. use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
  2. use Symfony\Component\Uid\Ulid;
  3. /**
  4. * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
  5. */
  6. class Product
  7. {
  8. /**
  9. * @ORM\Id
  10. * @ORM\Column(type="ulid", unique=true)
  11. * @ORM\GeneratedValue(strategy="CUSTOM")
  12. * @ORM\CustomIdGenerator(class=UlidGenerator::class)
  13. */
  14. private $id;
  15. // ...
  16. public function getId(): ?Ulid
  17. {
  18. return $this->id;
  19. }
  20. // ...
  21. }

New in version 5.2: The ULID type and generator were introduced in Symfony 5.2.

When using built-in Doctrine repository methods (e.g. findOneBy()), Doctrine knows how to convert these ULID types to build the SQL query (e.g.->findOneBy([‘user’ => $user->getUlid()])). However, when using DQL queries or building the query yourself, you’ll need to set ulid as the type of the ULID parameters:

  1. // src/Repository/ProductRepository.php
  2. // ...
  3. class ProductRepository extends ServiceEntityRepository
  4. {
  5. // ...
  6. public function findUserProducts(User $user): array
  7. {
  8. $qb = $this->createQueryBuilder('p')
  9. // ...
  10. // add 'ulid' as the third argument to tell Doctrine that this is a ULID
  11. ->setParameter('user', $user->getUlid(), 'ulid')
  12. // alternatively, you can convert it to a value compatible with
  13. // the type inferred by Doctrine
  14. ->setParameter('user', $user->getUlid()->toBinary())
  15. ;
  16. // ...
  17. }
  18. }

Generating and Inspecting UUIDs/ULIDs in the Console

New in version 5.3: The commands to inspect and generate UUIDs/ULIDs were introduced in Symfony 5.3.

This component provides several commands to generate and inspect UUIDs/ULIDs in the console. They are not enabled by default, so you must add the following configuration in your application before using these commands:

  • YAML

    1. # config/services.yaml
    2. services:
    3. Symfony\Component\Uid\Command\GenerateUlidCommand: ~
    4. Symfony\Component\Uid\Command\GenerateUuidCommand: ~
    5. Symfony\Component\Uid\Command\InspectUlidCommand: ~
    6. Symfony\Component\Uid\Command\InspectUuidCommand: ~
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... -->
    9. <service id="Symfony\Component\Uid\Command\GenerateUlidCommand"/>
    10. <service id="Symfony\Component\Uid\Command\GenerateUuidCommand"/>
    11. <service id="Symfony\Component\Uid\Command\InspectUlidCommand"/>
    12. <service id="Symfony\Component\Uid\Command\InspectUuidCommand"/>
    13. </services>
    14. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use Symfony\Component\Uid\Command\GenerateUlidCommand;
    4. use Symfony\Component\Uid\Command\GenerateUuidCommand;
    5. use Symfony\Component\Uid\Command\InspectUlidCommand;
    6. use Symfony\Component\Uid\Command\InspectUuidCommand;
    7. return static function (ContainerConfigurator $configurator): void {
    8. // ...
    9. $services
    10. ->set(GenerateUlidCommand::class)
    11. ->set(GenerateUuidCommand::class)
    12. ->set(InspectUlidCommand::class)
    13. ->set(InspectUuidCommand::class);
    14. };

Now you can generate UUIDs/ULIDs as follows (add the --help option to the commands to learn about all their options):

  1. # generate 1 random-based UUID
  2. $ php bin/console uuid:generate --random-based
  3. # generate 1 time-based UUID with a specific node
  4. $ php bin/console uuid:generate --time-based=now --node=fb3502dc-137e-4849-8886-ac90d07f64a7
  5. # generate 2 UUIDs and output them in base58 format
  6. $ php bin/console uuid:generate --count=2 --format=base58
  7. # generate 1 ULID with the current time as the timestamp
  8. $ php bin/console ulid:generate
  9. # generate 1 ULID with a specific timestamp
  10. $ php bin/console ulid:generate --time="2021-02-02 14:00:00"
  11. # generate 2 ULIDs and ouput them in RFC4122 format
  12. $ php bin/console ulid:generate --count=2 --format=rfc4122

In addition to generating new UIDs, you can also inspect them with the following commands to show all the information for a given UID:

  1. $ php bin/console uuid:inspect d0a3a023-f515-4fe0-915c-575e63693998
  2. ---------------------- --------------------------------------
  3. Label Value
  4. ---------------------- --------------------------------------
  5. Version 4
  6. Canonical (RFC 4122) d0a3a023-f515-4fe0-915c-575e63693998
  7. Base 58 SmHvuofV4GCF7QW543rDD9
  8. Base 32 6GMEG27X8N9ZG92Q2QBSHPJECR
  9. ---------------------- --------------------------------------
  10. $ php bin/console ulid:inspect 01F2TTCSYK1PDRH73Z41BN1C4X
  11. --------------------- --------------------------------------
  12. Label Value
  13. --------------------- --------------------------------------
  14. Canonical (Base 32) 01F2TTCSYK1PDRH73Z41BN1C4X
  15. Base 58 1BYGm16jS4kX3VYCysKKq6
  16. RFC 4122 0178b5a6-67d3-0d9b-889c-7f205750b09d
  17. --------------------- --------------------------------------
  18. Timestamp 2021-04-09 08:01:24.947
  19. --------------------- --------------------------------------

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.