bentools/doctrine-ulid

ULID (Universally Unique Lexicographically Sortable Identifier) support for Doctrine IDs

1.1 2019-05-27 09:55 UTC

README

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Doctrine ULID generator

This small library adds support for ULID in Doctrine.

ULIDs act like UUIDs that can be lexicographically sorted. ULIDs also have a smaller footprint (26 ANSI characters vs. 36 for UUIDs);

This package integrates robinvdvleuten/ulid as a CustomIdGenerator.

Installation

composer require bentools/doctrine-ulid

Usage

Use the provided class as a custom ID generator:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Foo
{

    /**
     * @var string
     *
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class="\BenTools\ULIDGenerator")
     * @ORM\Column(type="string", length=26)
     */
    private $id;
    
    // ...
    
}

Or use the following trait:

use Doctrine\ORM\Mapping as ORM;
use BenTools\GeneratedULIDTrait;

/**
 * @ORM\Entity()
 */
class Foo
{

    use GeneratedULIDTrait;
    
    // ... 
    
}

If you want to set ULIDs by yourself (this way, they can be generated on the client side), use the EditableULIDTrait which will expose a setId() method:

use Doctrine\ORM\Mapping as ORM;
use BenTools\EditableULIDTrait;

/**
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 */
class Foo
{

    use EditableULIDTrait;
    
    // ... 
    
}
  • If setId() is not called, an ULID will be automatically generated on persist.
  • Don't forget to add a @HasLifecycleCallbacks() annotation on top of your entity for this behavior to work properly.

Tests

./vendor/bin/phpunit

License

MIT.