tito10047/type-safe-id-bundle

Type safe UUID or Ulid bundle

dev-main 2025-09-22 16:26 UTC

This package is auto-updated.

Last update: 2025-09-22 16:37:24 UTC


README

Introduction

⚠️ WARNING: This is an experimental package and may not be suitable for production use. Use at your own risk.

When working with Symfony and Doctrine, using UUIDs as entity identifiers is a common approach. Traditionally, IDs are stored as simple integers or as raw Uuid objects. However, this can lead to type confusion, especially when working with Symfony Messenger or repository methods. A more robust and type-safe approach is to use dedicated ID classes.

This package override bin/console make:entity and add Type safe identifiers. This is implementation of this article

Its generates some like this

bin/console make:entity Foo --with-ulid

#[ORM\Entity(repositoryClass: FooRepository::class)]
class Foo
{
    #[ORM\Id]
    #[ORM\Column(type: FooIdType::class, unique: true)]
    private FooId $id;

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

    public function getId(): FooId
    {
        return $this->id;
    }
}
class FooRepository extends ServiceEntityRepository
{
    //...
    public function get(FooId $id): ?Foo    {
        return $this->find($id->toString());
    }
    //...
}

Usage

$foo = new Foo();
$poo = new Poo();
$this->em->persist($foo);
$this->em->persist($poo);
$this->em->flush();

$serializedFooId = serialize($foo->getId());
$serializedPooId = serialize($poo->getId());

//this work
$foo = $this->fooRepository->get(unserialize($serializedFooId));
//this throw Exception App\Repository\FooRepository::get(): Argument #1 ($id) must be of type App\EntityId\FooId, App\EntityId\PooId given
$foo = $this->fooRepository->get(unserialize($serializedPooId));

Installation

Make sure Composer is installed globally, as explained in the installation chapter of the Composer documentation.

Applications that use Symfony Flex

Open a command console, enter your project directory and execute:

$ composer require tito10047/type-safe-id-bundle

Applications that don't use Symfony Flex

Step 1: Download the Bundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

$ composer require tito10047/type-safe-id-bundle

Step 2: Enable the Bundle

Then, enable the bundle by adding it to the list of registered bundles in the config/bundles.php file of your project:

// config/bundles.php

return [
    // ...
    Tito10047\TypeSafeIdBundle\TypeSafeIdBundle::class => ['all' => true],
];