Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 62 ยท Databases with Doctrine

Entities and Mapping

Map PHP classes to tables with Doctrine attributes: column types, identifiers, enums, embeddables and lifecycle callbacks, plus a runnable data-mapper stand-in.

An entity is an ordinary PHP class that Doctrine knows how to store and load. There is no base class to extend and no magic: you add mapping metadata (nowadays PHP attributes) that says "this class is the product table, this property is a VARCHAR(255) column, that one is the primary key". Doctrine reads the metadata, generates SQL, and turns rows back into objects. Because the metadata lives next to the code, an entity is the single place where you describe a piece of your domain and how it is persisted.

This lesson covers the mapping vocabulary you will use every day: the entity and table attributes, column types and options, identifiers, PHP enums, embeddable value objects and lifecycle callbacks. Real Doctrine code is read-only here. To understand what the ORM actually does with those attributes, you will also build a small data mapper in plain PHP on SQLite that reads attributes through reflection, creates the table and hydrates objects.

A first entity

This is roughly what make:entity Product generates, trimmed:

PHP
<?php

namespace App\Entity;

use App\Repository\ProductRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ProductRepository::class)]
#[ORM\Table(name: 'product')]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 120)]
    private string $name;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    private ?string $description = null;

    #[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 2)]
    private string $price = '0.00';

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): static
    {
        $this->name = $name;
        return $this;
    }
}

#[ORM\Entity] marks the class (and names its repository, covered in Repositories and Queries). #[ORM\Table] is optional: without it, the table name is derived from the class name by the naming strategy. Doctrine reads the properties, not the getters, so you are free to design the public methods of the object however your domain needs. Private properties are fine: Doctrine uses reflection to fill them.

flowchart LR
    CLS["PHP class<br/>with #[ORM] attributes"] --> META["Class metadata"]
    META --> SQL["Generated SQL<br/>(INSERT, SELECT, CREATE TABLE)"]
    META --> HYD["Hydration:<br/>row to object"]
    SQL --> DB[("Database")]
    HYD --> OBJ["Entity objects"]

Attributes become metadata; the metadata drives both SQL generation and turning rows back into objects.

Columns and types

If you omit type, Doctrine infers it from the PHP type of the property: int becomes integer, string becomes string (VARCHAR, default length 255), bool becomes boolean, ?string adds nullable. Be explicit when you need something else, using the constants in Doctrine\DBAL\Types\Types:

Types constant PHP value Typical use
STRING (default for string) string names, titles, up to length
TEXT string long text
INTEGER, SMALLINT, BIGINT int (bigint is a string) counters, ids
DECIMAL string money, exact numbers
FLOAT float measurements
BOOLEAN bool flags
DATETIME_IMMUTABLE, DATE_IMMUTABLE DateTimeImmutable timestamps
JSON array flexible structured data

Useful column options: length, nullable, unique, precision and scale, name (the column name), options: ['default' => 0]. Two traps are worth remembering. A DECIMAL value arrives as a string ('19.90') because PHP floats cannot hold exact decimals; many teams store money as an integer count of cents instead. And always prefer the *_IMMUTABLE date types, so that modifying a date creates a new object rather than silently changing the one Doctrine is tracking.

Indexes are declared on the table: #[ORM\Table(name: 'product')] plus #[ORM\Index(columns: ['name'])] or #[ORM\UniqueConstraint(columns: ['sku'])]. Index design matters for speed and is covered in Doctrine Performance and Pitfalls.

Identifiers

Every entity needs an identifier. The common choices:

  • Auto-increment integer (#[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] on ?int $id). Simple and compact. The id is null until the first flush(), which is why the property is nullable.
  • UUID or ULID, with Symfony's Uid component. The id can be created in the constructor, before any database call, which is handy for distributed systems and for not leaking record counts through URLs. The mapping uses UuidType::NAME or UlidType::NAME plus a custom id generator; the recipe make:entity can generate it for you.
  • Natural keys (an ISBN or a country code), assigned manually, when the value is truly unique and immutable.

Auto-increment ids are fine for most applications; just do not treat them as secrets.

Enums, embeddables and JSON

PHP backed enums map directly to a column with enumType:

PHP
enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
}

#[ORM\Column(enumType: Status::class)]
private Status $status = Status::Draft;

Doctrine stores the backing value ('draft') and returns the enum case on load, so invalid states cannot be represented in your objects. Prefer this over free-form strings.

An embeddable is a value object stored inside the owner's table, with no id of its own:

PHP
#[ORM\Embeddable]
class Money
{
    #[ORM\Column]
    private int $amount;

    #[ORM\Column(length: 3)]
    private string $currency;

    public function __construct(int $amount, string $currency)
    {
        $this->amount = $amount;
        $this->currency = $currency;
    }
}

// in Product:
#[ORM\Embedded(class: Money::class, columnPrefix: 'price_')]
private Money $price;

This produces price_amount and price_currency columns on product, while your code works with a rich Money object. Use embeddables for concepts like money, address or date range that belong to one owner and are compared by value. Use JSON columns for data whose shape really varies, and avoid them for anything you filter or join on regularly.

Lifecycle callbacks

Doctrine fires events around persisting. For small, self-contained logic on the entity itself, mark methods with lifecycle attributes (and the class with #[ORM\HasLifecycleCallbacks]):

PHP
#[ORM\Entity]
#[ORM\HasLifecycleCallbacks]
class Article
{
    #[ORM\Column(length: 160, unique: true)]
    private ?string $slug = null;

    #[ORM\PrePersist]
    public function prepareSlug(): void
    {
        $this->slug ??= strtolower(trim(preg_replace('/[^A-Za-z0-9]+/', '-', $this->title), '-'));
    }
}

The available hooks include PrePersist, PostPersist, PreUpdate, PostUpdate, PreRemove, PostRemove and PostLoad. A callback cannot receive services, because the entity is not created by the container. If the logic needs a mailer, a slugger service or a clock, use an entity listener instead (a service marked with #[AsEntityListener]). Keep callbacks tiny and fast, and never call flush() from inside one.

Building a mapper to see how it works

The next stand-in shows what the ORM does with attributes: it reads them using reflection and turns a plain class into a CREATE TABLE statement. Changing the class changes the SQL, which is the idea behind migrations too.

PHP From attributes to CREATE TABLE (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second stand-in is a complete little data mapper: it creates the table, runs a PrePersist callback, stores an enum, flattens an embedded value object into prefixed columns and rebuilds the objects when loading, all on in-memory SQLite.

PHP A tiny data mapper: persist, embed, hydrate (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Habits for healthy entities

  • Give entities behaviour, not just getters and setters: a method such as publish() that checks the rules beats a public setStatus().
  • Validate with constraints (see Validation) and protect with database constraints (nullable, unique). Both matter.
  • Keep entities free of services and of request or session data.
  • Prefer enums and value objects to loose strings and arrays.
  • After you change mapping, do not edit the database by hand: generate a migration, which is the next lesson. php bin/console doctrine:schema:validate tells you whether mapping and database agree, and doctrine:mapping:info lists the entities Doctrine found.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does Doctrine read the getters of an entity to know what to save?

    Mapping lives on properties. You can design the public API freely, and Doctrine fills private properties via reflection.
  2. 2. Why is the id property typed ?int and set to null by default?

    With GeneratedValue, the database assigns the id during the INSERT, so a new object has no id yet.
  3. 3. In which PHP type does a Doctrine DECIMAL column arrive?

    Decimals are returned as strings to avoid floating-point rounding. Store cents in an integer or use a money library.
  4. 4. When should you use an entity listener instead of a lifecycle callback?

    Lifecycle callbacks run on the entity, which the container does not build, so they cannot receive services. Listeners are services and can.
  5. 5. What does enumType: Status::class on a column do?

    The backing value (for example 'draft') is saved, and Doctrine converts it back into the matching enum case on hydration.

Summary

  • An entity is a plain PHP class with mapping attributes: #[ORM\Entity], #[ORM\Table], #[ORM\Id], #[ORM\GeneratedValue] and #[ORM\Column].
  • Column types come from Doctrine\DBAL\Types\Types; remember that decimals and bigints are strings and prefer immutable date types.
  • Choose ids deliberately: auto-increment for simplicity, UUID or ULID when you need ids before saving.
  • Backed enums (enumType) and embeddables (#[ORM\Embedded]) keep your model expressive; JSON columns are for genuinely loose data.
  • Lifecycle callbacks suit tiny self-contained logic; use entity listeners when services are needed.

Next up: Migrations.