



  

ramsey/uuid stable Manual

 [ramsey/uuid](index.html#document-index) 

* [Introduction](index.html#document-introduction)

	+ [What Is a UUID?](index.html#what-is-a-uuid)

* [Getting Started](index.html#document-quickstart)

	+ [Requirements](index.html#requirements)

	+ [Install With Composer](index.html#install-with-composer)

	+ [Using ramsey/uuid](index.html#using-ramsey-uuid)

* [RFC 4122 UUIDs](index.html#document-rfc4122)

	+ [Version 1: Gregorian Time](index.html#document-rfc4122/version1)

	+ [Version 2: DCE Security](index.html#document-rfc4122/version2)

	+ [Version 3: Name-based (MD5)](index.html#document-rfc4122/version3)

	+ [Version 4: Random](index.html#document-rfc4122/version4)

	+ [Version 5: Name-based (SHA-1)](index.html#document-rfc4122/version5)

	+ [Version 6: Reordered Time](index.html#document-rfc4122/version6)

	+ [Version 7: Unix Epoch Time](index.html#document-rfc4122/version7)

	+ [Version 8: Custom](index.html#document-rfc4122/version8)

* [Nonstandard UUIDs](index.html#document-nonstandard)

	+ [Version 6: Reordered Time](index.html#document-nonstandard/version6)

	+ [Globally Unique Identifiers (GUIDs)](index.html#document-nonstandard/guid)

	+ [Other Nonstandard UUIDs](index.html#document-nonstandard/other)

* [Using In a Database](index.html#document-database)

	+ [Storing As a String](index.html#storing-as-a-string)

	+ [Storing As Bytes](index.html#storing-as-bytes)

	+ [Using As a Primary Key](index.html#using-as-a-primary-key)

	+ [Using As a Unique Key](index.html#using-as-a-unique-key)

	+ [Insertion Order and Sorting](index.html#insertion-order-and-sorting)

* [Customization](index.html#document-customize)

	+ [Ordered-time Codec](index.html#document-customize/ordered-time-codec)

	+ [Timestamp-first COMB Codec](index.html#document-customize/timestamp-first-comb-codec)

	+ [Using a Custom Calculator](index.html#document-customize/calculators)

	+ [Using a Custom Validator](index.html#document-customize/validators)

	+ [Replace the Default Factory](index.html#document-customize/factory)

* [Testing With UUIDs](index.html#document-testing)

	+ [Inject a UUID of a Specific Type](index.html#inject-a-uuid-of-a-specific-type)

	+ [Returning Specific UUIDs From a Static Method](index.html#returning-specific-uuids-from-a-static-method)

	+ [Mocking UuidInterface](index.html#mocking-uuidinterface)

* [Upgrading ramsey/uuid](index.html#document-upgrading)

	+ [Version 3 to 4](index.html#document-upgrading/3-to-4)

	+ [Version 2 to 3](index.html#document-upgrading/2-to-3)

* [FAQs](index.html#document-faq)

	+ [How do I fix “rhumsaa/uuid is abandoned” messages?](index.html#how-do-i-fix-rhumsaa-uuid-is-abandoned-messages)

	+ [Why does ramsey/uuid use `final`?](index.html#why-does-ramsey-uuid-use-final)

* [Reference](index.html#document-reference)

	+ [Uuid](index.html#document-reference/uuid)

	+ [UuidInterface](index.html#document-reference/uuidinterface)

	+ [Fields\FieldsInterface](index.html#document-reference/fields-fieldsinterface)

	+ [Rfc4122\UuidInterface](index.html#document-reference/rfc4122-uuidinterface)

	+ [Rfc4122\FieldsInterface](index.html#document-reference/rfc4122-fieldsinterface)

	+ [Rfc4122\UuidV1](index.html#document-reference/rfc4122-uuidv1)

	+ [Rfc4122\UuidV2](index.html#document-reference/rfc4122-uuidv2)

	+ [Rfc4122\UuidV3](index.html#document-reference/rfc4122-uuidv3)

	+ [Rfc4122\UuidV4](index.html#document-reference/rfc4122-uuidv4)

	+ [Rfc4122\UuidV5](index.html#document-reference/rfc4122-uuidv5)

	+ [Rfc4122\UuidV6](index.html#document-reference/rfc4122-uuidv6)

	+ [Rfc4122\UuidV7](index.html#document-reference/rfc4122-uuidv7)

	+ [Rfc4122\UuidV8](index.html#document-reference/rfc4122-uuidv8)

	+ [Guid\Fields](index.html#document-reference/guid-fields)

	+ [Guid\Guid](index.html#document-reference/guid-guid)

	+ [Nonstandard\Fields](index.html#document-reference/nonstandard-fields)

	+ [Nonstandard\Uuid](index.html#document-reference/nonstandard-uuid)

	+ [Nonstandard\UuidV6](index.html#document-reference/nonstandard-uuidv6)

	+ [UuidFactoryInterface](index.html#document-reference/uuidfactoryinterface)

	+ [Types](index.html#document-reference/types)

	+ [Exceptions](index.html#document-reference/exceptions)

	+ [Helper Functions](index.html#document-reference/helper)

	+ [Predefined Namespaces](index.html#document-reference/name-based-namespaces)

	+ [Calculators](index.html#document-reference/calculators)

	+ [Validators](index.html#document-reference/validators)

* [Copyright](index.html#document-copyright)

* [ramsey/uuid for Enterprise](index.html#document-tidelift)

[ramsey/uuid](index.html#document-index)

* [Docs](index.html#document-index) »

* ramsey/uuid stable Manual

* [Edit on GitHub](https://github.com/ramsey/uuid/blob/60a4c63ab724854332900504274f6150ff26d286/docs/index.rst)

---

ramsey/uuid Manual[¶](#ramsey-uuid-manual "Permalink to this headline")

=======================================================================

For [ramsey/uuid](https://github.com/ramsey/uuid) stable. Updated on 2023-04-15.

This work is licensed under the [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/) license.

Support ramsey/uuid!

Your support encourages and motivates me to continue building and

maintaining open source software. If you benefit from my work, consider

supporting me financially.

You may support ramsey/uuid as an individual through [GitHub Sponsors](https://github.com/sponsors/ramsey) or as a company through the

**Tidelift Subscription**. With the Tidelift Subscription, you can get

commercial maintenance and assurances, while supporting my work.

Learn more about [ramsey/uuid for enterprise](index.html#tidelift)!

Contents[¶](#contents "Permalink to this headline")

---------------------------------------------------

### Introduction[¶](#introduction "Permalink to this headline")

ramsey/uuid is a PHP library for generating and working with [RFC 4122](https://tools.ietf.org/html/rfc4122) version

1, 2, 3, 4, 5, 6, and 7 universally unique identifiers (UUID). ramsey/uuid also

supports optional and non-standard features, such as GUIDs and other approaches

for encoding/decoding UUIDs.

#### What Is a UUID?[¶](#what-is-a-uuid "Permalink to this headline")

A universally unique identifier, or UUID, is a 128-bit unsigned integer, usually

represented as a hexadecimal string split into five groups with dashes. The most

widely-known and used types of UUIDs are defined by [RFC 4122](https://tools.ietf.org/html/rfc4122).

A UUID, when encoded in hexadecimal string format, looks like:

```

ebb5c735-0308-4e3c-9aea-8a270aebfe15

```

The probability of duplicating a UUID is close to zero, so they are a great

choice for generating unique identifiers in distributed systems.

UUIDs can also be stored in binary format, as a string of 16 bytes.

### Getting Started[¶](#getting-started "Permalink to this headline")

#### Requirements[¶](#requirements "Permalink to this headline")

ramsey/uuid stable requires the following:

* PHP 8.0+

* [ext-json](https://www.php.net/manual/en/book.json.php)

The JSON extension is normally enabled by default, but it is possible to disable

it. Other required extensions include

[PCRE](https://www.php.net/manual/en/book.pcre.php)

and [SPL](https://www.php.net/manual/en/book.spl.php). These standard

extensions cannot be disabled without patching PHP’s build system and/or C

sources.

ramsey/uuid recommends installing/enabling the following extensions. While not

required, these extensions improve the performance of ramsey/uuid.

* [ext-gmp](https://www.php.net/manual/en/book.gmp.php)

* [ext-bcmath](https://www.php.net/manual/en/book.bc.php)

#### Install With Composer[¶](#install-with-composer "Permalink to this headline")

The only supported installation method for ramsey/uuid is

[Composer](https://getcomposer.org). Use the following command to add

ramsey/uuid to your project dependencies:

```

composer require ramsey/uuid

```

#### Using ramsey/uuid[¶](#using-ramsey-uuid "Permalink to this headline")

After installing ramsey/uuid, the quickest way to get up-and-running is to use

the static generation methods.

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid4();

printf(

    "UUID: %s\nVersion: %d\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion()

);

```

This will return an instance of [`Ramsey\Uuid\Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4").

Tip

Use the Interfaces

Feel free to use `instanceof` to check the specific instance types of

UUIDs. However, when using type hints, it’s best to use the interfaces.

The most lenient interface is [`Ramsey\Uuid\UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface"),

while [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface") ensures the

UUIDs you’re using conform to the [RFC 4122](https://tools.ietf.org/html/rfc4122) standard. If you’re not sure

which one to use, start with the stricter

[`Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

ramsey/uuid provides a number of helpful static methods that help you work with

and generate most types of UUIDs, without any special customization of the

library.

| Method | Description |

| --- | --- |

| [`Uuid::uuid1()`](index.html#Ramsey\Uuid\Uuid::uuid1 "Ramsey\Uuid\Uuid::uuid1") | This generates a [Version 1: Gregorian Time](index.html#rfc4122-version1) UUID. |

| [`Uuid::uuid2()`](index.html#Ramsey\Uuid\Uuid::uuid2 "Ramsey\Uuid\Uuid::uuid2") | This generates a [Version 2: DCE Security](index.html#rfc4122-version2) UUID. |

| [`Uuid::uuid3()`](index.html#Ramsey\Uuid\Uuid::uuid3 "Ramsey\Uuid\Uuid::uuid3") | This generates a [Version 3: Name-based (MD5)](index.html#rfc4122-version3) UUID. |

| [`Uuid::uuid4()`](index.html#Ramsey\Uuid\Uuid::uuid4 "Ramsey\Uuid\Uuid::uuid4") | This generates a [Version 4: Random](index.html#rfc4122-version4) UUID. |

| [`Uuid::uuid5()`](index.html#Ramsey\Uuid\Uuid::uuid5 "Ramsey\Uuid\Uuid::uuid5") | This generates a [Version 5: Name-based (SHA-1)](index.html#rfc4122-version5) UUID. |

| [`Uuid::uuid6()`](index.html#Ramsey\Uuid\Uuid::uuid6 "Ramsey\Uuid\Uuid::uuid6") | This generates a [Version 6: Reordered Time](index.html#rfc4122-version6) UUID. |

| [`Uuid::uuid7()`](index.html#Ramsey\Uuid\Uuid::uuid7 "Ramsey\Uuid\Uuid::uuid7") | This generates a [Version 7: Unix Epoch Time](index.html#rfc4122-version7) UUID. |

| [`Uuid::isValid()`](index.html#Ramsey\Uuid\Uuid::isValid "Ramsey\Uuid\Uuid::isValid") | Checks whether a string is a valid UUID. |

| [`Uuid::fromString()`](index.html#Ramsey\Uuid\Uuid::fromString "Ramsey\Uuid\Uuid::fromString") | Creates a UUID instance from a string UUID. |

| [`Uuid::fromBytes()`](index.html#Ramsey\Uuid\Uuid::fromBytes "Ramsey\Uuid\Uuid::fromBytes") | Creates a UUID instance from a 16-byte string. |

| [`Uuid::fromInteger()`](index.html#Ramsey\Uuid\Uuid::fromInteger "Ramsey\Uuid\Uuid::fromInteger") | Creates a UUID instance from a string integer. |

| [`Uuid::fromDateTime()`](index.html#Ramsey\Uuid\Uuid::fromDateTime "Ramsey\Uuid\Uuid::fromDateTime") | Creates a version 1 UUID instance from a PHP [DateTimeInterface](https://www.php.net/datetimeinterface). |

### RFC 4122 UUIDs[¶](#rfc-4122-uuids "Permalink to this headline")

#### Version 1: Gregorian Time[¶](#version-1-gregorian-time "Permalink to this headline")

Attention

If you need a time-based UUID, and you don’t need the other features

included in version 1 UUIDs, we recommend using

[version 7 UUIDs](index.html#rfc4122-version7).

A version 1 UUID uses the current time, along with the MAC address (or *node*)

for a network interface on the local machine. This serves two purposes:

1. You can know *when* the identifier was created.

2. You can know *where* the identifier was created.

In a distributed system, these two pieces of information can be valuable. Not

only is there no need for a central authority to generate identifiers, but you

can determine what nodes in your infrastructure created the UUIDs and at what

time.

Tip

It is also possible to use a **randomly-generated node**, rather than a

hardware address. This is useful for when you don’t want to leak machine

information, while still using a UUID based on time. Keep reading to find

out how.

By default, ramsey/uuid will attempt to look up a MAC address for the machine it

is running on, using this value as the node. If it cannot find a MAC address, it

will generate a random node.

Generate a version 1, Gregorian time UUID[¶](#rfc4122-version1-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid1();

printf(

    "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getDateTime()->format('r'),

    $uuid->getFields()->getNode()->toString()

);

```

This will generate a version 1 UUID and print out its string representation, the

time the UUID was created, and the node used to create the UUID.

It will look something like this:

```

UUID: e22e1622-5c14-11ea-b2f3-0242ac130003

Version: 1

Date: Sun, 01 Mar 2020 23:32:15 +0000

Node: 0242ac130003

```

You may provide custom values for version 1 UUIDs, including node and clock

sequence.

Provide custom node and clock sequence to create a version 1,

Gregorian time UUID[¶](#rfc4122-version1-custom-example "Permalink to this code")

```

use Ramsey\Uuid\Provider\Node\StaticNodeProvider;

use Ramsey\Uuid\Type\Hexadecimal;

use Ramsey\Uuid\Uuid;

$nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212'));

$clockSequence = 16383;

$uuid = Uuid::uuid1($nodeProvider->getNode(), $clockSequence);

```

Tip

Version 1 UUIDs generated in ramsey/uuid are instances of UuidV1. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1") API documentation to learn

more about what you can do with a UuidV1 instance.

##### Providing a Custom Node[¶](#providing-a-custom-node "Permalink to this headline")

You may override the default behavior by passing your own node value when

generating a version 1 UUID.

In the [example above](#rfc4122-version1-custom-example), we saw how to

pass a custom node and clock sequence. An interesting thing to note about the

example is its use of StaticNodeProvider. Why didn’t we pass in a

[`Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") value, instead?

According to [RFC 4122, section 4.5](https://tools.ietf.org/html/rfc4122#section-4.5), node values that do not identify the

host — in other words, our own custom node value — should set the

unicast/multicast bit to one (1). This bit will never be set in IEEE 802

addresses obtained from network cards, so it helps to distinguish it from a

hardware MAC address.

The StaticNodeProvider sets this bit for you. This is why we used it rather

than providing a [`Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

value directly.

Recall from the example that the node value we set was `121212121212`, but if

you take a look at this value with `$uuid->getFields()->getNode()->toString()`,

it becomes:

```

131212121212

```

That’s a result of this bit being set by the StaticNodeProvider.

##### Generating a Random Node[¶](#generating-a-random-node "Permalink to this headline")

Instead of providing a custom node, you may also generate a random node each

time you generate a version 1 UUID. The RandomNodeProvider may be used to

generate a random node value, and like the StaticNodeProvider, it also sets the

unicast/multicast bit for you.

Provide a random node value to create a version 1, Gregorian time UUID[¶](#rfc4122-version1-random-example "Permalink to this code")

```

use Ramsey\Uuid\Provider\Node\RandomNodeProvider;

use Ramsey\Uuid\Uuid;

$nodeProvider = new RandomNodeProvider();

$uuid = Uuid::uuid1($nodeProvider->getNode());

```

##### What’s a Clock Sequence?[¶](#what-s-a-clock-sequence "Permalink to this headline")

The clock sequence part of a version 1 UUID helps prevent collisions. Since this

UUID is based on a timestamp and a machine node value, it is possible for

collisions to occur for multiple UUIDs generated within the same microsecond on

the same machine.

The clock sequence is the solution to this problem.

The clock sequence is a 14-bit number — this supports values from 0 to 16,383

— which means it should be possible to generate up to 16,384 UUIDs per

microsecond with the same node value, before hitting a collision.

Caution

ramsey/uuid does not use *stable storage* for clock sequence values.

Instead, all clock sequences are randomly-generated. If you are generating

a lot of version 1 UUIDs every microsecond, it is possible to hit collisions

because of the random values. If this is the case, you should use your own

mechanism for generating clock sequence values, to ensure against

randomly-generated duplicates.

See [section 4.2 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-4.2), for more information.

##### Privacy Concerns[¶](#privacy-concerns "Permalink to this headline")

As discussed earlier in this section, version 1 UUIDs use a MAC address from a

local hardware network interface. This means it is possible to uniquely identify

the machine on which a version 1 UUID was created.

If the value provided by the timestamp of a version 1 UUID is important to you,

but you do not wish to expose the interface address of any of your local

machines, see [Generating a Random Node](#rfc4122-version1-random) or [Providing a Custom Node](#rfc4122-version1-custom).

If you do not need an identifier with a timestamp value embedded in it, see

[Version 4: Random](index.html#rfc4122-version4) to learn about random UUIDs.

#### Version 2: DCE Security[¶](#version-2-dce-security "Permalink to this headline")

Tip

DCE Security UUIDs are so-called because they were defined as part of the

“Authentication and Security Services” for the [Distributed Computing

Environment](https://en.wikipedia.org/wiki/Distributed_Computing_Environment) (DCE) in the early 1990s.

Version 2 UUIDs are not widely used. See [Problems With Version 2 UUIDs](#rfc4122-version2-problems)

before deciding whether to use them.

Like a [version 1 UUID](index.html#rfc4122-version1), a version 2 UUID uses the

current time, along with the MAC address (or *node*) for a network interface on

the local machine. Additionally, a version 2 UUID replaces the low part of the

time field with a local identifier such as the user ID or group ID of the local

account that created the UUID. This serves three purposes:

1. You can know *when* the identifier was created (see

[Lossy Timestamps](#rfc4122-version2-timestamp-problems)).

2. You can know *where* the identifier was created.

3. You can know *who* created the identifier.

In a distributed system, these three pieces of information can be valuable. Not

only is there no need for a central authority to generate identifiers, but you

can determine what nodes in your infrastructure created the UUIDs, at what time

they were created, and the account on the machine that created them.

By default, ramsey/uuid will attempt to look up a MAC address for the machine it

is running on, using this value as the node. If it cannot find a MAC address, it

will generate a random node.

Use a domain to generate a version 2, DCE Security UUID[¶](#rfc4122-version2-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid2(Uuid::DCE\_DOMAIN\_PERSON);

printf(

    "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\nDomain: %s\nID: %s\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getDateTime()->format('r'),

    $uuid->getFields()->getNode()->toString(),

    $uuid->getLocalDomainName(),

    $uuid->getLocalIdentifier()->toString()

);

```

This will generate a version 2 UUID and print out its string representation, the

time the UUID was created, and the node used to create it, as well as the name

of the local domain specified and the local domain identifier (in this case, a

[POSIX](https://en.wikipedia.org/wiki/POSIX) UID, automatically obtained from the local machine).

It will look something like this:

```

UUID: 000001f5-5e9a-21ea-9e00-0242ac130003

Version: 2

Date: Thu, 05 Mar 2020 04:30:10 +0000

Node: 0242ac130003

Domain: person

ID: 501

```

Just as with version 1 UUIDs, you may provide custom values for version 2 UUIDs,

including local identifier, node, and clock sequence.

Provide custom identifier, node, and clock sequence to create a

version 2, DCE Security UUID[¶](#rfc4122-version2-custom-example "Permalink to this code")

```

use Ramsey\Uuid\Provider\Node\StaticNodeProvider;

use Ramsey\Uuid\Type\Hexadecimal;

use Ramsey\Uuid\Type\Integer;

use Ramsey\Uuid\Uuid;

$localId = new Integer(1001);

$nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212'));

$clockSequence = 63;

$uuid = Uuid::uuid2(

    Uuid::DCE\_DOMAIN\_ORG,

    $localId,

    $nodeProvider->getNode(),

    $clockSequence

);

```

Tip

Version 2 UUIDs generated in ramsey/uuid are instances of UuidV2. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV2`](index.html#Ramsey\Uuid\Rfc4122\UuidV2 "Ramsey\Uuid\Rfc4122\UuidV2") API documentation to learn

more about what you can do with a UuidV2 instance.

##### Domains[¶](#domains "Permalink to this headline")

The *domain* value tells what the local identifier represents.

If using the *person* or *group* domains, ramsey/uuid will attempt to look up

these values from the local machine. On [POSIX](https://en.wikipedia.org/wiki/POSIX) systems, it will use `id -u`

and `id -g`, respectively. On Windows, it will use `whoami` and `wmic`.

The *org* domain is site-defined. Its intent is to identify the organization

that generated the UUID, but since this can have different meanings for

different companies and projects, you get to define its value.

DCE Security Domains[¶](#rfc4122-version2-table-domains "Permalink to this table")

| Constant | Description |

| --- | --- |

| [`Uuid::DCE\_DOMAIN\_PERSON`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON "Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON") | The local identifier refers to a *person* (e.g., UID). |

| [`Uuid::DCE\_DOMAIN\_GROUP`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP "Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP") | The local identifier refers to a *group* (e.g., GID). |

| [`Uuid::DCE\_DOMAIN\_ORG`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG "Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG") | The local identifier refers to an *organization* (this is site-defined). |

Note

According to section 5.2.1.1 of [DCE 1.1: Authentication and Security Services](https://publications.opengroup.org/c311), the domain “can potentially hold

values outside the range [0, 28 – 1]; however, the only values

currently registered are in the range [0, 2].”

As a result, ramsey/uuid supports only the *person*, *group*, and *org*

domains.

##### Custom and Random Nodes[¶](#custom-and-random-nodes "Permalink to this headline")

In the [example above](#rfc4122-version2-custom-example), we provided a

custom node when generating a version 2 UUID. You may also generate random

node values.

To learn more, see the [Providing a Custom Node](index.html#rfc4122-version1-custom) and

[Generating a Random Node](index.html#rfc4122-version1-random) sections under [Version 1: Gregorian Time](index.html#rfc4122-version1).

##### Clock Sequence[¶](#clock-sequence "Permalink to this headline")

In a version 2 UUID, the clock sequence serves the same purpose as in a version

1 UUID. See [What’s a Clock Sequence?](index.html#rfc4122-version1-clock) to learn more.

Warning

The clock sequence in a version 2 UUID is a 6-bit number. It supports values

from 0 to 63. This is different from the 14-bit number used by version 1

UUIDs.

See [Limited Uniqueness](#rfc4122-version2-uniqueness-problems) to understand how this

affects version 2 UUIDs.

##### Problems With Version 2 UUIDs[¶](#problems-with-version-2-uuids "Permalink to this headline")

Version 2 UUIDs can be useful for the data they contain. However, there are

trade-offs in choosing to use them.

###### Privacy[¶](#privacy "Permalink to this headline")

Unless using a randomly-generated node, version 2 UUIDs use the MAC address for

a local hardware interface as the node value. In addition, they use a local

identifier — usually an account or group ID. Some may consider the use of

these identifying features a breach of privacy. The use of a timestamp further

complicates the issue, since these UUIDs could be used to identify a user

account on a specific machine at a specific time.

If you don’t need an identifier with a local identifier and timestamp value

embedded in it, see [Version 4: Random](index.html#rfc4122-version4) to learn about random UUIDs.

###### Limited Uniqueness[¶](#limited-uniqueness "Permalink to this headline")

With the inclusion of the local identifier and domain comes a serious limitation

in the number of unique UUIDs that may be created. This is because:

1. The local identifier replaces the lower 32 bits of the timestamp.

2. The domain replaces the lower 8 bits of the clock sequence.

As a result, the timestamp advances — the clock *ticks* — only once every

429.49 seconds (about 7 minutes). This means the clock sequence is important to

ensure uniqueness, but since the clock sequence is only 6 bits, compared to 14

bits for version 1 UUIDs, **only 64 unique UUIDs per combination of node,

domain, and identifier may be generated per 7-minute tick of the clock**.

You can overcome this lack of uniqueness by using a

[random node](#rfc4122-version2-nodes), which provides 47 bits of

randomness to the UUID — after setting the unicast/multicast bit (see

discussion on [Providing a Custom Node](index.html#rfc4122-version1-custom)) — increasing the number of UUIDs

per 7-minute clock tick to 253 (or 9,007,199,254,740,992), at the

expense of remaining locally unique.

Note

This lack of uniqueness did not present a problem for DCE, since:

> 

> [T]he security architecture of DCE depends upon the uniqueness of

> security-version UUIDs *only within the context of a cell*; that is,

> only within the context of the local [Registration Service’s]

> (persistent) datastore, and that degree of uniqueness can be guaranteed

> by the RS itself (namely, the RS maintains state in its datastore, in

> the sense that it can always check that every UUID it maintains is

> different from all other UUIDs it maintains). In other words, while

> security-version UUIDs are (like all UUIDs) specified to be “globally

> unique in space and time”, security is not compromised if they are

> merely “locally unique per cell”.

> 

> 

> —[DCE 1.1: Authentication and Security Services, section 5.2.1.1](https://publications.opengroup.org/c311)

> 

> 

> 

###### Lossy Timestamps[¶](#lossy-timestamps "Permalink to this headline")

Version 2 UUIDs are generated in the same way as version 1 UUIDs, but the low

part of the timestamp (the `time\_low` field) is replaced by a 32-bit integer

that represents a local identifier. Because of this, not only do version 2 UUIDs

have [limited uniqueness](#rfc4122-version2-uniqueness-problems), but they

also lack time precision.

When reconstructing the timestamp to return a [DateTimeInterface](https://www.php.net/datetimeinterface) instance from

[`UuidV2::getDateTime()`](index.html#Ramsey\Uuid\Rfc4122\UuidV2::getDateTime "Ramsey\Uuid\Rfc4122\UuidV2::getDateTime"),

we replace the 32 lower bits of the timestamp with zeros, since the local

identifier should not be part of the timestamp. This results in a loss of

precision, causing the timestamp to be off by a range of 0 to 429.4967295

seconds (or 7 minutes, 9 seconds, and 496,730 microseconds).

When using version 2 UUIDs, treat the timestamp as an approximation. At worst,

it could be off by about 7 minutes.

Hint

If the value 429.4967295 looks familiar, it’s because it directly

corresponds to 232 – 1, or `0xffffffff`. The local identifier is

32-bits, and we have set each of these bits to 0, so the maximum range of

timestamp drift is `0x00000000` to `0xffffffff` (counted in

100-nanosecond intervals).

#### Version 3: Name-based (MD5)[¶](#version-3-name-based-md5 "Permalink to this headline")

Attention

[RFC 4122](https://tools.ietf.org/html/rfc4122) states, “If backward compatibility is not an issue, SHA-1 is

preferred.” As a result, the use of [version 5 UUIDs](index.html#rfc4122-version5) is preferred over version 3 UUIDs, unless you have a

specific use-case for version 3 UUIDs.

Note

To learn about name-based UUIDs, read the section [Version 5: Name-based (SHA-1)](index.html#rfc4122-version5).

Version 3 UUIDs behave exactly the same as [version 5 UUIDs](index.html#rfc4122-version5). The only difference is the hashing algorithm used to

generate the UUID.

Version 3 UUIDs use [MD5](https://en.wikipedia.org/wiki/MD5) as the hashing algorithm for combining

the namespace and the name.

Due to the use of a different hashing algorithm, version 3 UUIDs generated with

any given namespace and name will differ from version 5 UUIDs generated using

the same namespace and name.

As an example, let’s take a look at generating a version 3 UUID using the same

namespace and name used in “[Generate a version 5, name-based UUID for a URL](index.html#rfc4122-version5-url-example).”

Generate a version 3, name-based UUID for a URL[¶](#rfc4122-version3-url-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid3(Uuid::NAMESPACE\_URL, 'https://www.php.net');

```

Even though the namespace and name are the same, the version 3 UUID generated

will always be `3f703955-aaba-3e70-a3cb-baff6aa3b28f`.

Likewise, we can use the custom namespace we created in

“[Generate a custom namespace UUID](index.html#rfc4122-version5-create-namespace)” to generate a version 3 UUID, but the

result will be different from the version 5 UUID with the same custom namespace

and name.

Use a custom namespace to create version 3, name-based UUIDs[¶](#rfc4122-version3-custom-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

const WIDGET\_NAMESPACE = '4bdbe8ec-5cb5-11ea-bc55-0242ac130003';

$uuid = Uuid::uuid3(WIDGET\_NAMESPACE, 'widget/1234567890');

```

With this custom namespace, the version 3 UUID for the name “widget/1234567890”

will always be `53564aa3-4154-3ca5-ac90-dba59dc7d3cb`.

Tip

Version 3 UUIDs generated in ramsey/uuid are instances of UuidV3. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV3`](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3") API documentation to learn

more about what you can do with a UuidV3 instance.

#### Version 4: Random[¶](#version-4-random "Permalink to this headline")

Version 4 UUIDs are perhaps the most popular form of UUID. They are

randomly-generated and do not contain any information about the time they are

created or the machine that generated them. If you don’t care about this

information, then a version 4 UUID might be perfect for your needs.

Generate a version 4, random UUID[¶](#rfc4122-version4-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid4();

printf(

    "UUID: %s\nVersion: %d\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion()

);

```

This will generate a version 4 UUID and print out its string representation.

It will look something like this:

```

UUID: 1ee9aa1b-6510-4105-92b9-7171bb2f3089

Version: 4

```

Tip

Version 4 UUIDs generated in ramsey/uuid are instances of UuidV4. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4") API documentation to learn

more about what you can do with a UuidV4 instance.

#### Version 5: Name-based (SHA-1)[¶](#version-5-name-based-sha-1 "Permalink to this headline")

Danger

Since [version 3](index.html#rfc4122-version3) and version 5 UUIDs essentially

use a *salt* (the namespace) to hash data, it may be tempting to use them to

hash passwords. **DO NOT do this under any circumstances!** You should not

store any sensitive information in a version 3 or version 5 UUID, since [MD5

and SHA-1 are insecure and have known attacks demonstrated against them](https://en.wikipedia.org/wiki/Hash_function_security_summary). *Use these

types of UUIDs as identifiers only.*

The first thing that comes to mind with most people think of a UUID is a

*random* identifier, but name-based UUIDs aren’t random at all. In fact, they’re

deterministic. For any given identical namespace and name, you will always

generate the same UUID.

Name-based UUIDs are useful when you need an identifier that’s based on

something’s *name* — think *identity* — and will always be the same no

matter where or when it is created.

For example, let’s say I want to create an identifier for a URL. I could use

a [version 1](index.html#rfc4122-version1) or [version 4](index.html#rfc4122-version4)

UUID to create an identifier for the URL, but what if I’m working with a

distributed system, and I want to ensure that every client in this system can

always generate the same identifier for any given URL?

This is where a name-based UUID comes in handy.

Name-based UUIDs combine a namespace with a name. This way, the UUIDs are unique

to the namespace they’re created in. [RFC 4122](https://tools.ietf.org/html/rfc4122) defines some

[predefined namespaces](index.html#reference-name-based-namespaces), one of which is

for URLs.

Note

Version 5 UUIDs use [SHA-1](https://en.wikipedia.org/wiki/SHA-1) as the hashing algorithm for combining the

namespace and the name.

Generate a version 5, name-based UUID for a URL[¶](#rfc4122-version5-url-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid5(Uuid::NAMESPACE\_URL, 'https://www.php.net');

```

The UUID generated will always be the same, as long as the namespace and name

are the same. The version 5 UUID for “<https://www.php.net>” in the URL namespace

will always be `a8f6ae40-d8a7-58f0-be05-a22f94eca9ec`. See for yourself. Run

the code above, and you’ll see it always generates the same UUID.

Tip

Version 5 UUIDs generated in ramsey/uuid are instances of UuidV5. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV5`](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5") API documentation to learn

more about what you can do with a UuidV5 instance.

##### Custom Namespaces[¶](#custom-namespaces "Permalink to this headline")

If you’re working with name-based UUIDs for names that don’t fit into any of

the [predefined namespaces](index.html#reference-name-based-namespaces), or you don’t

want to use any of the predefined namespaces, you can create your own namespace.

The best way to do this is to generate a [version 1](index.html#rfc4122-version1) or

[version 4](index.html#rfc4122-version4) UUID and save this UUID as your namespace.

Generate a custom namespace UUID[¶](#rfc4122-version5-create-namespace "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid1();

printf("My namespace UUID is %s\n", $uuid->toString());

```

This will generate a version 1, Gregorian time UUID, which we’ll store to a

constant so we can reuse it as our own custom namespace.

Use a custom namespace to create version 5, name-based UUIDs[¶](#rfc4122-version5-custom-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

const WIDGET\_NAMESPACE = '4bdbe8ec-5cb5-11ea-bc55-0242ac130003';

$uuid = Uuid::uuid5(WIDGET\_NAMESPACE, 'widget/1234567890');

```

With this custom namespace, the version 5 UUID for the name “widget/1234567890”

will always be `a35477ae-bfb1-5f2e-b5a4-4711594d855f`.

We can publish this namespace, allowing others to use it to generate identifiers

for widgets. When two or more systems try to reference the same widget, they’ll

end up generating the same identifier for it, which is exactly what we want.

#### Version 6: Reordered Time[¶](#version-6-reordered-time "Permalink to this headline")

Note

Version 6, reordered time UUIDs are a new format of UUID, proposed in an

[Internet-Draft under review](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.6) at the IETF. While the draft is still going

through the IETF process, the version 6 format is not expected to change

in any way that breaks compatibility.

Attention

If you need a time-based UUID, and you don’t need the other features

included in version 6 UUIDs, we recommend using

[version 7 UUIDs](index.html#rfc4122-version7).

Version 6 UUIDs solve [two problems that have long existed](https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/) with the use of

[version 1](index.html#rfc4122-version1) UUIDs:

1. Scattered database records

2. Inability to sort by an identifier in a meaningful way (i.e., insert order)

To overcome these issues, we need the ability to generate UUIDs that are

*monotonically increasing* while still providing all the benefits of version

1 UUIDs.

Version 6 UUIDs do this by storing the time in standard byte order, instead of

breaking it up and rearranging the time bytes, according to the [RFC 4122](https://tools.ietf.org/html/rfc4122)

definition. All other fields remain the same, and the version maintains its

position, according to RFC 4122.

In all other ways, version 6 UUIDs function like version 1 UUIDs.

Tip

Prior to version 4.0.0, ramsey/uuid provided a solution for this with the

[ordered-time codec](index.html#customize-ordered-time-codec). Use of the

ordered-time codec is still valid and acceptable. However, you may replace

UUIDs generated using the ordered-time codec with version 6 UUIDs. Keep

reading to find out how.

Generate a version 6, reordered time UUID[¶](#rfc4122-version6-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid6();

printf(

    "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getDateTime()->format('r'),

    $uuid->getFields()->getNode()->toString()

);

```

This will generate a version 6 UUID and print out its string representation, the

time the UUID was created, and the node used to create the UUID.

It will look something like this:

```

UUID: 1ea60f56-b67b-61fc-829a-0242ac130003

Version: 6

Date: Sun, 08 Mar 2020 04:29:37 +0000

Node: 0242ac130003

```

You may provide custom values for version 6 UUIDs, including node and clock

sequence.

Provide custom node and clock sequence to create a version 6,

reordered time UUID[¶](#rfc4122-version6-custom-example "Permalink to this code")

```

use Ramsey\Uuid\Provider\Node\StaticNodeProvider;

use Ramsey\Uuid\Type\Hexadecimal;

use Ramsey\Uuid\Uuid;

$nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212'));

$clockSequence = 16383;

$uuid = Uuid::uuid6($nodeProvider->getNode(), $clockSequence);

```

Tip

Version 6 UUIDs generated in ramsey/uuid are instances of UuidV6. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV6`](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6") API documentation to

learn more about what you can do with a UuidV6 instance.

##### Custom and Random Nodes[¶](#custom-and-random-nodes "Permalink to this headline")

In the [example above](#rfc4122-version6-custom-example), we provided a

custom node when generating a version 6 UUID. You may also generate random

node values.

To learn more, see the [Providing a Custom Node](index.html#rfc4122-version1-custom) and

[Generating a Random Node](index.html#rfc4122-version1-random) sections under [Version 1: Gregorian Time](index.html#rfc4122-version1).

##### Clock Sequence[¶](#clock-sequence "Permalink to this headline")

In a version 6 UUID, the clock sequence serves the same purpose as in a version

1 UUID. See [What’s a Clock Sequence?](index.html#rfc4122-version1-clock) to learn more.

##### Version 1-to-6 Conversion[¶](#version-1-to-6-conversion "Permalink to this headline")

It is possible to convert back-and-forth between version 6 and version 1 UUIDs.

Convert a version 1 UUID to a version 6 UUID[¶](#rfc4122-version6-convert-version1-example "Permalink to this code")

```

use Ramsey\Uuid\Rfc4122\UuidV1;

use Ramsey\Uuid\Rfc4122\UuidV6;

use Ramsey\Uuid\Uuid;

$uuid1 = Uuid::fromString('3960c5d8-60f8-11ea-bc55-0242ac130003');

if ($uuid1 instanceof UuidV1) {

    $uuid6 = UuidV6::fromUuidV1($uuid1);

}

```

Convert a version 6 UUID to a version 1 UUID[¶](#rfc4122-version6-convert-version6-example "Permalink to this code")

```

use Ramsey\Uuid\Rfc4122\UuidV6;

use Ramsey\Uuid\Uuid;

$uuid6 = Uuid::fromString('1ea60f83-960c-65d8-bc55-0242ac130003');

if ($uuid6 instanceof UuidV6) {

    $uuid1 = $uuid6->toUuidV1();

}

```

##### Ordered-time to Version 6 Conversion[¶](#ordered-time-to-version-6-conversion "Permalink to this headline")

You may convert UUIDs previously generated and stored using the

[ordered-time codec](index.html#customize-ordered-time-codec) into version 6 UUIDs.

Caution

If you perform this conversion, the bytes and string representation of your

UUIDs will change. This will break any software that expects your

identifiers to be fixed.

Convert an ordered-time codec encoded UUID to a version 6 UUID[¶](#rfc4122-version6-convert-ordered-time-example "Permalink to this code")

```

use Ramsey\Uuid\Codec\OrderedTimeCodec;

use Ramsey\Uuid\Rfc4122\UuidV1;

use Ramsey\Uuid\Rfc4122\UuidV6;

use Ramsey\Uuid\UuidFactory;

// The bytes of a version 1 UUID previously stored in some datastore

// after encoding to bytes with the OrderedTimeCodec.

$bytes = hex2bin('11ea60faf17c8af6ad23acde48001122');

$factory = new UuidFactory();

$codec = new OrderedTimeCodec($factory->getUuidBuilder());

$factory->setCodec($codec);

$orderedTimeUuid = $factory->fromBytes($bytes);

if ($orderedTimeUuid instanceof UuidV1) {

    $uuid6 = UuidV6::fromUuidV1($orderedTimeUuid);

}

```

##### Privacy Concerns[¶](#privacy-concerns "Permalink to this headline")

Like [version 1 UUIDs](index.html#rfc4122-version1), version 6 UUIDs use a MAC

address from a local hardware network interface. This means it is possible to

uniquely identify the machine on which a version 6 UUID was created.

If the value provided by the timestamp of a version 6 UUID is important to you,

but you do not wish to expose the interface address of any of your local

machines, see [Custom and Random Nodes](#rfc4122-version6-nodes).

If you do not need an identifier with a node value embedded in it, but you still

need the benefit of a monotonically increasing unique identifier, see

[Version 7: Unix Epoch Time](index.html#rfc4122-version7).

#### Version 7: Unix Epoch Time[¶](#version-7-unix-epoch-time "Permalink to this headline")

Note

Version 7, Unix Epoch time UUIDs are a new format of UUID, proposed in an

[Internet-Draft under review](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.7) at the IETF. While the draft is still going

through the IETF process, the version 7 format is not expected to change

in any way that breaks compatibility.

ULIDs and Version 7 UUIDs

Version 7 UUIDs are binary-compatible with [ULIDs](https://github.com/ulid/spec) (universally unique

lexicographically-sortable identifiers).

Both use a 48-bit timestamp in milliseconds since the Unix Epoch, filling

the rest with random data. Version 7 UUIDs then add the version and variant

bits required by the UUID specification, which reduces the randomness from

80 bits to 74. Otherwise, they are identical.

You may even convert a version 7 UUID to a ULID.

[See below for an example.](#rfc4122-version7-ulid)

Version 7 UUIDs solve [two problems that have long existed](https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/) with the use of

[version 1](index.html#rfc4122-version1) UUIDs:

1. Scattered database records

2. Inability to sort by an identifier in a meaningful way (i.e., insert order)

To overcome these issues, we need the ability to generate UUIDs that are

*monotonically increasing*.

[Version 6 UUIDs](index.html#rfc4122-version6) provide an excellent solution for

those who need monotonically increasing, sortable UUIDs with the features of

version 1 UUIDs (MAC address and clock sequence), but if those features aren’t

necessary for your application, using a version 6 UUID might be overkill.

Version 7 UUIDs combine random data (like version 4 UUIDs) with a timestamp (in

milliseconds since the Unix Epoch, i.e., 1970-01-01 00:00:00 UTC) to create a

monotonically increasing, sortable UUID that doesn’t have any privacy concerns,

since it doesn’t include a MAC address.

For this reason, implementations should use version 7 UUIDs over versions 1 and

6, if possible.

Generate a version 7, Unix Epoch time UUID[¶](#rfc4122-version7-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid7();

printf(

    "UUID: %s\nVersion: %d\nDate: %s\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getDateTime()->format('r'),

);

```

This will generate a version 7 UUID and print out its string representation and

the time it was created.

It will look something like this:

```

UUID: 01833ce0-3486-7bfd-84a1-ad157cf64005

Version: 7

Date: Wed, 14 Sep 2022 16:41:10 +0000

```

To use an existing date and time to generate a version 7 UUID, you may pass a

`\DateTimeInterface` instance to the `uuid7()` method.

Generate a version 7 UUID from an existing date and time[¶](#rfc4122-version7-example-datetime "Permalink to this code")

```

use DateTimeImmutable;

use Ramsey\Uuid\Uuid;

$dateTime = new DateTimeImmutable('@281474976710.655');

$uuid = Uuid::uuid7($dateTime);

printf(

    "UUID: %s\nVersion: %d\nDate: %s\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getDateTime()->format('r'),

);

```

Which will print something like this:

```

UUID: ffffffff-ffff-7964-a8f6-001336ac20cb

Version: 7

Date: Tue, 02 Aug 10889 05:31:50 +0000

```

Tip

Version 7 UUIDs generated in ramsey/uuid are instances of UuidV7. Check out

the [`Ramsey\Uuid\Rfc4122\UuidV7`](index.html#Ramsey\Uuid\Rfc4122\UuidV7 "Ramsey\Uuid\Rfc4122\UuidV7") API documentation to learn

more about what you can do with a UuidV7 instance.

##### Convert a Version 7 UUID to a ULID[¶](#convert-a-version-7-uuid-to-a-ulid "Permalink to this headline")

As mentioned in the callout above, version 7 UUIDs are binary-compatible with

[ULIDs](https://github.com/ulid/spec). This means you can encode a version 7 UUID using [Crockford’s Base 32

algorithm](https://www.crockford.com/base32.html) and it will be a valid ULID, timestamp and all.

Using the third-party library [tuupola/base32](https://packagist.org/packages/tuupola/base32), here’s how we can encode a

version 7 UUID as a ULID. Note that there’s a little bit of work to perform the

conversion, since you’re working with different bases.

Encode a version 7, Unix Epoch time UUID as a ULID[¶](#rfc4122-version7-example-ulid "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

use Tuupola\Base32;

$crockford = new Base32([

    'characters' => Base32::CROCKFORD,

    'padding' => false,

    'crockford' => true,

]);

$uuid = Uuid::uuid7();

// First, we must pad the 16-byte string to 20 bytes

// for proper conversion without data loss.

$bytes = str\_pad($uuid->getBytes(), 20, "\x00", STR\_PAD\_LEFT);

// Use Crockford's Base 32 encoding algorithm.

$encoded = $crockford->encode($bytes);

// That 20-byte string was encoded to 32 characters to avoid loss

// of data. We must strip off the first 6 characters--which are

// all zeros--to get a valid 26-character ULID string.

$ulid = substr($encoded, 6);

printf("ULID: %s\n", $ulid);

```

This will print something like this:

```

ULID: 01GCZ05N3JFRKBRWKNGCQZGP44

```

Caution

Be aware that all version 7 UUIDs may be converted to ULIDs but not all

ULIDs may be converted to UUIDs.

For that matter, all UUIDs of any version may be encoded as ULIDs, but they

will not be monotonically increasing and sortable unless they are version 7

UUIDs. You will also not be able to extract a meaningful timestamp from the

ULID, unless it was converted from a version 7 UUID.

#### Version 8: Custom[¶](#version-8-custom "Permalink to this headline")

Note

Version 8, custom UUIDs are a new format of UUID, proposed in an

[Internet-Draft under review](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.8) at the IETF. While the draft is still going

through the IETF process, the version 8 format is not expected to change

in any way that breaks compatibility.

Version 8 UUIDs allow applications to create custom UUIDs in an RFC-compatible

way. The only requirement is the version and variant bits must be set according

to the UUID specification. The bytes provided may contain any value according to

your application’s needs. Be aware, however, that other applications may not

understand the semantics of the value.

Warning

The bytes should be a 16-byte octet string, an open blob of data that you

may fill with 128 bits of information. However, bits 48 through 51 will be

replaced with the UUID version field, and bits 64 and 65 will be replaced

with the UUID variant. You must not rely on these bits for your application

needs.

Generate a version 8, custom UUID[¶](#rfc4122-version8-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff");

printf(

    "UUID: %s\nVersion: %d\n",

    $uuid->toString(),

    $uuid->getFields()->getVersion()

);

```

This will generate a version 8 UUID and print out its string representation.

It will look something like this:

```

UUID: 00112233-4455-8677-8899-aabbccddeeff

Version: 8

```

[RFC 4122](https://tools.ietf.org/html/rfc4122) defines five versions of UUID, while a [new Internet-Draft under

review](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00) defines three new versions. Each version has different generation

algorithms and properties. Which one you choose depends on your use-case. You

can find out more about their applications on the specific page for that version.

Version 1: Gregorian TimeThis version of UUID combines a timestamp, node value (in the form of a MAC

address from the local computer’s network interface), and a clock sequence

to ensure uniqueness. For more details, see [Version 1: Gregorian Time](index.html#document-rfc4122/version1).

Version 2: DCE SecurityThis version of UUID is the same as Version 1, except the `clock\_seq\_low`

field is replaced with a *local domain* and the `time\_low` field is

replaced with a *local identifier*. For more details, see

[Version 2: DCE Security](index.html#document-rfc4122/version2).

Version 3: Name-based (MD5)This version of UUID hashes together a namespace and a name to create a

deterministic UUID. The hashing algorithm used is MD5. For more details, see

[Version 3: Name-based (MD5)](index.html#document-rfc4122/version3).

Version 4: RandomThis version creates a UUID using truly-random or pseudo-random numbers. For

more details, see [Version 4: Random](index.html#document-rfc4122/version4).

Version 5: Named-based (SHA-1)This version of UUID hashes together a namespace and a name to create a

deterministic UUID. The hashing algorithm used is SHA-1. For more details,

see [Version 5: Name-based (SHA-1)](index.html#document-rfc4122/version5).

Version 6: Reordered TimeThis version of UUID combines the features of a

[version 1 UUID](index.html#rfc4122-version1) with a *monotonically increasing*

UUID. For more details, see [Version 6: Reordered Time](index.html#rfc4122-version6).

Version 7: Unix Epoch TimeThis version of UUID combines a timestamp–based on milliseconds elapsed

since the Unix Epoch–and random bytes to create a monotonically increasing,

sortable UUID without the privacy and entropy concerns associated with

version 1 and version 6 UUIDs. For more details, see [Version 7: Unix Epoch Time](index.html#rfc4122-version7).

Version 8: CustomThis version of UUID allows applications to generate custom identifiers in

an RFC-compatible format. For more details, see [Version 8: Custom](index.html#document-rfc4122/version8).

### Nonstandard UUIDs[¶](#nonstandard-uuids "Permalink to this headline")

#### Version 6: Reordered Time[¶](#version-6-reordered-time "Permalink to this headline")

Attention

This documentation has moved to [RFC 4122 UUIDs: Version 6: Reordered

Time](index.html#rfc4122-version6).

Version 6 UUIDs have been promoted to the `Rfc4122` namespace. While still

in draft form, the version 6 format is not expected to change in any way

that breaks compatibility.

The [`Ramsey\Uuid\Nonstandard\UuidV6`](index.html#Ramsey\Uuid\Nonstandard\UuidV6 "Ramsey\Uuid\Nonstandard\UuidV6") class is deprecated in

favor of [`Ramsey\Uuid\Rfc4122\UuidV6`](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6").

#### Globally Unique Identifiers (GUIDs)[¶](#globally-unique-identifiers-guids "Permalink to this headline")

Tip

Using these techniques to work with GUIDs is useful if you’re working with

identifiers that have been stored in GUID byte order. For example, this is

the case if working with the `UNIQUEIDENTIFIER` data type in Microsoft SQL

Server. This is a GUID, stored as a 16-byte binary string. If working

directly with the bytes, you may use the GUID functionality in ramsey/uuid

to properly handle this data type.

According to the Windows Dev Center article on [GUID structure](https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid#remarks), “GUIDs are the

Microsoft implementation of the distributed computing environment (DCE)

universally unique identifier.” For all intents and purposes, a GUID string

representation is identical to that of an [RFC 4122](https://tools.ietf.org/html/rfc4122) UUID. For historical

reasons, *the byte order is not*.

The [.NET Framework documentation](https://docs.microsoft.com/en-us/dotnet/api/system.guid.tobytearray#remarks) explains:

> 

> Note that the order of bytes in the returned byte array is different from

> the string representation of a Guid value. The order of the beginning

> four-byte group and the next two two-byte groups is reversed, whereas the

> order of the last two-byte group and the closing six-byte group is the same.

> 

> 

> 

This is best explained by example.

Decoding a GUID from byte representation[¶](#nonstandard-guid-decode-bytes-example "Permalink to this code")

```

use Ramsey\Uuid\FeatureSet;

use Ramsey\Uuid\UuidFactory;

// The bytes of a GUID previously stored in some datastore.

$guidBytes = hex2bin('0eab93fc9ec9584b975e9c5e68c53624');

$useGuids = true;

$featureSet = new FeatureSet($useGuids);

$factory = new UuidFactory($featureSet);

$guid = $factory->fromBytes($guidBytes);

printf(

    "Class: %s\nGUID: %s\nVersion: %d\nBytes: %s\n",

    get\_class($guid),

    $guid->toString(),

    $guid->getFields()->getVersion(),

    bin2hex($guid->getBytes())

);

```

This transforms the bytes of a GUID, as represented by `$guidBytes`, into a

[`Ramsey\Uuid\Guid\Guid`](index.html#Ramsey\Uuid\Guid\Guid "Ramsey\Uuid\Guid\Guid") instance and prints out some details about

it. It looks something like this:

```

Class: Ramsey\Uuid\Guid\Guid

GUID: fc93ab0e-c99e-4b58-975e-9c5e68c53624

Version: 4

Bytes: 0eab93fc9ec9584b975e9c5e68c53624

```

Note the difference between the string GUID and the bytes. The bytes are

arranged like this:

```

0e ab 93 fc 9e c9 58 4b 97 5e 9c 5e 68 c5 36 24

```

In an [RFC 4122](https://tools.ietf.org/html/rfc4122) UUID, the bytes are stored in the same order as you see

presented in the string representation. This is often called *network byte

order*, or *big-endian* order. In a GUID, the order of the bytes are reversed

in each grouping for the first 64 bits and stored in *little-endian* order. The

remaining 64 bits are stored in network byte order. See [Endianness](#nonstandard-guid-endianness) to learn more.

Caution

The bytes themselves do not indicate their order. If you decode GUID bytes

as a UUID or UUID bytes as a GUID, you will get the wrong values. However,

you can always create a GUID or UUID from the same string value; the bytes

for each will be in a different order, even though the string is the same.

The key is to know ahead of time in what order the bytes are stored. Then,

you will be able to decode them using the correct approach.

##### Converting GUIDs to UUIDs[¶](#converting-guids-to-uuids "Permalink to this headline")

Continuing from the example, [Decoding a GUID from byte representation](#nonstandard-guid-decode-bytes-example), we

can take the GUID string representation and convert it into a standard UUID.

Convert a GUID to a UUID[¶](#nonstandard-guid-convert-example "Permalink to this code")

```

$uuid = Uuid::fromString($guid->toString());

printf(

    "Class: %s\nUUID: %s\nVersion: %d\nBytes: %s\n",

    get\_class($uuid),

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    bin2hex($uuid->getBytes())

);

```

Because the GUID was a version 4, random UUID, this creates an instance of

[`Ramsey\Uuid\Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4") from the GUID string and prints out a

few details about it. It looks something like this:

```

Class: Ramsey\Uuid\Rfc4122\UuidV4

UUID: fc93ab0e-c99e-4b58-975e-9c5e68c53624

Version: 4

Bytes: fc93ab0ec99e4b58975e9c5e68c53624

```

Note how the UUID string is identical to the GUID string. However, the byte

order is different, since they are in big-endian order. The bytes are now

arranged like this:

```

fc 93 ab 0e c9 9e 4b 58 97 5e 9c 5e 68 c5 36 24

```

Endianness

Big-endian and little-endian refer to the ordering of bytes in a multi-byte

number. Big-endian order places the most significant byte first, followed by

the other bytes in descending order. Little-endian order places the least

significant byte first, followed by the other bytes in ascending order.

Take the hexadecimal number `0x1234`, for example. In big-endian order,

the bytes are stored as `12 34`, and in little-endian order, they are

stored as `34 12`. In either case, the number is still `0x1234`.

Networking protocols usually use big-endian ordering, while computer

processor architectures often use little-endian ordering.

The terms originated in Jonathan Swift’s *Gulliver’s Travels*, where the

Lilliputians argue over which end of a hard-boiled egg is the best end to

crack.

#### Other Nonstandard UUIDs[¶](#other-nonstandard-uuids "Permalink to this headline")

Sometimes, you might encounter a string that looks like a UUID but doesn’t

follow the [RFC 4122](https://tools.ietf.org/html/rfc4122) specification. Take this string, for example:

```

d95959bc-2ff5-43eb-fccd-14883ba8f174

```

At a glance, this looks like a valid UUID, but the variant bits don’t match RFC

4122. Instead of throwing a validation exception, ramsey/uuid will assume this

is a UUID, since it fits the format and has 128 bits, but it will represent it

as a [`Ramsey\Uuid\Nonstandard\Uuid`](index.html#Ramsey\Uuid\Nonstandard\Uuid "Ramsey\Uuid\Nonstandard\Uuid").

Create an instance of Nonstandard\Uuid from a non-RFC 4122 UUID[¶](#id1 "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::fromString('d95959bc-2ff5-43eb-fccd-14883ba8f174');

printf(

    "Class: %s\nUUID: %s\nVersion: %d\nVariant: %s\n",

    get\_class($uuid),

    $uuid->toString(),

    $uuid->getFields()->getVersion(),

    $uuid->getFields()->getVariant()

);

```

This will create a Nonstandard\Uuid from the given string and print out a few

details about it. It will look something like this:

```

Class: Ramsey\Uuid\Nonstandard\Uuid

UUID: d95959bc-2ff5-43eb-fccd-14883ba8f174

Version: 0

Variant: 7

```

Note that the version is 0. Since the variant is 7, and there is no

formal specification for this variant of UUID, ramsey/uuid has no way of knowing

what type of UUID this is.

Outside of [RFC 4122](https://tools.ietf.org/html/rfc4122), other types of UUIDs are in-use, following rules of

their own. Some of these are on their way to becoming accepted standards, while

others have historical reasons for remaining valid today. Still, others are

completely random and do not follow any rules.

For these cases, ramsey/uuid provides a special functionality to handle these

alternate, nonstandard forms.

Version 6: Reordered TimeThis is a new version of UUID that combines the features of a

[version 1 UUID](index.html#rfc4122-version1) with a *monotonically increasing*

UUID. For more details, see [Version 6: Reordered Time](index.html#nonstandard-version6).

Globally Unique Identifiers (GUIDs)A globally unique identifier, or GUID, is often used as a synonym for UUID.

A key difference is the order of the bytes. Any [RFC 4122](https://tools.ietf.org/html/rfc4122) version UUID may

be represented as a GUID. For more details, see [Globally Unique Identifiers (GUIDs)](index.html#nonstandard-guid).

Other Nonstandard UUIDsSometimes, UUID string or byte representations don’t follow [RFC 4122](https://tools.ietf.org/html/rfc4122).

Rather than reject these identifiers, ramsey/uuid returns them with the

special Nonstandard\Uuid instance type. For more details, see

[Other Nonstandard UUIDs](index.html#nonstandard-other).

### Using In a Database[¶](#using-in-a-database "Permalink to this headline")

Tip

[ramsey/uuid-doctrine](https://github.com/ramsey/uuid-doctrine) allows the use of ramsey/uuid as a [Doctrine field

type](https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/types.html). If you use Doctrine, it’s a great option for working with UUIDs and

databases.

There are several strategies to consider when working with UUIDs in a database.

Among these are whether to store the string representation or bytes and whether

the UUID column should be treated as a primary key. We’ll discuss a few of these

approaches here, but the final decision on how to use UUIDs in a database is up

to you since your needs will be different from those of others.

Note

All database code examples in this section assume the use of [MariaDB](https://mariadb.org) and

[PHP Data Objects (PDO)](https://www.php.net/pdo). If using a different database engine or

connection library, your code will differ, but the general concepts should

remain the same.

#### Storing As a String[¶](#storing-as-a-string "Permalink to this headline")

Perhaps the easiest way to store a UUID to a database is to create a `char(36)`

column and store the UUID as a string. When stored as a string, UUIDs require

no special treatment in SQL statements or when displaying them.

The primary drawback is the size. At 36 characters, UUIDs can take up a lot of

space, and when handling a lot of data, this can add up.

Create a table with a column for UUIDs[¶](#database-uuid-column-example "Permalink to this code")

```

CREATE TABLE `notes` (

 `uuid` char(36) NOT NULL,

 `notes` text NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

Using this database table, we can store the string UUID using code similar to

this (assume some of the variables in this example have been set beforehand):

Store a string UUID to the uuid column[¶](#database-uuid-column-store-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid4();

$dbh = new PDO($dsn, $username, $password);

$sth = $dbh->prepare('

 INSERT INTO notes (

 uuid,

 notes

 ) VALUES (

 :uuid,

 :notes

 )

');

$sth->execute([

    ':uuid' => $uuid->toString(),

    ':notes' => $notes,

]);

```

#### Storing As Bytes[¶](#storing-as-bytes "Permalink to this headline")

In [the previous example](#database-uuid-column-store-example), we saw how

to store the string representation of a UUID to a `char(36)` column. As

discussed, the primary drawback is the size. However, if we store the UUID in

byte form, we only need a `char(16)` column, saving over half the space.

The primary drawback with this approach is ease-of-use. Since the UUID bytes are

stored in the database, querying and selecting data becomes more difficult.

Create a table with a column for UUID bytes[¶](#database-uuid-bytes-example "Permalink to this code")

```

CREATE TABLE `notes` (

 `uuid` char(16) NOT NULL,

 `notes` text NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

Using this database table, we can store the UUID bytes using code similar to

this (again, assume some of the variables in this example have been set

beforehand):

Store UUID bytes to the uuid column[¶](#database-uuid-bytes-store-example "Permalink to this code")

```

$sth->execute([

    ':uuid' => $uuid->getBytes(),

    ':notes' => $notes,

]);

```

Now, when we `SELECT` the records from the database, we will need to convert

the `notes.uuid` column to a ramsey/uuid object, so that we are able to use

it.

Covert database UUID bytes to UuidInterface instance[¶](#database-uuid-bytes-convert-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::uuid4();

$dbh = new PDO($dsn, $username, $password);

$sth = $dbh->prepare('SELECT uuid, notes FROM notes');

$sth->execute();

foreach ($sth->fetchAll() as $record) {

    $uuid = Uuid::fromBytes($record['uuid']);

    printf(

        "UUID: %s\nNotes: %s\n\n",

        $uuid->toString(),

        $record['notes']

    );

}

```

We’ll also need to query the database using the bytes.

Look-up the record from the database, using the UUID bytes[¶](#database-uuid-bytes-select-example "Permalink to this code")

```

use Ramsey\Uuid\Uuid;

$uuid = Uuid::fromString('278198d3-fa96-4833-abab-82f9e67f4712');

$dbh = new PDO($dsn, $username, $password);

$sth = $dbh->prepare('

 SELECT uuid, notes

 FROM notes

 WHERE uuid = :uuid

');

$sth->execute([

    ':uuid' => $uuid->getBytes(),

]);

$record = $sth->fetch();

if ($record) {

    $uuid = Uuid::fromBytes($record['uuid']);

    printf(

        "UUID: %s\nNotes: %s\n\n",

        $uuid->toString(),

        $record['notes']

    );

}

```

#### Using As a Primary Key[¶](#using-as-a-primary-key "Permalink to this headline")

In the previous examples, we didn’t use the UUID as a primary key, but it’s

logical to use the `notes.uuid` field as a primary key. There’s nothing wrong

with this approach, but there are a couple of points to consider:

* InnoDB stores data in the primary key order

* All the secondary keys also contain the primary key (in InnoDB)

We’ll deal with the first point in the section, [Insertion Order and Sorting](#database-order). For the

second point, if you are using the string version of the UUID (i.e.,

`char(36)`), then not only will the primary key be large and take up a lot of

space, but every secondary key that uses that primary key will also be much

larger.

For this reason, if you choose to use UUIDs as primary keys, it might be worth

the drawbacks to use UUID bytes (i.e., `char(16)`) instead of the string

representation (see [Storing As Bytes](#database-bytes)).

Hint

If not using InnoDB with MySQL or MariaDB, consult your database engine

documentation to find whether it also has similar properties that will

factor into your use of UUIDs.

#### Using As a Unique Key[¶](#using-as-a-unique-key "Permalink to this headline")

Instead of [using UUIDs as a primary key](#database-pk), you may choose to

use an `AUTO\_INCREMENT` column with the `int unsigned` data type as a

primary key, while using a `char(36)` for UUIDs and setting a `UNIQUE KEY`

on this column. This will aid in lookups while helping keep your secondary keys

small.

Use an auto-incrementing column as primary key, with UUID as a unique key[¶](#database-id-auto-increment-uuid-unique-key "Permalink to this code")

```

CREATE TABLE `notes` (

 `id` int(11) unsigned NOT NULL AUTO\_INCREMENT,

 `uuid` char(36) NOT NULL,

 `notes` text NOT NULL,

 PRIMARY KEY (`id`),

 UNIQUE KEY `notes\_uuid\_uk` (`uuid`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

#### Insertion Order and Sorting[¶](#insertion-order-and-sorting "Permalink to this headline")

UUID versions 1, 2, 3, 4, and 5 are not *monotonically increasing*. If using

these versions as primary keys, the inserts will be random, and the data will be

scattered on disk (for InnoDB). Over time, as the database size grows, lookups

will become slower and slower.

Tip

See Percona’s “[Storing UUID Values in MySQL](https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/)” post, for more details on

the performance of UUIDs as primary keys.

To minimize these problems, two solutions have been devised:

1. [Version 6: Reordered Time](index.html#rfc4122-version6) UUIDs

2. [Version 7: Unix Epoch Time](index.html#rfc4122-version7) UUIDs

Note

We previously recommended the use of the [timestamp-first COMB](index.html#customize-timestamp-first-comb-codec) or [ordered-time](index.html#customize-ordered-time-codec) codecs to solve these problems. However,

UUID versions 6 and 7 were defined to provide these solutions in a

standardized way.

### Customization[¶](#customization "Permalink to this headline")

#### Ordered-time Codec[¶](#ordered-time-codec "Permalink to this headline")

Attention

[Version 6, reordered time UUIDs](index.html#rfc4122-version6) are a new version

of UUID that eliminate the need for the ordered-time codec. If you aren’t

currently using the ordered-time codec, and you need time-based, sortable

UUIDs, consider using version 6 UUIDs.

UUIDs arrange their bytes according to the standard recommended by [RFC 4122](https://tools.ietf.org/html/rfc4122).

Unfortunately, this means the bytes aren’t in an arrangement that supports

sorting by creation time or an otherwise incrementing value. The Percona

article, “[Storing UUID Values in MySQL](https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/),” explains at length the problems this

can cause. It also recommends a solution: the *ordered-time UUID*.

RFC 4122 version 1, Gregorian time UUIDs rearrange the bytes of the time fields

so that the lowest bytes appear first, the middle bytes are next, and the

highest bytes come last. Logical sorting is not possible with this arrangement.

An ordered-time UUID is a version 1 UUID with the time fields arranged in

logical order so that the UUIDs can be sorted by creation time. These UUIDs are

*monotonically increasing*, each one coming after the previously-created one, in

a proper sort order.

Use the ordered-time codec to generate a version 1 UUID[¶](#customize-ordered-time-codec-example "Permalink to this code")

```

use Ramsey\Uuid\Codec\OrderedTimeCodec;

use Ramsey\Uuid\UuidFactory;

$factory = new UuidFactory();

$codec = new OrderedTimeCodec($factory->getUuidBuilder());

$factory->setCodec($codec);

$orderedTimeUuid = $factory->uuid1();

printf(

    "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\nBytes: %s\n",

    $orderedTimeUuid->toString(),

    $orderedTimeUuid->getFields()->getVersion(),

    $orderedTimeUuid->getDateTime()->format('r'),

    $orderedTimeUuid->getFields()->getNode()->toString(),

    bin2hex($orderedTimeUuid->getBytes())

);

```

This will use the ordered-time codec to generate a version 1 UUID and will print

out details about the UUID similar to these:

```

UUID: 593200aa-61ae-11ea-bbf2-0242ac130003

Version: 1

Date: Mon, 09 Mar 2020 02:33:23 +0000

Node: 0242ac130003

Bytes: 11ea61ae593200aabbf20242ac130003

```

Attention

Only the byte representation is rearranged. The string representation

follows the format of a standard version 1 UUID. This means only the byte

representation of an ordered-time codec encoded UUID may be used for

sorting, such as with database results.

To store the byte representation to a database field, see

[Storing As Bytes](index.html#database-bytes).

Hint

If you use this codec and store the bytes of the UUID to the database, as

recommended above, you will need to use this codec to decode the bytes, as

well. Otherwise, the UUID string value will be incorrect.

```

// Using a factory configured with the OrderedTimeCodec, as shown above.

$orderedTimeUuid = $factory->fromBytes($bytes);

```

#### Timestamp-first COMB Codec[¶](#timestamp-first-comb-codec "Permalink to this headline")

Attention

[Version 7, Unix Epoch time UUIDs](index.html#rfc4122-version7) are a new version

of UUID that eliminate the need for the timestamp-first COMB codec. If you

aren’t currently using the timestamp-first COMB codec, and you need

time-based, sortable UUIDs, consider using version 7 UUIDs.

[Version 4, random UUIDs](index.html#rfc4122-version4) are doubly problematic when it

comes to sorting and storing to databases (see [Insertion Order and Sorting](index.html#database-order)), since

their values are random, and there is no timestamp associated with them that may

be rearranged, like with the [ordered-time codec](index.html#customize-ordered-time-codec). In 2002, Jimmy Nilsson recognized this problem

with random UUIDs and proposed a solution he called “COMBs” (see “[The Cost of

GUIDs as Primary Keys](https://www.informit.com/articles/printerfriendly/25862)”).

So-called because they *combine* random bytes with a timestamp, the

timestamp-first COMB codec replaces the first 48 bits of a version 4, random

UUID with a Unix timestamp and microseconds, creating an identifier that can be

sorted by creation time. These UUIDs are *monotonically increasing*, each one

coming after the previously-created one, in a proper sort order.

Use the timestamp-first COMB codec to generate a version 4 UUID[¶](#customize-timestamp-first-comb-codec-example "Permalink to this code")

```

use Ramsey\Uuid\Codec\TimestampFirstCombCodec;

use Ramsey\Uuid\Generator\CombGenerator;

use Ramsey\Uuid\UuidFactory;

$factory = new UuidFactory();

$codec = new TimestampFirstCombCodec($factory->getUuidBuilder());

$factory->setCodec($codec);

$factory->setRandomGenerator(new CombGenerator(

    $factory->getRandomGenerator(),

    $factory->getNumberConverter()

));

$timestampFirstComb = $factory->uuid4();

printf(

    "UUID: %s\nVersion: %d\nBytes: %s\n",

    $timestampFirstComb->toString(),

    $timestampFirstComb->getFields()->getVersion(),

    bin2hex($timestampFirstComb->getBytes())

);

```

This will use the timestamp-first COMB codec to generate a version 4 UUID with

the timestamp replacing the first 48 bits and will print out details about the

UUID similar to these:

```

UUID: 9009ebcc-cd99-4b5f-90cf-9155607d2de9

Version: 4

Bytes: 9009ebcccd994b5f90cf9155607d2de9

```

Note that the bytes are in the same order as the string representation. Unlike

the [ordered-time codec](index.html#customize-ordered-time-codec), the

timestamp-first COMB codec affects both the string representation and the byte

representation. This means either the string UUID or the bytes may be stored to

a datastore and sorted. To learn more, see [Using In a Database](index.html#database).

#### Using a Custom Calculator[¶](#using-a-custom-calculator "Permalink to this headline")

By default, ramsey/uuid uses [brick/math](https://github.com/brick/math) as its internal calculator. However,

you may change the calculator, if your needs require something else.

To swap the default calculator with your custom one, first make an adapter that

wraps your custom calculator and implements

[`Ramsey\Uuid\Math\CalculatorInterface`](index.html#Ramsey\Uuid\Math\CalculatorInterface "Ramsey\Uuid\Math\CalculatorInterface"). This might look

something like this:

Create a custom calculator wrapper that implements CalculatorInterface[¶](#customize-calculators-wrapper-example "Permalink to this code")

```

namespace MyProject;

use Other\OtherCalculator;

use Ramsey\Uuid\Math\CalculatorInterface;

use Ramsey\Uuid\Type\Integer as IntegerObject;

use Ramsey\Uuid\Type\NumberInterface;

class MyUuidCalculator implements CalculatorInterface

{

    private $internalCalculator;

    public function \_\_construct(OtherCalculator $customCalculator)

    {

        $this->internalCalculator = $customCalculator;

    }

    public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface

    {

        $value = $augend->toString();

        foreach ($addends as $addend) {

            $value = $this->internalCalculator->plus($value, $addend->toString());

        }

        return new IntegerObject($value);

    }

    /\* ... Class truncated for brevity ... \*/

}

```

The easiest way to use your custom calculator wrapper is to instantiate a new

FeatureSet, set the calculator on it, and pass the FeatureSet into a new

UuidFactory. Using the factory, you may then generate and work with UUIDs, using

your custom calculator.

Use your custom calculator wrapper when working with UUIDs[¶](#customize-calculators-use-wrapper-example "Permalink to this code")

```

use MyProject\MyUuidCalculator;

use Other\OtherCalculator;

use Ramsey\Uuid\FeatureSet;

use Ramsey\Uuid\UuidFactory;

$otherCalculator = new OtherCalculator();

$myUuidCalculator = new MyUuidCalculator($otherCalculator);

$featureSet = new FeatureSet();

$featureSet->setCalculator($myUuidCalculator);

$factory = new UuidFactory($featureSet);

$uuid = $factory->uuid1();

```

#### Using a Custom Validator[¶](#using-a-custom-validator "Permalink to this headline")

By default, ramsey/uuid validates UUID strings with the lenient validator

[`Ramsey\Uuid\Validator\GenericValidator`](index.html#Ramsey\Uuid\Validator\GenericValidator "Ramsey\Uuid\Validator\GenericValidator"). This validator ensures

the string is 36 characters, has the dashes in the correct places, and uses only

hexadecimal values. It does not ensure the string is of the RFC 4122 variant or

contains a valid version.

The validator [`Ramsey\Uuid\Rfc4122\Validator`](index.html#Ramsey\Uuid\Rfc4122\Validator "Ramsey\Uuid\Rfc4122\Validator") validates UUID

strings to ensure they match the RFC 4122 variant and contain a valid version.

Since it is not enabled by default, you will need to configure ramsey/uuid to

use it, if you want stricter validation.

Set an alternate validator to use for Uuid::isValid()[¶](#customize-validators-example "Permalink to this code")

```

use Ramsey\Uuid\Rfc4122\Validator as Rfc4122Validator;

use Ramsey\Uuid\Uuid;

use Ramsey\Uuid\UuidFactory;

$factory = new UuidFactory();

$factory->setValidator(new Rfc4122Validator());

Uuid::setFactory($factory);

if (!Uuid::isValid('2bfb5006-087b-9553-5082-e8f39337ad29')) {

    echo "This UUID is not valid!\n";

}

```

Tip

If you want to use your own validation, create a class that implements

[`Ramsey\Uuid\Validator\ValidatorInterface`](index.html#Ramsey\Uuid\Validator\ValidatorInterface "Ramsey\Uuid\Validator\ValidatorInterface") and use the

same method to set your validator on the factory.

#### Replace the Default Factory[¶](#replace-the-default-factory "Permalink to this headline")

In many of the examples throughout this documentation, we’ve seen how to

configure the factory and then use that factory to generate and work with UUIDs.

For example:

Configure the factory and use it to generate a version 1 UUID[¶](#customize-factory-example "Permalink to this code")

```

use Ramsey\Uuid\Codec\OrderedTimeCodec;

use Ramsey\Uuid\UuidFactory;

$factory = new UuidFactory();

$codec = new OrderedTimeCodec($factory->getUuidBuilder());

$factory->setCodec($codec);

$orderedTimeUuid = $factory->uuid1();

```

When doing this, the default behavior of ramsey/uuid is left intact. If we call

`Uuid::uuid1()` to generate a version 1 UUID after configuring the factory as

shown above, it won’t use [OrderedTimeCodec](index.html#customize-ordered-time-codec)

to generate the UUID.

The behavior differs between $factory->uuid1() and Uuid::uuid1()[¶](#customize-factory-behavior-example "Permalink to this code")

```

$orderedTimeUuid = $factory->uuid1();

printf(

    "UUID: %s\nBytes: %s\n\n",

    $orderedTimeUuid->toString(),

    bin2hex($orderedTimeUuid->getBytes())

);

$uuid = Uuid::uuid1();

printf(

    "UUID: %s\nBytes: %s\n\n",

    $uuid->toString(),

    bin2hex($uuid->getBytes())

);

```

In this example, we print out details for two different UUIDs. The first was

generated with the [OrderedTimeCodec](index.html#customize-ordered-time-codec) using

`$factory->uuid1()`. The second was generated using `Uuid::uuid1()`. It

looks something like this:

```

UUID: 2ff06620-6251-11ea-9791-0242ac130003

Bytes: 11ea62512ff0662097910242ac130003

UUID: 2ff09730-6251-11ea-ba64-0242ac130003

Bytes: 2ff09730625111eaba640242ac130003

```

Notice the arrangement of the bytes. The first set of bytes has been rearranged,

according to the ordered-time codec rules, but the second set of bytes remains

in the same order as the UUID string.

*Configuring the factory does not change the default behavior.*

If we want to change the default behavior, we must *replace* the factory used

by the Uuid static methods, and we can do this using the

[`Uuid::setFactory()`](index.html#Ramsey\Uuid\Uuid::setFactory "Ramsey\Uuid\Uuid::setFactory") static method.

Replace the factory to globally affect Uuid behavior[¶](#customize-factory-replace-factory-example "Permalink to this code")

```

Uuid::setFactory($factory);

$uuid = Uuid::uuid1();

```

Now, every time we call [`Uuid::uuid()`](index.html#Ramsey\Uuid\Uuid::uuid1 "Ramsey\Uuid\Uuid::uuid1"),

ramsey/uuid will use the factory configured with the [OrderedTimeCodec](index.html#customize-ordered-time-codec) to generate version 1 UUIDs.

Warning

Calling [`Uuid::setFactory()`](index.html#Ramsey\Uuid\Uuid::setFactory "Ramsey\Uuid\Uuid::setFactory") to

replace the factory will change the behavior of Uuid no matter where it is

used, so keep this in mind when replacing the factory. If you replace the

factory deep inside a method somewhere, any later code that calls a static

method on [`Ramsey\Uuid\Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") will use the new factory to

generate UUIDs.

ramsey/uuid offers a variety of ways to modify the standard behavior of the

library through dependency injection. Using [FeatureSet](https://github.com/ramsey/uuid/blob/4.x/src/FeatureSet.php), [UuidFactory](https://github.com/ramsey/uuid/blob/4.x/src/UuidFactory.php), and

[`Uuid::setFactory()`](index.html#Ramsey\Uuid\Uuid::setFactory "Ramsey\Uuid\Uuid::setFactory"), you are able

to replace just about any [builder](https://github.com/ramsey/uuid/tree/4.x/src/Builder), [codec](https://github.com/ramsey/uuid/tree/4.x/src/Codec), [converter](https://github.com/ramsey/uuid/tree/4.x/src/Converter), [generator](https://github.com/ramsey/uuid/tree/4.x/src/Generator),

[provider](https://github.com/ramsey/uuid/tree/4.x/src/Provider), and more.

Ordered-time CodecThe ordered-time codec exists to rearrange the bytes of a version 1,

Gregorian time UUID so that the timestamp portion of the UUID is

monotonically increasing. To learn more, see [Ordered-time Codec](index.html#customize-ordered-time-codec).

Timestamp-first COMB CodecThe timestamp-first COMB codec replaces part of a version 4, random UUID

with a timestamp, so that the UUID becomes monotonically increasing. To

learn more, see [Timestamp-first COMB Codec](index.html#customize-timestamp-first-comb-codec).

Using a Custom CalculatorIt’s possible to replace the default calculator ramsey/uuid uses. If your

requirements require a different solution for making calculations, see

[Using a Custom Calculator](index.html#customize-calculators).

Using a Custom ValidatorIf your requirements require a different level of validation or a different

UUID format, you may replace the default validator. See

[Using a Custom Validator](index.html#customize-validators), to learn more.

Replace the Default FactoryNot only are you able to inject alternate builders, codecs, etc. into the

factory and use the factory to generate UUIDs, you may also replace the

global, static factory used by the static methods on the Uuid class. To find

out how, see [Replace the Default Factory](index.html#customize-factory).

### Testing With UUIDs[¶](#testing-with-uuids "Permalink to this headline")

One problem with the use of `final` is the inability to create a [mock object](https://en.wikipedia.org/wiki/Mock_object)

to use in tests. However, the following techniques should help with testing.

Tip

To learn why ramsey/uuid uses `final`, take a look at [Why does ramsey/uuid use final?](index.html#faq-final).

#### Inject a UUID of a Specific Type[¶](#inject-a-uuid-of-a-specific-type "Permalink to this headline")

Let’s say we have a method that uses a type hint for [`UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1").

```

public function tellTime(UuidV1 $uuid): string

{

    return $uuid->getDateTime()->format('Y-m-d H:i:s');

}

```

Since this method uses UuidV1 as the type hint, we’re not able to pass another

object that implements UuidInterface, and we cannot extend or mock UuidV1, so

how do we test this?

One way is to use [`Uuid::uuid1()`](index.html#Ramsey\Uuid\Uuid::uuid1 "Ramsey\Uuid\Uuid::uuid1") to

create a regular UuidV1 instance and pass it.

```

public function testTellTime(): void

{

    $uuid = Uuid::uuid1();

    $myObj = new MyClass();

    $this->assertIsString($myObj->tellTime($uuid));

}

```

This might satisfy our testing needs if we only want to assert that the method

returns a string. If we want to test for a specific string, we can do that, too,

by generating a UUID ahead of time and using it as a known value.

```

public function testTellTime(): void

{

    // We generated this version 1 UUID ahead of time and know the

    // exact date and time it contains, so we can use it to test the

    // return value of our method.

    $uuid = Uuid::fromString('177ef0d8-6630-11ea-b69a-0242ac130003');

    $myObj = new MyClass();

    $this->assertSame('2020-03-14 20:12:12', $myObj->tellTime($uuid));

}

```

Note

These examples assume the use of [PHPUnit](https://phpunit.de) for tests. The concepts will

work no matter what testing framework you use.

#### Returning Specific UUIDs From a Static Method[¶](#returning-specific-uuids-from-a-static-method "Permalink to this headline")

Sometimes, rather than pass UUIDs as method arguments, we might call the static

methods on the Uuid class from inside the method we want to test. This can be

tricky to test.

```

public function tellTime(): string

{

    $uuid = Uuid::uuid1();

    return $uuid->getDateTime()->format('Y-m-d H:i:s');

}

```

We can call this in a test and assert that it returns a string, but we can’t

return a specific UUID value from the static method call — or can we?

We can do this by [overriding the default factory](index.html#customize-factory).

First, we create our own factory class for testing. In this example, we extend

UuidFactory, but you may create your own separate factory class for testing, as

long as you implement [`Ramsey\Uuid\UuidFactoryInterface`](index.html#Ramsey\Uuid\UuidFactoryInterface "Ramsey\Uuid\UuidFactoryInterface").

```

namespace MyPackage;

use Ramsey\Uuid\UuidFactory;

use Ramsey\Uuid\UuidInterface;

class MyTestUuidFactory extends UuidFactory

{

    public $uuid1;

    public function uuid1($node = null, ?int $clockSeq = null): UuidInterface

    {

        return $this->uuid1;

    }

}

```

Now, from our tests, we can replace the default factory with our new factory,

and we can even change the value returned by the [`uuid1()`](index.html#Ramsey\Uuid\UuidFactoryInterface::uuid1 "Ramsey\Uuid\UuidFactoryInterface::uuid1") method for our tests.

```

/\*\*

 \* @runInSeparateProcess

 \* @preserveGlobalState disabled

 \*/

public function testTellTime(): void

{

    $factory = new MyTestUuidFactory();

    Uuid::setFactory($factory);

    $myObj = new MyClass();

    $factory->uuid1 = Uuid::fromString('177ef0d8-6630-11ea-b69a-0242ac130003');

    $this->assertSame('2020-03-14 20:12:12', $myObj->tellTime());

    $factory->uuid1 = Uuid::fromString('13814000-1dd2-11b2-9669-00007ffffffe');

    $this->assertSame('1970-01-01 00:00:00', $myObj->tellTime());

}

```

Attention

The factory is a static property on the Uuid class. By replacing it like

this, all uses of the Uuid class after this point will continue to use the

new factory. This is why we must run the test in a separate process.

Otherwise, this could cause other tests to fail.

Running tests in separate processes can significantly slow down your tests,

so try to use this technique sparingly, and if possible, pass your

dependencies to your objects, rather than creating (or fetching them) from

within. This makes testing easier.

#### Mocking UuidInterface[¶](#mocking-uuidinterface "Permalink to this headline")

Another technique for testing with UUIDs is to mock

[`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

Consider a method that accepts a UuidInterface.

```

public function tellTime(UuidInterface $uuid): string

{

    return $uuid->getDateTime()->format('Y-m-d H:i:s');

}

```

We can mock UuidInterface, passing that mocked value into this method. Then, we

can make assertions about what methods were called on the mock object. In the

following example test, we don’t care whether the return value matches an

actual date format. What we care about is that the methods on the UuidInterface

object were called.

```

public function testTellTime(): void

{

    $dateTime = Mockery::mock(DateTime::class);

    $dateTime->expects()->format('Y-m-d H:i:s')->andReturn('a test date');

    $uuid = Mockery::mock(UuidInterface::class, [

        'getDateTime' => $dateTime,

    ]);

    $myObj = new MyClass();

    $this->assertSame('a test date', $myObj->tellTime($uuid));

}

```

Note

One of my favorite mocking libraries is [Mockery](https://github.com/mockery/mockery), so that’s what I use in

these examples. However, other mocking libraries exist, and PHPUnit provides

built-in mocking capabilities.

### Upgrading ramsey/uuid[¶](#upgrading-ramsey-uuid "Permalink to this headline")

#### Version 3 to 4[¶](#version-3-to-4 "Permalink to this headline")

I’ve made great efforts to ensure that the upgrade experience for most will be

seamless and uneventful. However, no matter the degree to which you use

ramsey/uuid (customized or unchanged), there are a number of things to be aware

of as you upgrade your code to use version 4.

Tip

These are the changes that are most likely to affect you. For a full list of

changes, take a look at the [4.0.0 changelog](https://github.com/ramsey/uuid/releases/tag/4.0.0).

##### What’s New?[¶](#what-s-new "Permalink to this headline")

There are a lot of new features in ramsey/uuid! Here are a few of them:

* Support [version 6 UUIDs](index.html#nonstandard-version6).

* Support [version 2 (DCE Security) UUIDs](index.html#rfc4122-version2).

* Add classes to represent each version of RFC 4122 UUID. When generating new

UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID

is an RFC 4122 variant, one of these instances will be returned:

	+ [`Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

	+ [`Rfc4122\UuidV2`](index.html#Ramsey\Uuid\Rfc4122\UuidV2 "Ramsey\Uuid\Rfc4122\UuidV2")

	+ [`Rfc4122\UuidV3`](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3")

	+ [`Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4")

	+ [`Rfc4122\UuidV5`](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5")

	+ `Rfc4122\NilUuid`

* Add classes to represent version 6 UUIDs, GUIDs, and nonstandard

(non-RFC 4122 variants) UUIDs:

	+ [`Nonstandard\UuidV6`](index.html#Ramsey\Uuid\Nonstandard\UuidV6 "Ramsey\Uuid\Nonstandard\UuidV6")

	+ [`Nonstandard\Uuid`](index.html#Ramsey\Uuid\Nonstandard\Uuid "Ramsey\Uuid\Nonstandard\Uuid")

	+ [`Guid\Guid`](index.html#Ramsey\Uuid\Guid\Guid "Ramsey\Uuid\Guid\Guid")

* Add [`Uuid::fromDateTime()`](index.html#Ramsey\Uuid\Uuid::fromDateTime "Ramsey\Uuid\Uuid::fromDateTime") to

create version 1 UUIDs from instances of DateTimeInterface.

##### What’s Changed?[¶](#what-s-changed "Permalink to this headline")

Attention

ramsey/uuid version 4 requires PHP 7.2 or later.

Quite a bit has changed, but much remains familiar. Unless you’ve changed the

behavior of ramsey/uuid through custom codecs, providers, generators, etc., the

standard functionality and API found in version 3 will not differ much.

Here are the highlights:

* ramsey/uuid now works on 32-bit and 64-bit systems, with no degradation in

functionality! All Degraded\* classes are deprecated and no longer used;

they’ll go away in ramsey/uuid version 5.

* Pay attention to the [return types for the static methods](#upgrading-3-to-4-static-methods) on the [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid")

class. They’ve changed slightly, but this won’t affect you if your type hints

use [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

* The [return types for three methods](#upgrading-3-to-4-return-types)

defined on [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface") have

changed, breaking backwards compatibility. **Take note and update your code.**

* [There are a number of deprecations.](#upgrading-3-to-4-deprecations)

These shouldn’t affect you now, but please take a look at the recommendations

and update your code soon. These will go away in ramsey/uuid version 5.

* ramsey/uuid now [throws custom exceptions for everything](index.html#reference-exceptions). The exception UnsatisfiedDependencyException no

longer exists.

* If you customize ramsey/uuid at all by implementing the interfaces, take a

look at the [interface](#upgrading-3-to-4-interfaces) and

[constructor](#upgrading-3-to-4-constructors) changes and update your

code.

Tip

If you maintain a public project that uses ramsey/uuid version 3 and you

find that **your code does not require any changes to upgrade** to version

4, consider using the following version constraint in your project’s

`composer.json` file:

```

composer require ramsey/uuid:"^3 || ^4"

```

This will allow any [downstream users](https://en.wikipedia.org/wiki/Downstream_(software_development)) of your project who aren’t ready to

upgrade to version 4 the ability to continue using your project while

deciding on an appropriate upgrade schedule.

If your downstream users do not specify ramsey/uuid as a dependency, and

they use functionality specific to version 3, they may need to update their

own Composer dependencies to use ramsey/uuid `^3` to avoid using version 4.

##### Uuid Static Methods[¶](#uuid-static-methods "Permalink to this headline")

All the static methods on the [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") class

continue to work as they did in version 3, with this slight change: **they now

return more-specific types**, all of which implement the new interface

[`Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface"),

which implements the familiar interface [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

If your type hints are for [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface"), then you should not require any changes.

Return types for Uuid static methods[¶](#id5 "Permalink to this table")

| Method | 3.x Returned | 4.x Returns |

| --- | --- | --- |

| [`Uuid::uuid1()`](index.html#Ramsey\Uuid\Uuid::uuid1 "Ramsey\Uuid\Uuid::uuid1") | [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") | [`Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1") |

| [`Uuid::uuid3()`](index.html#Ramsey\Uuid\Uuid::uuid3 "Ramsey\Uuid\Uuid::uuid3") | [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") | [`Rfc4122\UuidV3`](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3") |

| [`Uuid::uuid4()`](index.html#Ramsey\Uuid\Uuid::uuid4 "Ramsey\Uuid\Uuid::uuid4") | [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") | [`Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4") |

| [`Uuid::uuid5()`](index.html#Ramsey\Uuid\Uuid::uuid5 "Ramsey\Uuid\Uuid::uuid5") | [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") | [`Rfc4122\UuidV5`](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5") |

[`Uuid::fromString()`](index.html#Ramsey\Uuid\Uuid::fromString "Ramsey\Uuid\Uuid::fromString"),

[`Uuid::fromBytes()`](index.html#Ramsey\Uuid\Uuid::fromBytes "Ramsey\Uuid\Uuid::fromBytes"), and

[`Uuid::fromInteger()`](index.html#Ramsey\Uuid\Uuid::fromInteger "Ramsey\Uuid\Uuid::fromInteger") all return

an appropriate more-specific type, based on the input value. If the input value

is a version 1 UUID, for example, the return type will be an

[`Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1"). If the input looks

like a UUID or is a 128-bit number, but it doesn’t validate as an RFC 4122 UUID,

the return type will be a [`Nonstandard\Uuid`](index.html#Ramsey\Uuid\Nonstandard\Uuid "Ramsey\Uuid\Nonstandard\Uuid"). These return types implement

[`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface"). If using this as

a type hint, you shouldn’t need to make any changes.

##### Changed Return Types[¶](#changed-return-types "Permalink to this headline")

The following [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

method return types have changed in version 4 and you will need to update your

code, if you use these methods.

Changed UuidInterface method return types[¶](#id6 "Permalink to this table")

| Method | 3.x Returned | 4.x Returns |

| --- | --- | --- |

| [`UuidInterface::getFields()`](index.html#Ramsey\Uuid\UuidInterface::getFields "Ramsey\Uuid\UuidInterface::getFields") | `array` | [`Rfc4122\FieldsInterface`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface") |

| [`UuidInterface::getHex()`](index.html#Ramsey\Uuid\UuidInterface::getHex "Ramsey\Uuid\UuidInterface::getHex") | `string` | [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") |

| [`UuidInterface::getInteger()`](index.html#Ramsey\Uuid\UuidInterface::getInteger "Ramsey\Uuid\UuidInterface::getInteger") | `mixed` [1](#f1) | [`Type\Integer`](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer") |

In version 3, the following [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") methods

return `int`, `string`, or Moontoast\Math\BigNumber, depending on the

environment. In version 4, they all return numeric `string` values for the

sake of consistency. These methods [are also deprecated](#upgrading-3-to-4-deprecations-uuid) and will be removed in version 5.

* `getClockSeqHiAndReserved()`

* `getClockSeqLow()`

* `getClockSequence()`

* `getLeastSignificantBits()`

* `getMostSignificantBits()`

* `getNode()`

* `getTimeHiAndVersion()`

* `getTimeLow()`

* `getTimeMid()`

* `getTimestamp()`

##### Deprecations[¶](#deprecations "Permalink to this headline")

###### UuidInterface[¶](#uuidinterface "Permalink to this headline")

The following [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

methods are deprecated, but upgrading to version 4 should not cause any problems

if using these methods. You are encouraged to update your code according to the

recommendations, though, since these methods will go away in version 5.

Deprecated UuidInterface methods[¶](#id7 "Permalink to this table")

| Deprecated Method | Update To |

| --- | --- |

| `getDateTime()` | Use `getDateTime()` on [`UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1::getDateTime "Ramsey\Uuid\Rfc4122\UuidV1::getDateTime"), [`UuidV2`](index.html#Ramsey\Uuid\Rfc4122\UuidV2::getDateTime "Ramsey\Uuid\Rfc4122\UuidV2::getDateTime"), or [`UuidV6`](index.html#Ramsey\Uuid\Nonstandard\UuidV6::getDateTime "Ramsey\Uuid\Nonstandard\UuidV6::getDateTime") |

| `getClockSeqHiAndReservedHex()` | [`getFields()->getClockSeqHiAndReserved()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved "Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved") |

| `getClockSeqLowHex()` | [`getFields()->getClockSeqLow()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow "Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow") |

| `getClockSequenceHex()` | [`getFields()->getClockSeq()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq "Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq") |

| `getFieldsHex()` | [`getFields()`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface::getFields "Ramsey\Uuid\Rfc4122\UuidInterface::getFields") [2](#f2) |

| `getLeastSignificantBitsHex()` | `substr($uuid->getHex()->toString(), 0, 16)` |

| `getMostSignificantBitsHex()` | `substr($uuid->getHex()->toString(), 16)` |

| `getNodeHex()` | [`getFields()->getNode()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getNode "Ramsey\Uuid\Rfc4122\FieldsInterface::getNode") |

| `getNumberConverter()` | This method has no replacement; plan accordingly. |

| `getTimeHiAndVersionHex()` | [`getFields()->getTimeHiAndVersion()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion "Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion") |

| `getTimeLowHex()` | [`getFields()->getTimeLow()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow "Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow") |

| `getTimeMidHex()` | [`getFields()->getTimeMid()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid "Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid") |

| `getTimestampHex()` | [`getFields()->getTimestamp()->toString()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp "Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp") |

| `getUrn()` | `Ramsey\Uuid\Rfc4122\UuidInterface::getUrn` |

| `getVariant()` | [`getFields()->getVariant()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant "Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant") |

| `getVersion()` | [`getFields()->getVersion()`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion "Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion") |

###### Uuid[¶](#uuid "Permalink to this headline")

[`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") as an instantiable class is deprecated.

In ramsey/uuid version 5, its constructor will be `private`, and the class

will be `final`. For more information, see [Why does ramsey/uuid use final?](index.html#faq-final)

Note

[`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") is being replaced by more-specific

concrete classes, such as:

* [`Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

* [`Rfc4122\UuidV3`](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3")

* [`Rfc4122\UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4")

* [`Rfc4122\UuidV5`](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5")

* [`Nonstandard\Uuid`](index.html#Ramsey\Uuid\Nonstandard\Uuid "Ramsey\Uuid\Nonstandard\Uuid")

However, the [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") class isn’t going away.

It will still hold common constants and static methods.

* `Uuid::UUID\_TYPE\_IDENTIFIER` is deprecated. Use

`Uuid::UUID\_TYPE\_DCE\_SECURITY` instead.

* `Uuid::VALID\_PATTERN` is deprecated. Use the following instead:

> 

> 

> ```

> use Ramsey\Uuid\Validator\GenericValidator;

> use Ramsey\Uuid\Rfc4122\Validator as Rfc4122Validator;

> 

> $genericPattern = (new GenericValidator())->getPattern();

> $rfc4122Pattern = (new Rfc4122Validator())->getPattern();

> 

> ```

> 

> 

>

The following [`Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") methods are deprecated. If

using these methods, you shouldn’t have any problems on version 4, but you are

encouraged to update your code, since they will go away in version 5.

* `getClockSeqHiAndReserved()`

* `getClockSeqLow()`

* `getClockSequence()`

* `getLeastSignificantBits()`

* `getMostSignificantBits()`

* `getNode()`

* `getTimeHiAndVersion()`

* `getTimeLow()`

* `getTimeMid()`

* `getTimestamp()`

Hint

There are no direct replacements for these methods. In ramsey/uuid version

3, they returned `int` or Moontoast\Math\BigNumber values, depending

on the environment. To update your code, you should use the recommended

alternates listed in [Deprecations: UuidInterface](#upgrading-3-to-4-deprecations-uuidinterface), combined with the

arbitrary-precision mathematics library of your choice (e.g., [brick/math](https://github.com/brick/math),

[gmp](https://www.php.net/gmp), [bcmath](https://www.php.net/bcmath), etc.).

Using brick/math to convert a node to a string integer[¶](#id8 "Permalink to this code")

```

use Brick\Math\BigInteger;

$node = BigInteger::fromBase($uuid->getFields()->getNode()->toString(), 16);

```

##### Interface Changes[¶](#interface-changes "Permalink to this headline")

For those who customize ramsey/uuid by implementing the interfaces provided,

there are a few breaking changes to note.

Hint

Most existing methods on interfaces have type hints added to them. If you

implement any interfaces, please be aware of this and update your classes.

###### UuidInterface[¶](#id3 "Permalink to this headline")

| Method | Description |

| --- | --- |

| [`\_\_toString()`](index.html#Ramsey\Uuid\UuidInterface::__toString "Ramsey\Uuid\UuidInterface::__toString") | New method; returns `string` |

| `getDateTime()` | Deprecated; now returns [DateTimeInterface](https://www.php.net/datetimeinterface) |

| [`getFields()`](index.html#Ramsey\Uuid\UuidInterface::getFields "Ramsey\Uuid\UuidInterface::getFields") | Used to return `array`; now returns [`Rfc4122\FieldsInterface`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface") |

| [`getHex()`](index.html#Ramsey\Uuid\UuidInterface::getHex "Ramsey\Uuid\UuidInterface::getHex") | Used to return `string`; now returns [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") |

| [`getInteger()`](index.html#Ramsey\Uuid\UuidInterface::getInteger "Ramsey\Uuid\UuidInterface::getInteger") | New method; returns [`Type\Integer`](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer") |

###### UuidFactoryInterface[¶](#uuidfactoryinterface "Permalink to this headline")

| Method | Description |

| --- | --- |

| [`uuid2()`](index.html#Ramsey\Uuid\UuidFactoryInterface::uuid2 "Ramsey\Uuid\UuidFactoryInterface::uuid2") | New method; returns [`Rfc4122\UuidV2`](index.html#Ramsey\Uuid\Rfc4122\UuidV2 "Ramsey\Uuid\Rfc4122\UuidV2") |

| [`uuid6()`](index.html#Ramsey\Uuid\UuidFactoryInterface::uuid6 "Ramsey\Uuid\UuidFactoryInterface::uuid6") | New method; returns [`Nonstandard\UuidV6`](index.html#Ramsey\Uuid\Nonstandard\UuidV6 "Ramsey\Uuid\Nonstandard\UuidV6") |

| [`fromDateTime()`](index.html#Ramsey\Uuid\UuidFactoryInterface::fromDateTime "Ramsey\Uuid\UuidFactoryInterface::fromDateTime") | New method; returns [`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface") |

| [`fromInteger()`](index.html#Ramsey\Uuid\UuidFactoryInterface::fromInteger "Ramsey\Uuid\UuidFactoryInterface::fromInteger") | Changed to accept only strings |

| [`getValidator()`](index.html#Ramsey\Uuid\UuidFactoryInterface::getValidator "Ramsey\Uuid\UuidFactoryInterface::getValidator") | New method; returns [`UuidInterface`](index.html#Ramsey\Uuid\Validator\ValidatorInterface "Ramsey\Uuid\Validator\ValidatorInterface") |

###### Builder\UuidBuilderInterface[¶](#builder-uuidbuilderinterface "Permalink to this headline")

| Method | Description |

| --- | --- |

| `build()` | The second parameter used to accept `array $fields`; now accepts `string $bytes` |

###### Converter\TimeConverterInterface[¶](#converter-timeconverterinterface "Permalink to this headline")

| Method | Description |

| --- | --- |

| `calculateTime()` | Used to return `string[]`; now returns [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") |

| `convertTime()` | New method; returns [`Type\Time`](index.html#Ramsey\Uuid\Type\Time "Ramsey\Uuid\Type\Time") |

###### Provider\TimeProviderInterface[¶](#provider-timeproviderinterface "Permalink to this headline")

| Method | Description |

| --- | --- |

| `currentTime()` | Method removed from interface; use `getTime()` instead |

| `getTime()` | New method; returns [`Type\Time`](index.html#Ramsey\Uuid\Type\Time "Ramsey\Uuid\Type\Time") |

###### Provider\NodeProviderInterface[¶](#provider-nodeproviderinterface "Permalink to this headline")

| Method | Description |

| --- | --- |

| `getNode()` | Used to return `string|false|null`; now returns [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") |

##### Constructor Changes[¶](#constructor-changes "Permalink to this headline")

There are a handful of constructor changes that might affect your use of

ramsey/uuid, especially if you customize the library.

###### Uuid[¶](#id4 "Permalink to this headline")

The constructor for [`Ramsey\Uuid\Uuid`](index.html#Ramsey\Uuid\Uuid "Ramsey\Uuid\Uuid") is deprecated. However,

there are a few changes to it that might affect your use of this class.

The first constructor parameter used to be `array $fields` and is now

[`Rfc4122\FieldsInterface $fields`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface").

`Converter\TimeConverterInterface $timeConverter` is required as a new fourth

parameter.

###### Builder\DefaultUuidBuilder[¶](#builder-defaultuuidbuilder "Permalink to this headline")

While Builder\DefaultUuidBuilder is deprecated, it now inherits from

Rfc4122\UuidBuilder, which requires `Converter\TimeConverterInterface

$timeConverter` as its second constructor argument.

###### Provider\Node\FallbackNodeProvider[¶](#provider-node-fallbacknodeprovider "Permalink to this headline")

Provider\Node\FallbackNodeProvider now requires

`iterable<Ramsey\Uuid\Provider\NodeProviderInterface>` as its constructor

parameter.

```

use MyPackage\MyCustomNodeProvider;

use Ramsey\Uuid\Provider\Node\FallbackNodeProvider;

use Ramsey\Uuid\Provider\Node\RandomNodeProvider;

use Ramsey\Uuid\Provider\Node\SystemNodeProvider;

$nodeProviders = [];

$nodeProviders[] = new MyCustomNodeProvider();

$nodeProviders[] = new SystemNodeProvider();

$nodeProviders[] = new RandomNodeProvider();

$provider = new FallbackNodeProvider($nodeProviders);

```

###### Provider\Time\FixedTimeProvider[¶](#provider-time-fixedtimeprovider "Permalink to this headline")

The constructor for Provider\Time\FixedTimeProvider no longer accepts an

array. It accepts [`Type\Time`](index.html#Ramsey\Uuid\Type\Time "Ramsey\Uuid\Type\Time") instances.

---

Footnotes

[1](#id1)

This `mixed` return type could have been an `int`, `string`, or

Moontoast\Math\BigNumber. In version 4, ramsey/uuid cleans this up for

the sake of consistency.

[2](#id2)

The [`getFields()`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface::getFields "Ramsey\Uuid\Rfc4122\UuidInterface::getFields")

method returns a [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

instance; you will need to construct an array if you wish to match the

return value of the deprecated `getFieldsHex()` method.

#### Version 2 to 3[¶](#version-2-to-3 "Permalink to this headline")

While we have made significant internal changes to the library, we have made

every effort to ensure a seamless upgrade path from the 2.x series of this

library to 3.x.

One major breaking change is the transition from the `Rhumsaa` root namespace

to `Ramsey`. In most cases, all you will need is to change the namespace to

`Ramsey` in your code, and everything will “just work.”

Note

For more details on the namespace change, including reasons for the change,

read the blog post “[Introducing ramsey/uuid](https://benramsey.com/blog/2016/04/ramsey-uuid/)”.

Here are full details on the breaking changes to the public API of this library:

1. All namespace references of `Rhumsaa` have changed to `Ramsey`. Simply

change the namespace to `Ramsey` in your code and everything should work.

2. The console application has moved to

[ramsey/uuid-console](https://packagist.org/packages/ramsey/uuid-console).

If using the console functionality, use Composer to require

`ramsey/uuid-console`.

3. The Doctrine field type mapping has moved to

[ramsey/uuid-doctrine](https://packagist.org/packages/ramsey/uuid-doctrine).

If using the Doctrine functionality, use Composer to require

`ramsey/uuid-doctrine`.

### Frequently Asked Questions (FAQs)[¶](#frequently-asked-questions-faqs "Permalink to this headline")

* [How do I fix “rhumsaa/uuid is abandoned” messages?](#how-do-i-fix-rhumsaa-uuid-is-abandoned-messages)

* [Why does ramsey/uuid use `final`?](#why-does-ramsey-uuid-use-final)

#### [How do I fix “rhumsaa/uuid is abandoned” messages?](#id1)[¶](#how-do-i-fix-rhumsaa-uuid-is-abandoned-messages "Permalink to this headline")

When installing your project’s dependencies using Composer, you might see the

following message:

```

Package rhumsaa/uuid is abandoned; you should avoid using it. Use

ramsey/uuid instead.

```

Don’t panic. Simply execute the following commands with Composer:

```

composer remove rhumsaa/uuid

composer require ramsey/uuid=^2.9

```

After doing so, you will have the latest ramsey/uuid package in the 2.x series,

and there will be no need to modify any code; the namespace in the 2.x series is

still `Rhumsaa`.

#### [Why does ramsey/uuid use `final`?](#id2)[¶](#why-does-ramsey-uuid-use-final "Permalink to this headline")

You might notice that many of the concrete classes returned in ramsey/uuid are

marked as `final`. There are specific reasons for this choice, and I will

offer a few solutions for those looking to extend or mock the classes for

testing purposes.

##### But Why?[¶](#but-why "Permalink to this headline")

[via GIPHY](https://giphy.com/gifs/eauCbbW6MvqKI)

First, let’s take a look at why ramsey/uuid uses `final`.

UUIDs are defined by a set of rules — published as [RFC 4122](https://tools.ietf.org/html/rfc4122) — and those

rules shouldn’t change. If they do, then it’s no longer a UUID — at least not

as defined by [RFC 4122](https://tools.ietf.org/html/rfc4122).

As an example, let’s think about [`Rfc4122\UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1"). If our application wants to do something

special with this type, it might use the `instanceof` operator to check that a

variable is a UuidV1, or it might use a type hint on a method argument. If a

third-party library passes a UUID object to us that extends UuidV1 but

overrides some very important internal logic, then we may no longer have a

version 1 UUID. Perhaps we can all be adults and play nicely, but ramsey/uuid

cannot make any guarantees for any subclasses of UuidV1.

However, ramsey/uuid *can* make guarantees about classes that implement

[`UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface") or

[`Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

So, if we’re working with an instance of a class that is marked `final`, we

can guarantee that the rules for the creation of that object will not change,

even if a third-party library passes us an instance of the same class.

This is the reason why ramsey/uuid specifies certain [argument and return

types](index.html#reference-types) that are marked `final`. Since these are `final`,

ramsey/uuid is able to guarantee the type of data these value objects contain.

[`Type\Integer`](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer") should never contain

any characters other than numeral digits, and [`Type\Hexadecimal`](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal") should never contain any characters other

than hexadecimal digits. If other libraries could extend these and return them

from UUID instances, then ramsey/uuid cannot guarantee their values.

This is very similar to using strict types with `int`, `float`, or `bool`.

These types cannot change, so think of final classes in ramsey/uuid as types

that cannot change.

##### Overriding Behavior[¶](#overriding-behavior "Permalink to this headline")

You may override the behavior of ramsey/uuid as much as you want. Despite the

use of `final`, the library is very flexible. Take a look at the myriad

opportunities to change how the library works:

* [Generating a Random Node](index.html#rfc4122-version1-random)

* [Timestamp-first COMB Codec](index.html#customize-timestamp-first-comb-codec)

* [Replace the Default Factory](index.html#customize-factory)

* [And more…](index.html#customize)

ramsey/uuid is able to provide this flexibility through the use of [interfaces](https://www.php.net/interfaces),

[factories](https://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29), and [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection).

At the same time, ramsey/uuid is able to guarantee that neither a

[`UuidV1`](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1") nor a

[`UuidV4`](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4") nor an

[`Integer`](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer") nor a

[`Time`](index.html#Ramsey\Uuid\Type\Time "Ramsey\Uuid\Type\Time"), etc. will ever change because of

[downstream](https://en.wikipedia.org/wiki/Downstream_(software_development)) code.

UUIDs have specific rules that make them practically unique. ramsey/uuid ensures

that other code cannot change this expectation while allowing your code and

third-party libraries to change how UUIDs are generated and to return different

types of UUIDs not specified by [RFC 4122](https://tools.ietf.org/html/rfc4122).

##### Testing With UUIDs[¶](#testing-with-uuids "Permalink to this headline")

Sometimes, the use of `final` can throw a wrench in our ability to write

tests, but it doesn’t have to be that way. To learn a few techniques for using

ramsey/uuid instances in your tests, take a look at [Testing With UUIDs](index.html#testing).

### Reference[¶](#reference "Permalink to this headline")

#### Uuid[¶](#uuid "Permalink to this headline")

RamseyUuidUuid provides static methods for the most common functionality for

generating and working with UUIDs. It also provides constants used throughout

the ramsey/uuid library.

*class* `Ramsey\Uuid\``Uuid`[¶](#Ramsey\Uuid\Uuid "Permalink to this definition")

*constant* `UUID_TYPE_TIME`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_TIME "Permalink to this definition")

[Version 1: Gregorian Time](index.html#rfc4122-version1) UUID.

*constant* `UUID_TYPE_DCE_SECURITY`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_DCE_SECURITY "Permalink to this definition")

[Version 2: DCE Security](index.html#rfc4122-version2) UUID.

*constant* `UUID_TYPE_HASH_MD5`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_HASH_MD5 "Permalink to this definition")

[Version 3: Name-based (MD5)](index.html#rfc4122-version3) UUID.

*constant* `UUID_TYPE_RANDOM`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_RANDOM "Permalink to this definition")

[Version 4: Random](index.html#rfc4122-version4) UUID.

*constant* `UUID_TYPE_HASH_SHA1`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_HASH_SHA1 "Permalink to this definition")

[Version 5: Name-based (SHA-1)](index.html#rfc4122-version5) UUID.

*constant* `UUID_TYPE_REORDERED_TIME`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_REORDERED_TIME "Permalink to this definition")

[Version 6: Reordered Time](index.html#rfc4122-version6) UUID.

*constant* `UUID_TYPE_PEABODY`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_PEABODY "Permalink to this definition")

*Deprecated.* Use [`Uuid::UUID\_TYPE\_REORDERED\_TIME`](#Ramsey\Uuid\Uuid::UUID_TYPE_REORDERED_TIME "Ramsey\Uuid\Uuid::UUID_TYPE_REORDERED_TIME") instead.

*constant* `UUID_TYPE_UNIX_TIME`[¶](#Ramsey\Uuid\Uuid::UUID_TYPE_UNIX_TIME "Permalink to this definition")

[Version 7: Unix Epoch Time](index.html#rfc4122-version7) UUID.

*constant* `NAMESPACE_DNS`[¶](#Ramsey\Uuid\Uuid::NAMESPACE_DNS "Permalink to this definition")

The name string is a fully-qualified domain name.

*constant* `NAMESPACE_URL`[¶](#Ramsey\Uuid\Uuid::NAMESPACE_URL "Permalink to this definition")

The name string is a URL.

*constant* `NAMESPACE_OID`[¶](#Ramsey\Uuid\Uuid::NAMESPACE_OID "Permalink to this definition")

The name string is an [ISO object identifier (OID)](http://www.oid-info.com).

*constant* `NAMESPACE_X500`[¶](#Ramsey\Uuid\Uuid::NAMESPACE_X500 "Permalink to this definition")

The name string is an [X.500](https://en.wikipedia.org/wiki/X.500) [DN](https://en.wikipedia.org/wiki/Distinguished_Name) in [DER](https://www.itu.int/rec/T-REC-X.690/) or a text output format.

*constant* `NIL`[¶](#Ramsey\Uuid\Uuid::NIL "Permalink to this definition")

The nil UUID is a special form of UUID that is specified to have all 128

bits set to zero.

*constant* `DCE_DOMAIN_PERSON`[¶](#Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON "Permalink to this definition")

DCE Security principal (person) domain.

*constant* `DCE_DOMAIN_GROUP`[¶](#Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP "Permalink to this definition")

DCE Security group domain.

*constant* `DCE_DOMAIN_ORG`[¶](#Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG "Permalink to this definition")

DCE Security organization domain.

*constant* `RESERVED_NCS`[¶](#Ramsey\Uuid\Uuid::RESERVED_NCS "Permalink to this definition")

Variant identifier: reserved, NCS backward compatibility.

*constant* `RFC_4122`[¶](#Ramsey\Uuid\Uuid::RFC_4122 "Permalink to this definition")

Variant identifier: the UUID layout specified in RFC 4122.

*constant* `RESERVED_MICROSOFT`[¶](#Ramsey\Uuid\Uuid::RESERVED_MICROSOFT "Permalink to this definition")

Variant identifier: reserved, Microsoft Corporation backward compatibility.

*constant* `RESERVED_FUTURE`[¶](#Ramsey\Uuid\Uuid::RESERVED_FUTURE "Permalink to this definition")

Variant identifier: reserved for future definition.

*static* `uuid1`([*$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\Uuid::uuid1 "Permalink to this definition")

Generates a version 1, Gregorian time UUID. See [Version 1: Gregorian Time](index.html#rfc4122-version1).

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

*static* `uuid2`(*$localDomain*[, *$localIdentifier*[, *$node*[, *$clockSeq*]]])[¶](#Ramsey\Uuid\Uuid::uuid2 "Permalink to this definition")

Generates a version 2, DCE Security UUID. See [Version 2: DCE Security](index.html#rfc4122-version2).

Parameters

* **$localDomain** (*int*) – The local domain to use (one of [`Uuid::DCE\_DOMAIN\_PERSON`](#Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON "Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON"), [`Uuid::DCE\_DOMAIN\_GROUP`](#Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP "Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP"), or [`Uuid::DCE\_DOMAIN\_ORG`](#Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG "Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG"))

* **$localIdentifier** (*Ramsey\Uuid\Type\Integer|null*) – A local identifier for the domain (defaults to system UID or GID for *person* or *group*)

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 2 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV2](index.html#Ramsey\Uuid\Rfc4122\UuidV2 "Ramsey\Uuid\Rfc4122\UuidV2")

*static* `uuid3`(*$ns*, *$name*)[¶](#Ramsey\Uuid\Uuid::uuid3 "Permalink to this definition")

Generates a version 3, name-based (MD5) UUID. See [Version 3: Name-based (MD5)](index.html#rfc4122-version3).

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A version 3 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV3](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3")

*static* `uuid4`[¶](#Ramsey\Uuid\Uuid::uuid4 "Permalink to this definition")

Generates a version 4, random UUID. See [Version 4: Random](index.html#rfc4122-version4).

Returns

A version 4 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV4](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4")

*static* `uuid5`(*$ns*, *$name*)[¶](#Ramsey\Uuid\Uuid::uuid5 "Permalink to this definition")

Generates a version 5, name-based (SHA-1) UUID. See [Version 5: Name-based (SHA-1)](index.html#rfc4122-version5).

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A version 5 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV5](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5")

*static* `uuid6`([*$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\Uuid::uuid6 "Permalink to this definition")

Generates a version 6, reordered time UUID. See [Version 6: Reordered Time](index.html#rfc4122-version6).

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 6 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV6](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6")

*static* `uuid7`([*$dateTime*])[¶](#Ramsey\Uuid\Uuid::uuid7 "Permalink to this definition")

Generates a version 7, Unix Epoch time UUID. See [Version 7: Unix Epoch Time](index.html#rfc4122-version7).

Parameters

* **$dateTime** (*DateTimeInterface|null*) – The date from which to create the UUID instance

Returns

A version 7 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV7](index.html#Ramsey\Uuid\Rfc4122\UuidV7 "Ramsey\Uuid\Rfc4122\UuidV7")

*static* `fromString`(*$uuid*)[¶](#Ramsey\Uuid\Uuid::fromString "Permalink to this definition")

Creates an instance of UuidInterface from the string standard

representation.

Parameters

* **$uuid** (*string*) – The string standard representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

*static* `fromBytes`(*$bytes*)[¶](#Ramsey\Uuid\Uuid::fromBytes "Permalink to this definition")

Creates an instance of UuidInterface from a 16-byte string.

Parameters

* **$bytes** (*string*) – A 16-byte binary string representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

*static* `fromInteger`(*$integer*)[¶](#Ramsey\Uuid\Uuid::fromInteger "Permalink to this definition")

Creates an instance of UuidInterface from a 128-bit string integer.

Parameters

* **$integer** (*string*) – A 128-bit string integer representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

*static* `fromDateTime`(*$dateTime*[, *$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\Uuid::fromDateTime "Permalink to this definition")

Creates a version 1 UUID instance from a [DateTimeInterface](https://www.php.net/datetimeinterface) instance.

Parameters

* **$dateTime** (*DateTimeInterface*) – The date from which to create the UUID instance

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

*static* `isValid`(*$uuid*)[¶](#Ramsey\Uuid\Uuid::isValid "Permalink to this definition")

Validates the string standard representation of a UUID.

Parameters

* **$uuid** (*string*) – The string standard representation of a UUID

Return type

`bool`

*static* `setFactory`(*$factory*)[¶](#Ramsey\Uuid\Uuid::setFactory "Permalink to this definition")

Sets the factory used to create UUIDs.

Parameters

* **$factory** ([*Ramsey\Uuid\UuidFactoryInterface*](index.html#Ramsey\Uuid\UuidFactoryInterface "Ramsey\Uuid\UuidFactoryInterface")) – A UUID factory to use for all UUID generation

Return type

void

#### UuidInterface[¶](#namespace-Ramsey\Uuid "Permalink to this headline")

*interface* `Ramsey\Uuid\``UuidInterface`[¶](#Ramsey\Uuid\UuidInterface "Permalink to this definition")

Represents a UUID.

`compareTo`(*$other*)[¶](#Ramsey\Uuid\UuidInterface::compareTo "Permalink to this definition")

Parameters

* **$other** ([*Ramsey\Uuid\UuidInterface*](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")) – The UUID to compare

Returns

Returns `-1`, `0`, or `1` if the UUID is less than, equal to, or greater than the other UUID.

Return type

`int`

`equals`(*$other*)[¶](#Ramsey\Uuid\UuidInterface::equals "Permalink to this definition")

Parameters

* **$other** (*object|null*) – An object to test for equality with this UUID.

Returns

Returns true if the UUID is equal to the provided object.

Return type

`bool`

`getBytes`()[¶](#Ramsey\Uuid\UuidInterface::getBytes "Permalink to this definition")

Returns

A binary string representation of the UUID.

Return type

`string`

`getFields`()[¶](#Ramsey\Uuid\UuidInterface::getFields "Permalink to this definition")

Returns

The fields that comprise this UUID.

Return type

[Ramsey\Uuid\Fields\FieldsInterface](index.html#Ramsey\Uuid\Fields\FieldsInterface "Ramsey\Uuid\Fields\FieldsInterface")

`getHex`()[¶](#Ramsey\Uuid\UuidInterface::getHex "Permalink to this definition")

Returns

The hexadecimal representation of the UUID.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getInteger`()[¶](#Ramsey\Uuid\UuidInterface::getInteger "Permalink to this definition")

Returns

The integer representation of the UUID.

Return type

[Ramsey\Uuid\Type\Integer](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

`getUrn`()[¶](#Ramsey\Uuid\UuidInterface::getUrn "Permalink to this definition")

Returns

The string standard representation of the UUID as a [URN](https://tools.ietf.org/html/rfc8141).

Return type

`string`

`toString`()[¶](#Ramsey\Uuid\UuidInterface::toString "Permalink to this definition")

Returns

The string standard representation of the UUID.

Return type

`string`

`__toString`()[¶](#Ramsey\Uuid\UuidInterface::__toString "Permalink to this definition")

Returns

The string standard representation of the UUID.

Return type

`string`

#### Fields\FieldsInterface[¶](#namespace-Ramsey\Uuid\Fields "Permalink to this headline")

*interface* `Ramsey\Uuid\Fields\``FieldsInterface`[¶](#Ramsey\Uuid\Fields\FieldsInterface "Permalink to this definition")

Represents the fields of a UUID.

`getBytes`()[¶](#Ramsey\Uuid\Fields\FieldsInterface::getBytes "Permalink to this definition")

Returns

The bytes that comprise these fields.

Return type

`string`

#### Rfc4122\UuidInterface[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*interface* `Ramsey\Uuid\Rfc4122\``UuidInterface`[¶](#Ramsey\Uuid\Rfc4122\UuidInterface "Permalink to this definition")

Implements [`Ramsey\Uuid\UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

Rfc4122UuidInterface represents an RFC 4122 UUID. In addition to the

methods defined on the interface, this interface additionally defines the

following methods.

`getFields`()[¶](#Ramsey\Uuid\Rfc4122\UuidInterface::getFields "Permalink to this definition")

Returns

The fields that comprise this UUID.

Return type

[Ramsey\Uuid\Rfc4122\FieldsInterface](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface")

#### Rfc4122\FieldsInterface[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*interface* `Ramsey\Uuid\Rfc4122\``FieldsInterface`[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface "Permalink to this definition")

Implements [`Ramsey\Uuid\Fields\FieldsInterface`](index.html#Ramsey\Uuid\Fields\FieldsInterface "Ramsey\Uuid\Fields\FieldsInterface").

Rfc4122FieldsInterface represents the fields of an RFC 4122 UUID.

In addition to the methods defined on the interface, this class additionally

defines the following methods.

`getClockSeq`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq "Permalink to this definition")

Returns

The full 16-bit clock sequence, with the variant bits (two most significant bits) masked out.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getClockSeqHiAndReserved`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved "Permalink to this definition")

Returns

The high field of the clock sequence multiplexed with the variant.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getClockSeqLow`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow "Permalink to this definition")

Returns

The low field of the clock sequence.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getNode`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getNode "Permalink to this definition")

Returns

The node field.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getTimeHiAndVersion`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion "Permalink to this definition")

Returns

The high field of the timestamp multiplexed with the version.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getTimeLow`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow "Permalink to this definition")

Returns

The low field of the timestamp.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getTimeMid`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid "Permalink to this definition")

Returns

The middle field of the timestamp.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getTimestamp`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp "Permalink to this definition")

Returns

The full 60-bit timestamp, without the version.

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`getVariant`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant "Permalink to this definition")

Returns the variant, which, for RFC 4122 variant UUIDs, should always be

the value `2`.

Returns

The UUID variant.

Return type

`int`

`getVersion`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion "Permalink to this definition")

Returns

The UUID version.

Return type

`int`

`isNil`()[¶](#Ramsey\Uuid\Rfc4122\FieldsInterface::isNil "Permalink to this definition")

A *nil* UUID is a special type of UUID with all 128 bits set to zero.

Its string standard representation is always

`00000000-0000-0000-0000-000000000000`.

Returns

True if this UUID represents a nil UUID.

Return type

`bool`

#### Rfc4122\UuidV1[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV1`[¶](#Ramsey\Uuid\Rfc4122\UuidV1 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV1 represents a [version 1, Gregorian time UUID](index.html#rfc4122-version1).

In addition to providing the methods defined on the interface, this class

additionally provides the following methods.

`getDateTime`()[¶](#Ramsey\Uuid\Rfc4122\UuidV1::getDateTime "Permalink to this definition")

Returns

A date object representing the timestamp associated with the UUID.

Return type

`\DateTimeInterface`

#### Rfc4122\UuidV2[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV2`[¶](#Ramsey\Uuid\Rfc4122\UuidV2 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV2 represents a [version 2, DCE Security UUID](index.html#rfc4122-version2).

In addition to providing the methods defined on the interface, this class

additionally provides the following methods.

`getDateTime`()[¶](#Ramsey\Uuid\Rfc4122\UuidV2::getDateTime "Permalink to this definition")

Returns a [DateTimeInterface](https://www.php.net/datetimeinterface)

instance representing the timestamp associated with the UUID

Caution

It is important to note that version 2 UUIDs suffer from some loss

of timestamp precision. See [Lossy Timestamps](index.html#rfc4122-version2-timestamp-problems)

to learn more.

Returns

A date object representing the timestamp associated with the UUID

Return type

`\DateTimeInterface`

`getLocalDomain`()[¶](#Ramsey\Uuid\Rfc4122\UuidV2::getLocalDomain "Permalink to this definition")

Returns

The local domain identifier for this UUID, which is one of

[`Ramsey\Uuid\Uuid::DCE\_DOMAIN\_PERSON`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON "Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON"),

[`Ramsey\Uuid\Uuid::DCE\_DOMAIN\_GROUP`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP "Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP"), or

[`Ramsey\Uuid\Uuid::DCE\_DOMAIN\_ORG`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG "Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG")

Return type

`int`

`getLocalDomainName`()[¶](#Ramsey\Uuid\Rfc4122\UuidV2::getLocalDomainName "Permalink to this definition")

Returns

A string name associated with the local domain identifier (one of “person,” “group,” or “org”)

Return type

`string`

`getLocalIdentifier`()[¶](#Ramsey\Uuid\Rfc4122\UuidV2::getLocalIdentifier "Permalink to this definition")

Returns

The local identifier used when creating this UUID

Return type

[Ramsey\Uuid\Type\Integer](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

#### Rfc4122\UuidV3[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV3`[¶](#Ramsey\Uuid\Rfc4122\UuidV3 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV3 represents a [version 3, name-based (MD5) UUID](index.html#rfc4122-version3).

#### Rfc4122\UuidV4[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV4`[¶](#Ramsey\Uuid\Rfc4122\UuidV4 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV4 represents a [version 4, random UUID](index.html#rfc4122-version4).

#### Rfc4122\UuidV5[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV5`[¶](#Ramsey\Uuid\Rfc4122\UuidV5 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV5 represents a [version 5, name-based (SHA-1) UUID](index.html#rfc4122-version5).

#### Rfc4122\UuidV6[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV6`[¶](#Ramsey\Uuid\Rfc4122\UuidV6 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV6 represents a [version 6, reordered time UUID](index.html#rfc4122-version6). In addition to providing the methods defined on the

interface, this class additionally provides the following methods.

`getDateTime`()[¶](#Ramsey\Uuid\Rfc4122\UuidV6::getDateTime "Permalink to this definition")

Returns

A date object representing the timestamp associated with the UUID

Return type

`\DateTimeInterface`

`toUuidV1`()[¶](#Ramsey\Uuid\Rfc4122\UuidV6::toUuidV1 "Permalink to this definition")

Returns

A version 1 UUID, converted from this version 6 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

*static* `fromUuidV1`[¶](#Ramsey\Uuid\Rfc4122\UuidV6::fromUuidV1 "Permalink to this definition")

Parameters

* **$uuidV1** ([*Ramsey\Uuid\Rfc4122\UuidV1*](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")) – A version 1 UUID

Returns

A version 6 UUID, converted from the given version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV6](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6")

#### Rfc4122\UuidV7[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV7`[¶](#Ramsey\Uuid\Rfc4122\UuidV7 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV7 represents a [version 7, Unix Epoch time UUID](index.html#rfc4122-version7).

In addition to providing the methods defined on the interface, this class

additionally provides the following methods.

`getDateTime`()[¶](#Ramsey\Uuid\Rfc4122\UuidV7::getDateTime "Permalink to this definition")

Returns

A date object representing the timestamp associated with the UUID.

Return type

`\DateTimeInterface`

#### Rfc4122\UuidV8[¶](#namespace-Ramsey\Uuid\Rfc4122 "Permalink to this headline")

*class* `Ramsey\Uuid\Rfc4122\``UuidV8`[¶](#Ramsey\Uuid\Rfc4122\UuidV8 "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV8 represents a [version 8, custom UUID](index.html#rfc4122-version8).

#### Guid\Fields[¶](#namespace-Ramsey\Uuid\Guid "Permalink to this headline")

*class* `Ramsey\Uuid\Guid\``Fields`[¶](#Ramsey\Uuid\Guid\Fields "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\FieldsInterface`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface").

GuidFields represents the fields of a GUID.

#### Guid\Guid[¶](#namespace-Ramsey\Uuid\Guid "Permalink to this headline")

*class* `Ramsey\Uuid\Guid\``Guid`[¶](#Ramsey\Uuid\Guid\Guid "Permalink to this definition")

Implements [`Ramsey\Uuid\UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

Guid represents a [Globally Unique Identifiers (GUIDs)](index.html#nonstandard-guid). In addition to providing the

methods defined on the interface, this class additionally provides the

following methods.

`getFields`()[¶](#Ramsey\Uuid\Guid\Guid::getFields "Permalink to this definition")

Returns

The fields that comprise this GUID.

Return type

[Ramsey\Uuid\Guid\Fields](index.html#Ramsey\Uuid\Guid\Fields "Ramsey\Uuid\Guid\Fields")

#### Nonstandard\Fields[¶](#namespace-Ramsey\Uuid\Nonstandard "Permalink to this headline")

*class* `Ramsey\Uuid\Nonstandard\``Fields`[¶](#Ramsey\Uuid\Nonstandard\Fields "Permalink to this definition")

Implements [`Ramsey\Uuid\Rfc4122\FieldsInterface`](index.html#Ramsey\Uuid\Rfc4122\FieldsInterface "Ramsey\Uuid\Rfc4122\FieldsInterface").

NonstandardFields represents the fields of a nonstandard UUID.

#### Nonstandard\Uuid[¶](#namespace-Ramsey\Uuid\Nonstandard "Permalink to this headline")

*class* `Ramsey\Uuid\Nonstandard\``Uuid`[¶](#Ramsey\Uuid\Nonstandard\Uuid "Permalink to this definition")

Implements [`Ramsey\Uuid\UuidInterface`](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface").

NonstandardUuid represents [Other Nonstandard UUIDs](index.html#nonstandard-other). In addition to

providing the methods defined on the interface, this class additionally

provides the following methods.

`getFields`()[¶](#Ramsey\Uuid\Nonstandard\Uuid::getFields "Permalink to this definition")

Returns

The fields that comprise this UUID

Return type

[Ramsey\Uuid\Nonstandard\Fields](index.html#Ramsey\Uuid\Nonstandard\Fields "Ramsey\Uuid\Nonstandard\Fields")

#### Nonstandard\UuidV6[¶](#namespace-Ramsey\Uuid\Nonstandard "Permalink to this headline")

*class* `Ramsey\Uuid\Nonstandard\``UuidV6`[¶](#Ramsey\Uuid\Nonstandard\UuidV6 "Permalink to this definition")

Attention

[`Ramsey\Uuid\Nonstandard\UuidV6`](#Ramsey\Uuid\Nonstandard\UuidV6 "Ramsey\Uuid\Nonstandard\UuidV6") is deprecated in favor of

[`Ramsey\Uuid\Rfc4122\UuidV6`](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6"). Please migrate any code

using `Nonstandard\UuidV6` to `Rfc4122\UuidV6`. The interface is

otherwise identical.

Implements [`Ramsey\Uuid\Rfc4122\UuidInterface`](index.html#Ramsey\Uuid\Rfc4122\UuidInterface "Ramsey\Uuid\Rfc4122\UuidInterface").

UuidV6 represents a [version 6, reordered time UUID](index.html#nonstandard-version6). In addition to providing the methods defined on the

interface, this class additionally provides the following methods.

`getDateTime`()[¶](#Ramsey\Uuid\Nonstandard\UuidV6::getDateTime "Permalink to this definition")

Returns

A date object representing the timestamp associated with the UUID

Return type

`\DateTimeInterface`

`toUuidV1`()[¶](#Ramsey\Uuid\Nonstandard\UuidV6::toUuidV1 "Permalink to this definition")

Returns

A version 1 UUID, converted from this version 6 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

*static* `fromUuidV1`[¶](#Ramsey\Uuid\Nonstandard\UuidV6::fromUuidV1 "Permalink to this definition")

Parameters

* **$uuidV1** ([*Ramsey\Uuid\Rfc4122\UuidV1*](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")) – A version 1 UUID

Returns

A version 6 UUID, converted from the given version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV6](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6")

#### UuidFactoryInterface[¶](#namespace-Ramsey\Uuid "Permalink to this headline")

*interface* `Ramsey\Uuid\``UuidFactoryInterface`[¶](#Ramsey\Uuid\UuidFactoryInterface "Permalink to this definition")

Represents a UUID factory.

`getValidator`()[¶](#Ramsey\Uuid\UuidFactoryInterface::getValidator "Permalink to this definition")

Return type

[Ramsey\Uuid\Validator\ValidatorInterface](index.html#Ramsey\Uuid\Validator\ValidatorInterface "Ramsey\Uuid\Validator\ValidatorInterface")

`uuid1`([*$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid1 "Permalink to this definition")

Generates a version 1, Gregorian time UUID. See [Version 1: Gregorian Time](index.html#rfc4122-version1).

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

`uuid2`(*$localDomain*[, *$localIdentifier*[, *$node*[, *$clockSeq*]]])[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid2 "Permalink to this definition")

Generates a version 2, DCE Security UUID. See [Version 2: DCE Security](index.html#rfc4122-version2).

Parameters

* **$localDomain** (*int*) – The local domain to use (one of [`Uuid::DCE\_DOMAIN\_PERSON`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON "Ramsey\Uuid\Uuid::DCE_DOMAIN_PERSON"), [`Uuid::DCE\_DOMAIN\_GROUP`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP "Ramsey\Uuid\Uuid::DCE_DOMAIN_GROUP"), or [`Uuid::DCE\_DOMAIN\_ORG`](index.html#Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG "Ramsey\Uuid\Uuid::DCE_DOMAIN_ORG"))

* **$localIdentifier** (*Ramsey\Uuid\Type\Integer|null*) – A local identifier for the domain (defaults to system UID or GID for *person* or *group*)

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 2 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV2](index.html#Ramsey\Uuid\Rfc4122\UuidV2 "Ramsey\Uuid\Rfc4122\UuidV2")

`uuid3`(*$ns*, *$name*)[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid3 "Permalink to this definition")

Generates a version 3, name-based (MD5) UUID. See [Version 3: Name-based (MD5)](index.html#rfc4122-version3).

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A version 3 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV3](index.html#Ramsey\Uuid\Rfc4122\UuidV3 "Ramsey\Uuid\Rfc4122\UuidV3")

`uuid4`()[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid4 "Permalink to this definition")

Generates a version 4, random UUID. See [Version 4: Random](index.html#rfc4122-version4).

Returns

A version 4 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV4](index.html#Ramsey\Uuid\Rfc4122\UuidV4 "Ramsey\Uuid\Rfc4122\UuidV4")

`uuid5`(*$ns*, *$name*)[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid5 "Permalink to this definition")

Generates a version 5, name-based (SHA-1) UUID. See [Version 5: Name-based (SHA-1)](index.html#rfc4122-version5).

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A version 5 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV5](index.html#Ramsey\Uuid\Rfc4122\UuidV5 "Ramsey\Uuid\Rfc4122\UuidV5")

`uuid6`([*$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\UuidFactoryInterface::uuid6 "Permalink to this definition")

Generates a version 6, reordered time UUID. See [Version 6: Reordered Time](index.html#rfc4122-version6).

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 6 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV6](index.html#Ramsey\Uuid\Rfc4122\UuidV6 "Ramsey\Uuid\Rfc4122\UuidV6")

`fromString`(*$uuid*)[¶](#Ramsey\Uuid\UuidFactoryInterface::fromString "Permalink to this definition")

Creates an instance of UuidInterface from the string standard

representation.

Parameters

* **$uuid** (*string*) – The string standard representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

`fromBytes`(*$bytes*)[¶](#Ramsey\Uuid\UuidFactoryInterface::fromBytes "Permalink to this definition")

Creates an instance of UuidInterface from a 16-byte string.

Parameters

* **$bytes** (*string*) – A 16-byte binary string representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

`fromInteger`(*$integer*)[¶](#Ramsey\Uuid\UuidFactoryInterface::fromInteger "Permalink to this definition")

Creates an instance of UuidInterface from a 128-bit string integer.

Parameters

* **$integer** (*string*) – A 128-bit string integer representation of a UUID

Return type

[Ramsey\Uuid\UuidInterface](index.html#Ramsey\Uuid\UuidInterface "Ramsey\Uuid\UuidInterface")

`fromDateTime`(*$dateTime*[, *$node*[, *$clockSeq*]])[¶](#Ramsey\Uuid\UuidFactoryInterface::fromDateTime "Permalink to this definition")

Creates a version 1 UUID instance from a [DateTimeInterface](https://www.php.net/datetimeinterface) instance.

Parameters

* **$dateTime** (*DateTimeInterface*) – The date from which to create the UUID instance

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A version 1 UUID

Return type

[Ramsey\Uuid\Rfc4122\UuidV1](index.html#Ramsey\Uuid\Rfc4122\UuidV1 "Ramsey\Uuid\Rfc4122\UuidV1")

#### Types[¶](#namespace-Ramsey\Uuid\Type "Permalink to this headline")

*class* `Ramsey\Uuid\Type\``TypeInterface`[¶](#Ramsey\Uuid\Type\TypeInterface "Permalink to this definition")

Implements [JsonSerializable](https://www.php.net/jsonserializable) and

[Serializable](https://www.php.net/serializable).

TypeInterface ensures consistency in typed values returned by ramsey/uuid.

`toString`()[¶](#Ramsey\Uuid\Type\TypeInterface::toString "Permalink to this definition")

Return type

`string`

`__toString`()[¶](#Ramsey\Uuid\Type\TypeInterface::__toString "Permalink to this definition")

Return type

`string`

*class* `Ramsey\Uuid\Type\``NumberInterface`[¶](#Ramsey\Uuid\Type\NumberInterface "Permalink to this definition")

Implements [`Ramsey\Uuid\Type\TypeInterface`](#Ramsey\Uuid\Type\TypeInterface "Ramsey\Uuid\Type\TypeInterface").

NumberInterface ensures consistency in numeric values returned by ramsey/uuid.

`isNegative`()[¶](#Ramsey\Uuid\Type\NumberInterface::isNegative "Permalink to this definition")

Returns

True if this number is less than zero, false otherwise.

Return type

`bool`

*class* `Ramsey\Uuid\Type\``Decimal`[¶](#Ramsey\Uuid\Type\Decimal "Permalink to this definition")

Implements [`Ramsey\Uuid\Type\NumberInterface`](#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface").

A value object representing a decimal, for type-safety purposes, to ensure

that decimals returned from ramsey/uuid methods as strings are truly

decimals and not some other kind of string.

To support values as true decimals and not as floats or doubles, we store

the decimals as strings.

*class* `Ramsey\Uuid\Type\``Hexadecimal`[¶](#Ramsey\Uuid\Type\Hexadecimal "Permalink to this definition")

Implements [`Ramsey\Uuid\Type\TypeInterface`](#Ramsey\Uuid\Type\TypeInterface "Ramsey\Uuid\Type\TypeInterface").

A value object representing a hexadecimal number, for type-safety purposes,

to ensure that hexadecimal numbers returned from ramsey/uuid methods as

strings are truly hexadecimal and not some other kind of string.

*class* `Ramsey\Uuid\Type\``Integer`[¶](#Ramsey\Uuid\Type\Integer "Permalink to this definition")

Implements [`Ramsey\Uuid\Type\NumberInterface`](#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface").

A value object representing an integer, for type-safety purposes, to ensure

that integers returned from ramsey/uuid methods as strings are truly

integers and not some other kind of string.

To support large integers beyond `PHP\_INT\_MAX` and `PHP\_INT\_MIN` on both

64-bit and 32-bit systems, we store the integers as strings.

*class* `Ramsey\Uuid\Type\``Time`[¶](#Ramsey\Uuid\Type\Time "Permalink to this definition")

Implements [`Ramsey\Uuid\Type\TypeInterface`](#Ramsey\Uuid\Type\TypeInterface "Ramsey\Uuid\Type\TypeInterface").

A value object representing a timestamp, for type-safety purposes, to ensure

that timestamps used by ramsey/uuid are truly timestamp integers and not

some other kind of string or integer.

`getSeconds`()[¶](#Ramsey\Uuid\Type\Time::getSeconds "Permalink to this definition")

Return type

[`Ramsey\Uuid\Type\Integer`](#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

`getMicroseconds`()[¶](#Ramsey\Uuid\Type\Time::getMicroseconds "Permalink to this definition")

Return type

[`Ramsey\Uuid\Type\Integer`](#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

#### Exceptions[¶](#exceptions "Permalink to this headline")

All exceptions in the [`Ramsey\Uuid`](index.html#namespace-Ramsey\Uuid) namespace implement

[`Ramsey\Uuid\Exception\UuidExceptionInterface`](#Ramsey\Uuid\Exception\UuidExceptionInterface "Ramsey\Uuid\Exception\UuidExceptionInterface"). This provides

a base type you may use to catch any and all exceptions that originate from this

library.

*interface* `Ramsey\Uuid\Exception\``UuidExceptionInterface`[¶](#Ramsey\Uuid\Exception\UuidExceptionInterface "Permalink to this definition")

This is the interface all exceptions in ramsey/uuid must implement.

*exception* `Ramsey\Uuid\Exception\``BuilderNotFoundException`[¶](#Ramsey\Uuid\Exception\BuilderNotFoundException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that no suitable UUID builder could be found.

*exception* `Ramsey\Uuid\Exception\``DateTimeException`[¶](#Ramsey\Uuid\Exception\DateTimeException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that the PHP DateTime extension encountered an

exception or error.

*exception* `Ramsey\Uuid\Exception\``DceSecurityException`[¶](#Ramsey\Uuid\Exception\DceSecurityException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate an exception occurred while dealing with DCE Security

(version 2) UUIDs

*exception* `Ramsey\Uuid\Exception\``InvalidArgumentException`[¶](#Ramsey\Uuid\Exception\InvalidArgumentException "Permalink to this definition")

Extends [InvalidArgumentException](https://www.php.net/invalidargumentexception).

Thrown to indicate that the argument received is not valid.

*exception* `Ramsey\Uuid\Exception\``InvalidBytesException`[¶](#Ramsey\Uuid\Exception\InvalidBytesException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that the bytes being operated on are invalid in some way.

*exception* `Ramsey\Uuid\Exception\``InvalidUuidStringException`[¶](#Ramsey\Uuid\Exception\InvalidUuidStringException "Permalink to this definition")

Extends [`Ramsey\Uuid\Exception\InvalidArgumentException`](#Ramsey\Uuid\Exception\InvalidArgumentException "Ramsey\Uuid\Exception\InvalidArgumentException").

Thrown to indicate that the string received is not a valid UUID.

*exception* `Ramsey\Uuid\Exception\``NameException`[¶](#Ramsey\Uuid\Exception\NameException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that an error occurred while attempting to hash a

namespace and name

*exception* `Ramsey\Uuid\Exception\``NodeException`[¶](#Ramsey\Uuid\Exception\NodeException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that attempting to fetch or create a node ID encountered

an error.

*exception* `Ramsey\Uuid\Exception\``RandomSourceException`[¶](#Ramsey\Uuid\Exception\RandomSourceException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that the source of random data encountered an error.

*exception* `Ramsey\Uuid\Exception\``TimeSourceException`[¶](#Ramsey\Uuid\Exception\TimeSourceException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate that the source of time encountered an error.

*exception* `Ramsey\Uuid\Exception\``UnableToBuildUuidException`[¶](#Ramsey\Uuid\Exception\UnableToBuildUuidException "Permalink to this definition")

Extends [RuntimeException](https://www.php.net/runtimeexception).

Thrown to indicate a builder is unable to build a UUID.

*exception* `Ramsey\Uuid\Exception\``UnsupportedOperationException`[¶](#Ramsey\Uuid\Exception\UnsupportedOperationException "Permalink to this definition")

Extends [LogicException](https://www.php.net/logicexception).

Thrown to indicate that the requested operation is not supported.

#### Helper Functions[¶](#helper-functions "Permalink to this headline")

ramsey/uuid additionally provides the following helper functions, which return

only the string standard representation of a UUID.

`Ramsey\Uuid\v1([$node[, $clockSeq]])`

Generates a string standard representation of a version 1, Gregorian time UUID.

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A string standard representation of a version 1 UUID

Return type

string

`Ramsey\Uuid\v2($localDomain[, $localIdentifier[, $node[, $clockSeq]]])`

Generates a string standard representation of a version 2, DCE Security UUID.

Parameters

* **$localDomain** (*int*) – The local domain to use (one of `Uuid::DCE\_DOMAIN\_PERSON`, `Uuid::DCE\_DOMAIN\_GROUP`, or `Uuid::DCE\_DOMAIN\_ORG`)

* **$localIdentifier** (*Ramsey\Uuid\Type\Integer|null*) – A local identifier for the domain (defaults to system UID or GID for *person* or *group*)

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A string standard representation of a version 2 UUID

Return type

string

`Ramsey\Uuid\v3($ns, $name)`

Generates a string standard representation of a version 3, name-based (MD5) UUID.

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A string standard representation of a version 3 UUID

Return type

string

`Ramsey\Uuid\v4()`

Generates a string standard representation of a version 4, random UUID.

Returns

A string standard representation of a version 4 UUID

Return type

string

`Ramsey\Uuid\v5($ns, $name)`

Generates a string standard representation of a version 5, name-based (SHA-1) UUID.

Parameters

* **$ns** (*Ramsey\Uuid\UuidInterface|string*) – The namespace for this identifier

* **$name** (*string*) – The name from which to generate an identifier

Returns

A string standard representation of a version 5 UUID

Return type

string

`Ramsey\Uuid\v6([$node[, $clockSeq]])`

Generates a string standard representation of a version 6, reordered time UUID.

Parameters

* **$node** (*Ramsey\Uuid\Type\Hexadecimal|null*) – An optional hexadecimal node to use

* **$clockSeq** (*int|null*) – An optional clock sequence to use

Returns

A string standard representation of a version 6 UUID

Return type

string

#### Predefined Namespaces[¶](#predefined-namespaces "Permalink to this headline")

[RFC 4122](https://tools.ietf.org/html/rfc4122) defines a handful of UUIDs to use with “for some potentially

interesting name spaces.”

| Constant | Description |

| --- | --- |

| [`Uuid::NAMESPACE\_DNS`](index.html#Ramsey\Uuid\Uuid::NAMESPACE_DNS "Ramsey\Uuid\Uuid::NAMESPACE_DNS") | The name string is a fully-qualified domain name. |

| [`Uuid::NAMESPACE\_URL`](index.html#Ramsey\Uuid\Uuid::NAMESPACE_URL "Ramsey\Uuid\Uuid::NAMESPACE_URL") | The name string is a URL. |

| [`Uuid::NAMESPACE\_OID`](index.html#Ramsey\Uuid\Uuid::NAMESPACE_OID "Ramsey\Uuid\Uuid::NAMESPACE_OID") | The name string is an [ISO object identifier (OID)](http://www.oid-info.com). |

| [`Uuid::NAMESPACE\_X500`](index.html#Ramsey\Uuid\Uuid::NAMESPACE_X500 "Ramsey\Uuid\Uuid::NAMESPACE_X500") | The name string is an [X.500](https://en.wikipedia.org/wiki/X.500) [DN](https://en.wikipedia.org/wiki/Distinguished_Name) in [DER](https://www.itu.int/rec/T-REC-X.690/) or a text output format. |

#### Calculators[¶](#namespace-Ramsey\Uuid\Math "Permalink to this headline")

*interface* `Ramsey\Uuid\Math\``CalculatorInterface`[¶](#Ramsey\Uuid\Math\CalculatorInterface "Permalink to this definition")

Provides functionality for performing mathematical calculations.

`add`(*$augend*, *...$addends*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::add "Permalink to this definition")

Parameters

* **$augend** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The first addend (the integer being added to)

* **...$addends** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The additional integers to a add to the augend

Returns

The sum of all the parameters

Return type

[Ramsey\Uuid\Type\NumberInterface](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")

`subtract`(*$minuend*, *...$subtrahends*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::subtract "Permalink to this definition")

Parameters

* **$minuend** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The integer being subtracted from

* **...$subtrahends** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The integers to subtract from the minuend

Returns

The difference after subtracting all parameters

Return type

[Ramsey\Uuid\Type\NumberInterface](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")

`multiply`(*$multiplicand*, *...$multipliers*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::multiply "Permalink to this definition")

Parameters

* **$multiplicand** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The integer to be multiplied

* **...$multipliers** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The factors by which to multiply the multiplicand

Returns

The product of multiplying all the provided parameters

Return type

[Ramsey\Uuid\Type\NumberInterface](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")

`divide`(*$roundingMode*, *$scale*, *$dividend*, *...$divisors*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::divide "Permalink to this definition")

Parameters

* **$roundingMode** (*int*) – The strategy for rounding the quotient; one of the [`Ramsey\Uuid\Math\RoundingMode`](#Ramsey\Uuid\Math\RoundingMode "Ramsey\Uuid\Math\RoundingMode") constants

* **$scale** (*int*) – The scale to use for the operation

* **$dividend** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The integer to be divided

* **...$divisors** ([*Ramsey\Uuid\Type\NumberInterface*](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")) – The integers to divide `$dividend` by, in the order in which the division operations should take place (left-to-right)

Returns

The quotient of dividing the provided parameters left-to-right

Return type

[Ramsey\Uuid\Type\NumberInterface](index.html#Ramsey\Uuid\Type\NumberInterface "Ramsey\Uuid\Type\NumberInterface")

`fromBase`(*$value*, *$base*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::fromBase "Permalink to this definition")

Converts a value from an arbitrary base to a base-10 integer value.

Parameters

* **$value** (*string*) – The value to convert

* **$base** (*int*) – The base to convert from (i.e., 2, 16, 32, etc.)

Returns

The base-10 integer value of the converted value

Return type

[Ramsey\Uuid\Type\Integer](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

`toBase`(*$value*, *$base*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::toBase "Permalink to this definition")

Converts a base-10 integer value to an arbitrary base.

Parameters

* **$value** ([*Ramsey\Uuid\Type\Integer*](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")) – The integer value to convert

* **$base** (*int*) – The base to convert to (i.e., 2, 16, 32, etc.)

Returns

The value represented in the specified base

Return type

`string`

`toHexadecimal`(*$value*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::toHexadecimal "Permalink to this definition")

Converts an Integer instance to a Hexadecimal instance.

Parameters

* **$value** ([*Ramsey\Uuid\Type\Integer*](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")) – The Integer to convert to Hexadecimal

Return type

[Ramsey\Uuid\Type\Hexadecimal](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")

`toInteger`(*$value*)[¶](#Ramsey\Uuid\Math\CalculatorInterface::toInteger "Permalink to this definition")

Converts a Hexadecimal instance to an Integer instance.

Parameters

* **$value** ([*Ramsey\Uuid\Type\Hexadecimal*](index.html#Ramsey\Uuid\Type\Hexadecimal "Ramsey\Uuid\Type\Hexadecimal")) – The Hexadecimal to convert to Integer

Return type

[Ramsey\Uuid\Type\Integer](index.html#Ramsey\Uuid\Type\Integer "Ramsey\Uuid\Type\Integer")

*class* `Ramsey\Uuid\Math\``RoundingMode`[¶](#Ramsey\Uuid\Math\RoundingMode "Permalink to this definition")

*constant* `UNNECESSARY`[¶](#Ramsey\Uuid\Math\RoundingMode::UNNECESSARY "Permalink to this definition")

Asserts that the requested operation has an exact result, hence no

rounding is necessary.

*constant* `UP`[¶](#Ramsey\Uuid\Math\RoundingMode::UP "Permalink to this definition")

Rounds away from zero.

Always increments the digit prior to a nonzero discarded fraction.

Note that this rounding mode never decreases the magnitude of the

calculated value.

*constant* `DOWN`[¶](#Ramsey\Uuid\Math\RoundingMode::DOWN "Permalink to this definition")

Rounds towards zero.

Never increments the digit prior to a discarded fraction (i.e.,

truncates). Note that this rounding mode never increases the magnitude of

the calculated value.

*constant* `CEILING`[¶](#Ramsey\Uuid\Math\RoundingMode::CEILING "Permalink to this definition")

Rounds towards positive infinity.

If the result is positive, behaves as for [`UP`](#Ramsey\Uuid\Math\RoundingMode::UP "Ramsey\Uuid\Math\RoundingMode::UP"); if negative, behaves as for

[`DOWN`](#Ramsey\Uuid\Math\RoundingMode::DOWN "Ramsey\Uuid\Math\RoundingMode::DOWN"). Note that

this rounding mode never decreases the calculated value.

*constant* `FLOOR`[¶](#Ramsey\Uuid\Math\RoundingMode::FLOOR "Permalink to this definition")

Rounds towards negative infinity.

If the result is positive, behave as for [`DOWN`](#Ramsey\Uuid\Math\RoundingMode::DOWN "Ramsey\Uuid\Math\RoundingMode::DOWN"); if negative, behave as for

[`UP`](#Ramsey\Uuid\Math\RoundingMode::UP "Ramsey\Uuid\Math\RoundingMode::UP"). Note that this

rounding mode never increases the calculated value.

*constant* `HALF_UP`[¶](#Ramsey\Uuid\Math\RoundingMode::HALF_UP "Permalink to this definition")

Rounds towards “nearest neighbor” unless both neighbors are equidistant,

in which case round up.

Behaves as for [`UP`](#Ramsey\Uuid\Math\RoundingMode::UP "Ramsey\Uuid\Math\RoundingMode::UP") if

the discarded fraction is >= 0.5; otherwise, behaves as for

[`DOWN`](#Ramsey\Uuid\Math\RoundingMode::DOWN "Ramsey\Uuid\Math\RoundingMode::DOWN"). Note that

this is the rounding mode commonly taught at school.

*constant* `HALF_DOWN`[¶](#Ramsey\Uuid\Math\RoundingMode::HALF_DOWN "Permalink to this definition")

Rounds towards “nearest neighbor” unless both neighbors are equidistant,

in which case round down.

Behaves as for [`UP`](#Ramsey\Uuid\Math\RoundingMode::UP "Ramsey\Uuid\Math\RoundingMode::UP") if

the discarded fraction is > 0.5; otherwise, behaves as for

[`DOWN`](#Ramsey\Uuid\Math\RoundingMode::DOWN "Ramsey\Uuid\Math\RoundingMode::DOWN").

*constant* `HALF_CEILING`[¶](#Ramsey\Uuid\Math\RoundingMode::HALF_CEILING "Permalink to this definition")

Rounds towards “nearest neighbor” unless both neighbors are equidistant,

in which case round towards positive infinity.

If the result is positive, behaves as for [`HALF\_UP`](#Ramsey\Uuid\Math\RoundingMode::HALF_UP "Ramsey\Uuid\Math\RoundingMode::HALF_UP"); if negative, behaves as

for [`HALF\_DOWN`](#Ramsey\Uuid\Math\RoundingMode::HALF_DOWN "Ramsey\Uuid\Math\RoundingMode::HALF_DOWN").

*constant* `HALF_FLOOR`[¶](#Ramsey\Uuid\Math\RoundingMode::HALF_FLOOR "Permalink to this definition")

Rounds towards “nearest neighbor” unless both neighbors are equidistant,

in which case round towards negative infinity.

If the result is positive, behaves as for [`HALF\_DOWN`](#Ramsey\Uuid\Math\RoundingMode::HALF_DOWN "Ramsey\Uuid\Math\RoundingMode::HALF_DOWN"); if negative, behaves as

for [`HALF\_UP`](#Ramsey\Uuid\Math\RoundingMode::HALF_UP "Ramsey\Uuid\Math\RoundingMode::HALF_UP").

*constant* `HALF_EVEN`[¶](#Ramsey\Uuid\Math\RoundingMode::HALF_EVEN "Permalink to this definition")

Rounds towards the “nearest neighbor” unless both neighbors are

equidistant, in which case rounds towards the even neighbor.

Behaves as for [`HALF\_UP`](#Ramsey\Uuid\Math\RoundingMode::HALF_UP "Ramsey\Uuid\Math\RoundingMode::HALF_UP")

if the digit to the left of the discarded fraction is odd; behaves as

for [`HALF\_DOWN`](#Ramsey\Uuid\Math\RoundingMode::HALF_DOWN "Ramsey\Uuid\Math\RoundingMode::HALF_DOWN")

if it’s even.

Note that this is the rounding mode that statistically minimizes

cumulative error when applied repeatedly over a sequence of calculations.

It is sometimes known as “Banker’s rounding”, and is chiefly used in the

USA.

#### Validators[¶](#namespace-Ramsey\Uuid\Validator "Permalink to this headline")

*interface* `Ramsey\Uuid\Validator\``ValidatorInterface`[¶](#Ramsey\Uuid\Validator\ValidatorInterface "Permalink to this definition")

`getPattern`()[¶](#Ramsey\Uuid\Validator\ValidatorInterface::getPattern "Permalink to this definition")

Returns

The regular expression pattern used by this validator

Return type

`string`

`validate`(*$uuid*)[¶](#Ramsey\Uuid\Validator\ValidatorInterface::validate "Permalink to this definition")

Parameters

* **$uuid** (*string*) – The string to validate as a UUID

Returns

True if the provided string represents a UUID, false otherwise

Return type

`bool`

*class* `Ramsey\Uuid\Validator\``GenericValidator`[¶](#Ramsey\Uuid\Validator\GenericValidator "Permalink to this definition")

Implements [`Ramsey\Uuid\Validator\ValidatorInterface`](#Ramsey\Uuid\Validator\ValidatorInterface "Ramsey\Uuid\Validator\ValidatorInterface").

GenericValidator validates strings as UUIDs of any variant.

*class* `Ramsey\Uuid\Rfc4122\``Validator`[¶](#Ramsey\Uuid\Rfc4122\Validator "Permalink to this definition")

Implements [`Ramsey\Uuid\Validator\ValidatorInterface`](#Ramsey\Uuid\Validator\ValidatorInterface "Ramsey\Uuid\Validator\ValidatorInterface").

Rfc4122Validator validates strings as UUIDs of the RFC 4122 variant.

### Copyright[¶](#copyright "Permalink to this headline")

Copyright © 2012-2023 Ben Ramsey <[ben@benramsey.com](mailto:ben%40benramsey.com)>

This work is licensed under the Creative Commons Attribution 4.0 International

License. To view a copy of this license, visit

<http://creativecommons.org/licenses/by/4.0/> or send a letter to Creative

Commons, PO Box 1866, Mountain View, CA 94042, USA.

### ramsey/uuid for Enterprise[¶](#ramsey-uuid-for-enterprise "Permalink to this headline")

Available as part of the Tidelift Subscription

Tidelift is working with the maintainers of ramsey/uuid and thousands of other

open source projects to deliver commercial support and maintenance for the open

source dependencies you use to build your applications. Save time, reduce risk,

and improve code health, while paying the maintainers of the exact dependencies

you use.

**[Learn More](https://tidelift.com/subscription/pkg/packagist-ramsey-uuid?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise)   [Request a Demo](https://tidelift.com/subscription/request-a-demo?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise)**

Enterprise-ready open source software — managed for you

The Tidelift Subscription is a managed open source subscription for application

dependencies covering millions of open source projects across JavaScript,

Python, Java, PHP, Ruby, .NET, and more.

Your subscription includes:

Security updatesTidelift’s security response team coordinates patches for new breaking

security vulnerabilities and alerts immediately through a private channel,

so your software supply chain is always secure.

Licensing verification and indemnificationTidelift verifies license information to enable easy policy enforcement and

adds intellectual property indemnification to cover creators and users in

case something goes wrong. You always have a 100% up-to-date bill of

materials for your dependencies to share with your legal team, customers,

or partners.

Maintenance and code improvementTidelift ensures the software you rely on keeps working as long as you need

it to work. Your managed dependencies are actively maintained and we recruit

additional maintainers where required.

Package selection and version guidanceWe help you choose the best open source packages from the start—and then

guide you through updates to stay on the best releases as new issues arise.

Roadmap inputTake a seat at the table with the creators behind the software you use.

Tidelift’s participating maintainers earn more income as their software is

used by more subscribers, so they’re interested in knowing what you need.

Tooling and cloud integrationTidelift works with GitHub, GitLab, BitBucket, and more. We support every

cloud platform (and other deployment targets, too).

The end result? All of the capabilities you expect from commercial-grade

software, for the full breadth of open source you use. That means less time

grappling with esoteric open source trivia, and more time building your own

applications—and your business.

**[Learn More](https://tidelift.com/subscription/pkg/packagist-ramsey-uuid?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise)   [Request a Demo](https://tidelift.com/subscription/request-a-demo?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise)**

Indices and Tables[¶](#indices-and-tables "Permalink to this headline")

-----------------------------------------------------------------------

* [Index](genindex.html)

* [Search Page](search.html)

