What are Codecs?
Codec's are used to encode and decode UUIDs into and from a certain format. Ramsey\Uuid uses them to create the string representation of the UUID aswell as the binary one.
There is a presentation that shows some of the ways to use alternate codecs. Starting at slide 46, you can see examples using different codecs. benramsey.com: UUID Talk
The default codec is StringCodec. If you create a FeatureSet passing true to the useGuids parameter it will use GuidStringCodec.
Change the Codec
You can use a different codec by creating a factory and setting a new Codec.
For example: (StringCodec is the default, to use it you don't need this! Its just meant to be an example.)
namespace Ramsey\Uuid;
$factory = new UuidFactory();
$codec = new Codec\StringCodec(
$factory->getUuidBuilder()
);
$factory->setCodec($codec);
$uuid = $factory->uuid1();
However, if you'd like to replace the default factory so that calling Uuid::uuid1() (or another version) uses it, you may do something like this:
Uuid::setFactory($factory);
$uuid = Uuid::uuid1();
Create your own codecs
You can create your own codec, just implement the Codec\CodecInterface or extend one of the included codecs.
Store UUID in an optimized way for InnoDB (OrderedTimeCodec)
From Karthik Appigatla on the Percona blog "Store UUID in an optimized way":
- UUID has 36 characters which makes it bulky.
- InnoDB stores data in the PRIMARY KEY order and all the secondary keys also contain PRIMARY KEY.
So having UUID as PRIMARY KEY makes the index bigger which can not be fit into the memory
- Inserts are random and the data is scattered.
He goes on to "explain how to store UUID in an efficient way by re-arranging timestamp part of UUID."
Ramsey\Uuid allows to do this by using the codec OrderedTimeCodec.
You can use the codec as show above. For example:
namespace Ramsey\Uuid;
$factory = new UuidFactory();
$codec = new Codec\OrderedTimeCodec(
$factory->getUuidBuilder()
);
$factory->setCodec($codec);
$orderedTimeUuid = $factory->uuid1();
Getting the optimized UUID:
$orderedTimeUuid->getBytes()
Get the human readable UUID:
$orderedTimeUuid->toString()
(string) $orderedTimeUuid
There is some more information in the UUID Talk of Ben Ramsey. The OrderedTimeCodec starts at slide 61. benramsey.com: UUID Talk