Package for Id and IdList value objects with Symfony

Package for Id and IdList value objects with Symfony
Photo by Maksym Kaharlytskyi / Unsplash

Just recently I wrote about how I handle ids and id lists as value objects in my projects. Shortly after, I realised that the version I'm using isn't the same in all the projects and decided to streamline them and move them into an open source id package for Symfony that is now available as a beta.

With it it's as simple as creating a new class extending from the base id:

<?php

declare(strict_types=1);

namespace App\ValueObject;

use DigitalCraftsman\Ids\ValueObject\Id;

/** @psalm-immutable */
final class UserId extends Id
{
}

The package also contains a normalizer with which you can automatically serialize and deserialize ids to strings and back. The normalizers are registered automatically through the Symfony framework bundle.

The usage of the ids as types got even easier. To use an id in your entities, you just need to register a new type for the id. Create a new class for the new id like the following:

<?php

declare(strict_types=1);

namespace App\Doctrine;

use App\ValueObject\UserId;
use DigitalCraftsman\Ids\Doctrine\IdType;

final class UserIdType extends IdType
{
    protected function getTypeName(): string
    {
        return 'user_id';
    }

    protected function getIdClass(): string
    {
        return UserId::class;
    }
}

Then register the new type in your config/packages/doctrine.yaml file:

doctrine:
  dbal:
    types:
      user_id: App\Doctrine\UserIdType

Additionally there are also value objects for id lists to handle multiple ids of one type. With it you're able to look through them, protect against duplicates and much more.

Always happy for new ideas through the Github repository.

It's also what I use in all the projects I'm using the CQRS bundle for Symfony.