Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 62 ยท Databases with Doctrine

Doctrine ORM Setup

Set up Doctrine in Symfony: install the ORM pack, write DATABASE_URL for SQLite or MySQL, create the database, meet the EntityManager and generate entities.

Almost every real application stores data, and in Symfony the standard way to do it is Doctrine. Doctrine is two layers. The lower one, DBAL, is a thin wrapper around PDO that gives you connections, a query builder and portable types. The upper one, the ORM, maps your PHP objects (called entities) to database rows, so you can work with $product->getName() instead of writing SQL for every read and write.

This lesson gets Doctrine running: installing it, pointing it at a database with DATABASE_URL, creating the database, and meeting the object that does the work, the EntityManager. The real commands are read-only on this site because Symfony cannot run here, but two runnable stand-ins show how a connection string is understood and how an entity manager defers writes.

Installing Doctrine

Doctrine arrives as a Symfony pack, and the Maker bundle (a code generator) is a development dependency:

Terminal
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle

Thanks to Flex recipes (see Flex, Recipes and Bundles), this creates config/packages/doctrine.yaml, adds a DATABASE_URL line to .env, registers the bundles and creates the src/Entity/ and src/Repository/ folders. If you need a quick look at what a pack contains, composer show symfony/orm-pack lists the real packages: the Doctrine bundle, the ORM, DBAL and migrations.

DATABASE_URL

Doctrine is told where the database lives through one environment variable, a DSN (data source name) in URL form:

DOTENV
# SQLite: a file, no server needed (great for learning and tests)
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"

# MySQL / MariaDB
DATABASE_URL="mysql://app_user:[email protected]:3306/app_db?serverVersion=8.4&charset=utf8mb4"

# PostgreSQL
DATABASE_URL="postgresql://app_user:[email protected]:5432/app_db?serverVersion=16&charset=utf8"

The scheme (sqlite, mysql, postgresql) chooses the driver, the rest is user, password, host, port and database name, and query parameters carry options. Two things deserve attention:

  • serverVersion tells Doctrine which SQL dialect features it may use without connecting. Keep it equal to the real server version, or you can get wrong migration SQL.
  • Special characters in the password (@, :, /, #, %) must be URL-encoded, otherwise the URL parses into the wrong pieces. Alternatively, define DATABASE_URL in .env.local with the password encoded, or build the URL from separate variables.

Never commit real credentials. Keep safe defaults in .env and your private values in .env.local, or use the secrets vault covered in Environment Variables and Secrets.

The next stand-in parses DSNs the way a driver would, including a password that must be decoded. parse_url and urldecode are plain PHP; the interpretation is what Doctrine's DBAL does for you.

PHP Reading a DATABASE_URL (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 doctrine.yaml file

The recipe's config/packages/doctrine.yaml is short. A simplified version shows the parts to know:

YAML
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
    orm:
        auto_mapping: true
        mappings:
            App:
                type: attribute
                is_bundle: false
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

dbal.url hands the DSN to DBAL (resolve expands %kernel.project_dir% inside it). Under orm.mappings, you declare that classes in src/Entity with the App\Entity namespace are entities described by attributes, which is the modern choice (older projects use annotations, XML or YAML). The recipe also tunes things for dev and prod: in production, proxy classes and query caches are generated ahead of time and kept in a cache pool. To see the merged result at any time, run php bin/console debug:config doctrine.

Creating the database

With the URL in place:

Terminal
php bin/console doctrine:database:create

For SQLite this creates the file, for MySQL it runs CREATE DATABASE. It is a development helper; in production the database is provisioned by your infrastructure. Related commands: doctrine:database:drop --force, and doctrine:schema:validate to check that the mapping and the database agree (you will use it in Migrations).

SQLite versus MySQL. SQLite needs no server, is a single file and is perfect for tutorials, prototypes and fast tests. It has weaker types and limited ALTER TABLE. MySQL or PostgreSQL are the right choice for production: real concurrency, users and permissions, richer types. Because Doctrine hides dialects behind DBAL, you can develop with one and deploy with another, but test against the production engine before you ship, since subtle differences (case sensitivity, JSON functions, locking) exist. This tutorial's runnable stand-ins use SQLite because it is the only database available in the browser runner.

The EntityManager

The object you will use constantly is Doctrine\ORM\EntityManagerInterface, autowired into controllers and services:

PHP
<?php

namespace App\Controller;

use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class ProductController extends AbstractController
{
    #[Route('/product/new', name: 'product_new')]
    public function new(EntityManagerInterface $entityManager): Response
    {
        $product = new Product();
        $product->setName('Keyboard');
        $product->setPrice(4900);

        $entityManager->persist($product); // "manage this object"
        $entityManager->flush();           // run the INSERT now

        return new Response('Saved product '.$product->getId());
    }

    #[Route('/product/{id}', name: 'product_show')]
    public function show(EntityManagerInterface $entityManager, int $id): Response
    {
        $product = $entityManager->find(Product::class, $id);
        if (!$product) {
            throw $this->createNotFoundException('No product for id '.$id);
        }

        return new Response($product->getName());
    }
}

The key concept is the unit of work. persist() does not touch the database: it tells the manager to track the object. Changes to tracked objects are noticed automatically. flush() then compares the current state with the remembered state and runs all necessary INSERT, UPDATE and DELETE statements, together inside one transaction. This is why you typically call flush() once at the end of a piece of work.

flowchart LR
    C["Controller or service"] -->|"persist(obj), remove(obj)"| UOW["Unit of work<br/>(tracks changes)"]
    UOW -->|"flush()"| T["One transaction<br/>INSERT / UPDATE / DELETE"]
    T --> DB["Database"]
    C -->|"find(Class, id)"| DB

Persisting only queues the change; flush() writes everything in one transaction.

The second stand-in makes this visible with a few lines of PDO. Watch the query log: nothing is written during persist, and all inserts happen together on flush.

PHP persist() and flush() with a mini entity manager (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.

Generating an entity

Writing the first entity by hand is educational, but the Maker bundle is faster and avoids typos:

Terminal
php bin/console make:entity Product

It asks for field names and types interactively, then creates src/Entity/Product.php with attributes and getters/setters, plus src/Repository/ProductRepository.php. Running the command again on an existing entity adds fields. What those attributes mean, which column types exist and how to model ids and enums is the topic of Entities and Mapping. After you change an entity, you update the database with migrations rather than recreating it, which is the topic of the lesson after that.

Common setup problems

  • "An exception occurred in the driver: could not find driver." The PHP extension for your database (pdo_mysql, pdo_sqlite, pdo_pgsql) is not enabled.
  • Wrong password parse. Unencoded special characters in the DSN; encode them with urlencode.
  • Different database in dev and test. Symfony appends _test to the database name in the test environment through the recipe's config; check config/packages/doctrine.yaml for when@test.
  • serverVersion missing or wrong, which can produce SQL the real server rejects.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the two layers of Doctrine?

    DBAL wraps PDO and gives a portable database layer. The ORM sits on top and maps entity objects to tables.
  2. 2. What does persist($product) do?

    persist() only schedules the object. flush() performs all pending INSERT, UPDATE and DELETE statements in a single transaction.
  3. 3. Why does serverVersion belong in DATABASE_URL?

    Doctrine generates SQL for a specific server version. A wrong version can lead to unsupported statements.
  4. 4. Your database password contains @ and /. What should you do in the DSN?

    Special URL characters break parsing unless encoded. Encode the password or assemble the URL from separate variables.

Summary

  • Doctrine = DBAL (portable database access) + ORM (entities mapped to tables); install it with symfony/orm-pack, and the Maker bundle for code generation.
  • DATABASE_URL selects driver, credentials and options; set serverVersion and URL-encode special characters.
  • SQLite is ideal for learning and tests, MySQL or PostgreSQL for production; test against the production engine.
  • The EntityManager implements a unit of work: persist() queues, flush() writes everything in one transaction, find() reads by id.
  • make:entity generates entity and repository classes; you update the schema with migrations.

Next up: Entities and Mapping.