Replace the Default Factory

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
use Ramsey\Uuid\Codec\OrderedTimeCodec;
use Ramsey\Uuid\UuidFactory;

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


$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 to generate the UUID.

The behavior differs between $factory->uuid1() and Uuid::uuid1()
$orderedTimeUuid = $factory->uuid1();

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

$uuid = Uuid::uuid1();

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

In this example, we print out details for two different UUIDs. The first was generated with the OrderedTimeCodec 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() static method.

Replace the factory to globally affect Uuid behavior

$uuid = Uuid::uuid1();

Now, every time we call Uuid::uuid(), ramsey/uuid will use the factory configured with the OrderedTimeCodec to generate version 1 UUIDs.


Calling 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 will use the new factory to generate UUIDs.