PHP.GT

Prefixes and typed identifiers

Prefixes let us add a small amount of human meaning to an identifier without giving up the sortable ULID structure.

For example, these are all valid outputs from the library:

USER_01KPKT4PFTKVQ9P1E72F
ORDER_01KPKT4PFTJH2WQ7M3CB
PET_01KPKT4PFT3EAJY4T1Q9

That can make logs, dashboards, and support tooling much easier to read at a glance.

Creating a prefixed ULID

use GT\Ulid\Ulid;

$invoiceId = new Ulid("invoice");
echo $invoiceId;

Output:

INVOICE_01KPKT4PFTKVQ9P1E72F

The prefix is always returned in uppercase, regardless of the original input.

Reading the prefix back

echo $invoiceId->getPrefix();

Output:

INVOICE

If no prefix was provided, getPrefix() returns null.

When prefixes are useful

Prefixes work well when the same system handles several categories of entity and we want the ID itself to give us a clue about what it belongs to.

Common examples:

  • USER_...
  • ORDER_...
  • INVOICE_...
  • SESSION_...

This can be especially helpful when identifiers move through external systems such as log aggregators, message queues, or support emails where surrounding context may be limited.

When not to use them

A prefix is not a substitute for proper typing in PHP, nor is it a substitute for relational integrity in a database.

If the identifier never leaves a tightly scoped part of the system, or if the prefix would simply duplicate obvious context, plain unprefixed ULIDs are often the cleaner choice.

One style decision to make early

It helps to settle on one prefix vocabulary across the application:

  • singular or plural nouns
  • domain terms or table names
  • short codes or whole words

The library will uppercase whatever we provide, but it will not enforce naming conventions beyond that.


Now that we can identify what an ID belongs to, the next step is to inspect when it was created in Reading timestamp information.