Value Object IDs in Doctrine, the Short Way: Symfony's AbstractUidType

πŸ‡¬πŸ‡§

​Introduction

A year ago I wrote Using Value Objects as Doctrine Entity IDs: A Deep Dive. The "why" of that article still holds: a PostId cannot be passed where a UserId is expected, and method signatures read like the domain.

The "how" aged less well. It asked for a hand-written Doctrine type of about fifty lines per ID, plus a UuidTrait to share between value objects. With twenty entities, that is a lot of code to maintain.

Symfony already ships that code. The Doctrine Bridge has an AbstractUidType, the class behind the built-in uuid and ulid types, and you can extend it for your own IDs. Here is the setup, what you get for free, and the four traps I ran into.

​The Trade-Off, Up Front

AbstractUidType only works with classes that extend Symfony\Component\Uid\AbstractUid. Its convertToPHPValue() method declares ?AbstractUid as return type, so a value object that wraps a UUID by composition triggers a TypeError.

Your ID has to inherit from a Symfony class. If your domain layer must stay free of any vendor inheritance, stop here and keep the approach from the first article. If you can live with it, read on: the rest is short.

​The Value Object

namespace App\Blog\Domain;

use Symfony\Component\Uid\UuidV7;

final class PostId extends UuidV7
{
}

That is the whole class. No trait, no private constructor, no validation code.

$id = new PostId();                    // generates a UUID v7
$id = PostId::fromString($request);    // accepts RFC 4122, base 58 and base 32
$id->toRfc4122();                      // "019ac0a5-3d4e-7c1a-9f3b-2a1b3c4d5e6f"
$id->getDateTime();                    // the timestamp embedded in a UUID v7

Validation comes with the parent class. PostId::fromString() throws an InvalidArgumentException with the message Invalid UUIDv7. for a malformed string, and also for a valid UUID of another version.

The class is still yours, so it can still implement your domain interfaces (ContentId, PublishableId, and so on) exactly as before.

​The Doctrine Type

namespace App\Blog\Infrastructure\Doctrine;

use App\Blog\Domain\PostId;
use Symfony\Bridge\Doctrine\Types\AbstractUidType;

final class PostIdType extends AbstractUidType
{
    public const string NAME = 'post_id';

    public function getName(): string
    {
        return self::NAME;
    }

    protected function getUidClass(): string
    {
        return PostId::class;
    }
}

Two methods: a name, and the class to instantiate. The SQL declaration, both conversions and the error handling live in the bridge.

Register it:

# config/packages/doctrine.yaml
doctrine:
    dbal:
        types:
            post_id: App\Blog\Infrastructure\Doctrine\PostIdType

And map it:

#[ORM\Entity]
class Post
{
    #[ORM\Id]
    #[ORM\Column(type: PostIdType::NAME)]
    private PostId $id;

    public function __construct()
    {
        $this->id = new PostId();
    }
}

​What You Get for Free

​Compact storage

The type from my first article relied on getGuidTypeDeclarationSQL(), which gives a CHAR(36) column on MySQL. AbstractUidType picks the best column per platform:

Platform Column Stored value
PostgreSQL UUID RFC 4122 string
MySQL, MariaDB BINARY(16) 16 bytes
SQLite BLOB 16 bytes

​Serialization

The first article listed serialization as a disadvantage: a toString() call at every layer boundary, and a custom normalizer per ID. Both are gone.

AbstractUid implements JsonSerializable and Stringable, so json_encode(), log contexts and cache keys work without conversion. The Symfony Serializer has a UidNormalizer that handles any AbstractUid subclass in both directions: it denormalizes a string into a PostId, not into a generic Uuid.

​Controller arguments

The built-in UidValueResolver also accepts subclasses:

#[Route('/posts/{id}')]
public function show(PostId $id): Response
{
    // ...
}

An invalid UUID in the URL gives a 404 before your code runs.

​Four Traps

​1. PostId::v7() does not return a PostId

The static factories of Uuid are final and return the Symfony classes. PostId::v7() compiles, autocompletes, and gives you a plain UuidV7. Use new PostId().

​2. equals() ignores the class

AbstractUid::equals() checks that the other value is an AbstractUid, then compares the strings. A PostId and a UserId holding the same UUID are equal. Override it if that matters to you:

final class PostId extends UuidV7
{
    #[\Override]
    public function equals(mixed $other): bool
    {
        return $other instanceof self && parent::equals($other);
    }
}

​3. The type accepts any UID

convertToDatabaseValue() takes any AbstractUid, so nothing stops a UserId from being bound to a post_id parameter in a query. Typed properties protect your entities. Typed repository signatures have to protect your queries.

Warning

Pass the type when you bind an ID in a query: ->setParameter('id', $postId, PostIdType::NAME). Without it, Doctrine casts the object to its RFC 4122 string, which never matches a BINARY(16) column.

​4. A wider public API

The constructor is public, and your ID exposes everything AbstractUid does: toBase58(), toBase32(), toHex(), jsonSerialize(). That is more surface than the three methods of the old UuidTrait. I find it acceptable for an identifier; you may not.

​Migrating from a Hand-Written Type

  1. Make each ID class extend UuidV7 (or Uuid if you store several versions) and delete the trait.
  2. Make each type extend AbstractUidType and keep only getName() and getUidClass().
  3. Replace PostId::generate() with new PostId().
  4. Run doctrine:schema:validate.

On PostgreSQL the column was already a native UUID, so step 4 reports nothing. On MySQL and MariaDB the column goes from CHAR(36) to BINARY(16): that one needs a real data migration, not just an ALTER TABLE.

​Conclusion

The pattern from the first article costs much less than I said it did. With AbstractUidType, one ID is an empty class and a twelve-line type, and the Serializer and the controller resolver already know what to do with it.

The price is one extends in your domain. Whether that is cheap depends on how strict your architecture is, and you only have to decide once for all your IDs.

​Further Reading