PHP.GT

Quick start guide

In this guide we will build the smallest useful phpgt/ulid setup from scratch.

The main public entry point is GT\Ulid\Ulid. Most projects can stop there. The rest of the library exists to help us inspect or customise IDs when we need more control.

1. Install the package

composer require phpgt/ulid

2. Construct an ID

use GT\Ulid\Ulid;

$id = new Ulid();
echo $id;

Example output:

01KPKT4PFTKVQ9P1E72F

This is the default shape of the identifier:

  • 10 characters of timestamp
  • 10 characters of randomness

The timestamp section sorts lexicographically, so newer IDs compare greater than older ones.

3. Add a prefix when it helps readability

$customerId = new Ulid("customer");
echo $customerId;

Example output:

CUSTOMER_01KPKT4PFTKVQ9P1E72F

Prefixes are automatically converted to uppercase, which keeps the identifiers visually consistent throughout logs, URLs, and SQL output.

4. Store it as a string

Ulid implements Stringable, so it fits naturally into the places where we already expect an identifier string:

$db->insert("user/insert", [
	"id" => (string)$customerId,
	"email" => "dev@example.com",
]);

We can cast explicitly, or let PHP convert the object to a string when that is appropriate.

5. Read the timestamp back out

echo $customerId->getTimestampString(), PHP_EOL;
echo $customerId->getDateTime()->format("Y-m-d H:i:s"), PHP_EOL;

That gives us an easy bridge between the identifier and its creation time, without storing a second value just to reconstruct it later.

6. Rehydrate an existing string

If we already have a ULID string from a database or request parameter, we can rebuild the object:

$existing = "CUSTOMER_01KPKT4PFTKVQ9P1E72F";
$id = new Ulid(init: $existing);

echo $id->getPrefix();           // CUSTOMER
echo $id->getTimestampString();  // 01KPKT4PFT

This is useful when the rest of our application prefers to work with an object instead of passing raw strings around.

7. Know when to reach for the other classes

Most of the time, Ulid is all we need.

  • Use Ulid to create and inspect whole identifiers.
  • Use Extractor when we already have an ID string and only want one section from it.
  • Use Base32 when we want direct access to the library’s encoding rules.

Once the basic flow is in place, continue with Prefixes and typed identifiers to decide when prefixed IDs improve the design of an application.