Skip to content

Auto-discover entities based on attribute #2124

@Nayte91

Description

@Nayte91

Feature Request

What

Automatically detect and register entity mappings by scanning for classes with the #[Entity] attribute when no explicit mappings are configured, eliminating the need for repetitive manual configuration.

Why

Currently, every entity mapping must be explicitly declared in doctrine.yaml:

doctrine:
    orm:
        mappings:
            User:
                dir: '%kernel.project_dir%/src/User/Entity'
                prefix: 'App\User\Entity'
            Event:
                dir: '%kernel.project_dir%/src/Event/Entity'
                prefix: 'App\Event\Entity'
            # ... repeated for each domain

This becomes particularly tedious in DDD-structured projects with multiple bounded contexts, where entities are distributed across many domain folders. Going for a auto discover offers multiple benefits:

  • Drastically reduces boilerplate configuration
  • Aligns with "convention over configuration" philosophy
  • Complements Symfony 7.3's auto-exclusion of entities from service container (PR #59987)
  • Complements Symfony 7.4's controllers auto-registering (PR #61492)
  • Provides DX similar to other ORMs (Laravel Eloquent, TypeORM, Hibernate)
  • Fully backwards compatible with below option.

How

The implementation could have zero configuration. For BC reason, it would add a new configuration option:

doctrine:
    orm:
        auto_discover_entities: true //true by default on next major version

I suppose that the approach would be:

  1. Detection by somehow reading composer PSR4 config,
  2. Discovery at compile time by scanning recursively folders,
  3. Automatically register discovered mappings with each namespace,
  4. Caching results in compiled container to avoid runtime overhead (Only rescanned when container is rebuilt)

I guess main implementation would be in DoctrineExtension::load() method, similar to how the legacy auto_mapping feature worked?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions