### Install DoctrineBundle via Composer Source: https://context7.com/doctrine/doctrinebundle/llms.txt Install the DoctrineBundle using Composer. Symfony Flex handles automatic enabling and configuration file generation. Verify configuration with `debug:config doctrine`. ```bash composer require doctrine/doctrine-bundle # Flex also scaffolds config/packages/doctrine.yaml automatically. # Verify with: php bin/console debug:config doctrine ``` -------------------------------- ### Autowire Entity Managers Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Example of how to autowire different entity managers by type-hinting service arguments with the EntityManagerInterface. ```diff - public function __construct(EntityManagerInterface $entityManager) + public function __construct(EntityManagerInterface $purchaseLogsEntityManager) { $this->entityManager = $purchaseLogsEntityManager; } ``` -------------------------------- ### Install DoctrineBundle using Composer Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/installation.rst Use this command to download the latest stable version of the DoctrineBundle. Requires Composer to be installed globally. ```bash $ composer require doctrine/doctrine-bundle ``` -------------------------------- ### Doctrine DBAL Configuration Options Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Comprehensive example showcasing various configuration keys for Doctrine DBAL, including connection details and driver-specific options. ```yaml doctrine: dbal: url: mysql://user:secret@localhost:1234/otherdatabase dbname: database host: localhost port: 1234 user: user password: secret dbname_suffix: _test driver: pdo_mysql driver_class: MyNamespace\MyDriverImpl options: foo: bar path: "%kernel.project_dir%/var/data.db" # SQLite specific memory: true # SQLite specific unix_socket: /tmp/mysql.sock persistent: true MultipleActiveResultSets: true # pdo_sqlsrv driver specific pooled: true # Oracle specific (SERVER=POOLED) protocol: TCPIP # IBM DB2 specific (PROTOCOL) server: my_database_server # SQL Anywhere specific (ServerName) service: true # Oracle specific (SERVICE_NAME instead of SID) servicename: MyOracleServiceName # Oracle specific (SERVICE_NAME) sessionMode: 2 # oci8 driver specific (session_mode) default_dbname: database # PostgreSQL specific (default_dbname) sslmode: require # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE) sslrootcert: postgresql-ca.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT) sslcert: postgresql-cert.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT) sslkey: postgresql-key.pem # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY) ``` -------------------------------- ### Default ORM Configuration Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Example of default ORM configuration settings, including auto-mapping and default entity manager. ```yaml doctrine: orm: auto_mapping: true # the standard distribution overrides this to be true in debug, false otherwise default_entity_manager: default metadata_cache_driver: ~ query_cache_driver: ~ result_cache_driver: ~ ``` -------------------------------- ### Get Help for a Specific Doctrine Command Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/doctrine-console.rst Use this command to get detailed help and usage information for a specific Doctrine command, such as doctrine:schema:update. ```console php bin/console doctrine:schema:update --help ``` -------------------------------- ### Decorate Driver Connection Logic Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/middlewares.rst Extend `AbstractDriverMiddleware` to decorate specific driver methods. This example prevents connections using the 'root' user. ```php */ class ProductRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Product::class); } /** @return Product[] */ public function findActiveByCategory(string $category, int $limit = 20): array { return $this->findBy( ['category' => $category, 'active' => true], ['createdAt' => 'DESC'], $limit, ); } public function findExpensiveProducts(float $minPrice): QueryBuilder { return $this->createQueryBuilder('p') ->where('p.price >= :minPrice') ->setParameter('minPrice', $minPrice) ->orderBy('p.price', 'DESC'); } } ``` -------------------------------- ### Doctrine Migrations Commands Source: https://context7.com/doctrine/doctrinebundle/llms.txt Manage database schema changes over time using Doctrine Migrations. Requires the 'doctrine/migrations' package to be installed. ```bash php bin/console doctrine:migrations:diff ``` ```bash php bin/console doctrine:migrations:migrate ``` -------------------------------- ### Entity with Second Level Cache Annotation Source: https://context7.com/doctrine/doctrinebundle/llms.txt Example of an entity class annotated for second-level caching. Specify usage and region for entities and collections. ```php getObject(); $this->logger->info('Entity created', [ 'class' => $entity::class, 'id' => $args->getObjectManager()->getUnitOfWork()->getEntityIdentifier($entity), ]); } public function postUpdate(PostUpdateEventArgs $args): void { $entity = $args->getObject(); $changeSet = $args->getObjectManager()->getUnitOfWork()->getEntityChangeSet($entity); $this->logger->info('Entity updated', ['class' => $entity::class, 'changes' => array_keys($changeSet)]); } } ``` -------------------------------- ### Resolve Target Entities in Entity Class Source: https://context7.com/doctrine/doctrinebundle/llms.txt Example of an entity class using an interface for a ManyToOne relationship, which will be resolved by the configuration. ```php findActiveByCategory($category); // $repo->find(42) — find by primary key // $repo->findOneBy(['sku' => 'ABC-123']) // $repo->count(['active' => true]) return $this->json($products); } } ``` -------------------------------- ### Built-in UUID ID Generator Source: https://context7.com/doctrine/doctrinebundle/llms.txt Example of using the built-in UUID generator for entity IDs. Requires the symfony/uid component. ```php id; } } ``` -------------------------------- ### Custom DBAL Money Type Source: https://context7.com/doctrine/doctrinebundle/llms.txt Example of creating a custom DBAL type for handling monetary values. This involves defining SQL declarations and conversion methods for database interaction. ```php ``` -------------------------------- ### Doctrine Mapping Information Commands Source: https://context7.com/doctrine/doctrinebundle/llms.txt Inspect your Doctrine entity mappings. Use 'info' to list all mapped entities and 'describe' for details on a specific entity. ```bash php bin/console doctrine:mapping:info ``` ```bash php bin/console doctrine:mapping:describe 'App\Entity\User' ``` -------------------------------- ### Enable DoctrineBundle in config/bundles.php Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/installation.rst Manually enable the DoctrineBundle by adding its class to the config/bundles.php file if you are not using Flex. ```php ['all' => true], // ... ]; ``` -------------------------------- ### Configure Listener with Event, Entity, and Method (XML) Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/entity-listeners.rst Configure entity listener registration using XML in the service definition, specifying the event, entity, and method. The 'entity_manager' and 'method' attributes are optional. ```xml ``` -------------------------------- ### Doctrine Console Commands Source: https://context7.com/doctrine/doctrinebundle/llms.txt Lists available Doctrine console commands for database management, including creation and dropping of databases. ```bash # List all available Doctrine commands php bin/console list doctrine ``` ```bash # --- Database management --- php bin/console doctrine:database:create # Create the configured database php bin/console doctrine:database:drop --force # Drop the database (--force required) ``` -------------------------------- ### Configure Multiple DBAL Connections Source: https://context7.com/doctrine/doctrinebundle/llms.txt Set up multiple named database connections in `config/packages/doctrine.yaml`. These connections can be injected into services by name using the `$Connection` convention. ```yaml # config/packages/doctrine.yaml doctrine: dbal: default_connection: default connections: default: url: '%env(resolve:DATABASE_URL)%' legacy: driver: pdo_pgsql host: legacy-db.example.com dbname: legacy user: '%env(LEGACY_DB_USER)%' password: '%env(LEGACY_DB_PASSWORD)%' ``` -------------------------------- ### Doctrine Query Command Source: https://context7.com/doctrine/doctrinebundle/llms.txt Execute DQL queries directly from the command line for testing or data retrieval. ```bash php bin/console doctrine:query:dql "SELECT u FROM App\Entity\User u WHERE u.active = true" ``` -------------------------------- ### Enable DoctrineBundle in app/AppKernel.php (older Symfony versions) Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/installation.rst For older Symfony versions without config/bundles.php, enable the DoctrineBundle by adding it to the AppKernel.php file. ```php ``` -------------------------------- ### Configure Listener with Event, Entity, and Method (YAML) Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/entity-listeners.rst Configure entity listener registration directly in the service definition, specifying the event, entity, and method. The 'entity_manager' and 'method' attributes are optional. ```yaml services: App\UserListener: tags: - name: doctrine.orm.entity_listener event: preUpdate entity: App\Entity\User # entity_manager attribute is optional entity_manager: custom # method attribute is optional method: validateEmail ``` -------------------------------- ### Configure Database Connection Option Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Adds a specific option to the database connection. This is useful for setting driver-specific parameters not covered by the main attributes. ```xml value ``` -------------------------------- ### Create Custom DBAL Middleware with #[AsMiddleware] Source: https://context7.com/doctrine/doctrinebundle/llms.txt Implement the Doctrine\DBAL\Driver\Middleware interface and use the #[AsMiddleware] attribute to register your custom middleware. This allows you to intercept and modify DBAL operations, such as logging slow queries. You can specify which connections the middleware applies to and its priority. ```php wrapped->prepare($sql); $elapsed = (hrtime(true) - $start) / 1e6; if ($elapsed > 100) { // log slow query preparations > 100ms error_log(sprintf('[SLOW PREPARE] %s — %.2fms', $sql, $elapsed)); } return $statement; } // Delegate all other methods to $this->wrapped ... public function exec(string $sql): int { return $this->wrapped->exec($sql); } public function query(string $sql): Doctrine\DBAL\Driver\Result { return $this->wrapped->query($sql); } public function quote(string $value): string { return $this->wrapped->quote($value); } public function beginTransaction(): void { $this->wrapped->beginTransaction(); } public function commit(): void { $this->wrapped->commit(); } public function rollBack(): void { $this->wrapped->rollBack(); } public function lastInsertId(): int|string { return $this->wrapped->lastInsertId(); } public function getNativeConnection(): mixed { return $this->wrapped->getNativeConnection(); } } ``` -------------------------------- ### Configure Entity Listener with #[AsEntityListener] Source: https://context7.com/doctrine/doctrinebundle/llms.txt Use the #[AsEntityListener] attribute on your listener service to register it for specific entity lifecycle events. This approach is useful when you don't want to modify the entity class directly or need more granular control over events and lazy loading. ```php plainPassword)) { $user->passwordHash = $this->hasher->hashPassword($user, $user->plainPassword); } } public function preUpdate(User $user, PreUpdateEventArgs $args): void { if ($args->hasChangedField('plainPassword')) { $user->passwordHash = $this->hasher->hashPassword($user, $user->plainPassword); } } } ``` -------------------------------- ### Set Middleware Execution Priority Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/middlewares.rst Use the `AsMiddleware` attribute with the `priority` option to control the execution order of middlewares. Higher values execute earlier. ```php services(); // listeners are applied by default to all Doctrine connections $services->set(SearchIndexer::class) ->tag('doctrine.event_listener', [ // this is the only required option for the lifecycle listener tag 'event' => 'postPersist', // listeners can define their priority in case multiple subscribers or listeners are associated // to the same event (default priority = 0; higher numbers = listener is run earlier) 'priority' => 500, // you can also restrict listeners to a specific Doctrine connection 'connection' => 'default', ]) ; }; ``` -------------------------------- ### Configure Multiple DBAL Connections in YAML Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Define multiple database connections by nesting them under the 'connections' key in your YAML configuration. Ensure each connection has a unique name. The 'default_connection' parameter specifies which connection is used by default. ```yaml doctrine: dbal: default_connection: default connections: default: dbname: Symfony2 user: root password: null host: localhost customer: dbname: customer user: root password: null host: localhost ``` -------------------------------- ### Doctrine Caching Drivers Configuration Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Overview of Doctrine ORM caching configurations, showing how to use Symfony Cache pools or custom services. ```yaml doctrine: orm: auto_mapping: true # With no cache set, this defaults to a sane 'pool' configuration metadata_cache_driver: ~ # the 'pool' type requires to define the 'pool' option and configure a cache pool using the FrameworkBundle result_cache_driver: type: pool pool: doctrine.result_cache_pool # the 'service' type requires to define the 'id' option too query_cache_driver: type: service id: App\ORM\MyCacheService framework: cache: pools: doctrine.result_cache_pool: adapter: cache.app ``` -------------------------------- ### Register Event Listener with YAML Configuration Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/event-listeners.rst Configure services in YAML to act as event listeners by tagging them with 'doctrine.event_listener'. The 'event' option is required, while 'priority' and 'connection' are optional. ```yaml services: # ... App\EventListener\SearchIndexer: tags: - name: 'doctrine.event_listener' # this is the only required option for the lifecycle listener tag event: 'postPersist' # listeners can define their priority in case multiple subscribers or listeners are associated # to the same event (default priority = 0; higher numbers = listener is run earlier) priority: 500 # you can also restrict listeners to a specific Doctrine connection connection: 'default' ``` -------------------------------- ### Configure Doctrine DBAL Connections Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Defines database connection parameters for Doctrine DBAL. Includes settings for database name, host, user, password, charset, and RDBMS-specific options. Use this to set up your primary database connection. ```yaml doctrine: dbal: default_connection: default # A collection of custom types types: # example some_custom_type: class: Acme\HelloBundle\MyCustomType connections: # A collection of different named connections (e.g. default, conn2, etc) default: dbname: ~ host: localhost port: ~ user: root password: ~ # RDBMS specific; Refer to the manual of your RDBMS for more information charset: ~ # Adds the given suffix to the configured database name, this option has no effects for the SQLite platform dbname_suffix: ~ # SQLite specific path: ~ # SQLite specific memory: ~ # MySQL specific. The unix socket to use for MySQL unix_socket: ~ # IBM DB2 specific. True to use as persistent connection for the ibm_db2 driver persistent: ~ # IBM DB2 specific. The protocol to use for the ibm_db2 driver (default to TCPIP if omitted) protocol: ~ # Oracle specific. True to use SERVICE_NAME as connection parameter instead of SID for Oracle service: ~ # Oracle specific. Overrules dbname parameter if given and used as SERVICE_NAME or SID connection # parameter for Oracle depending on the service parameter. servicename: ~ # oci8 driver specific. The session mode to use for the oci8 driver. sessionMode: ~ # SQL Anywhere specific (ServerName). The name of a running database server to connect to for SQL Anywhere. server: ~ # PostgreSQL specific (default_dbname). # Override the default database (postgres) to connect to. default_dbname: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLMODE). # Determines whether or with what priority a SSL TCP/IP connection will be negotiated with the server for PostgreSQL. sslmode: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLROOTCERT). # The name of a file containing SSL certificate authority (CA) certificate(s). # If the file exists, the server's certificate will be verified to be signed by one of these authorities. sslrootcert: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCERT). # The name of a file containing the client SSL certificate. sslcert: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLKEY). # The name of a file containing the private key for the client SSL certificate. sslkey: ~ # PostgreSQL specific (LIBPQ-CONNECT-SSLCRL). # The name of a file containing the SSL certificate revocation list (CRL). sslcrl: ~ # Oracle specific (SERVER=POOLED). True to use a pooled server with the oci8/pdo_oracle driver pooled: ~ # pdo_sqlsrv driver specific. Configuring MultipleActiveResultSets for the pdo_sqlsrv driver MultipleActiveResultSets: ~ driver: pdo_mysql platform_service: ~ auto_commit: ~ # If set to "/^sf2_/" all tables, and any named objects such as sequences # not prefixed with "sf2_" will be ignored by the schema tool. # This is for custom tables which should not be altered automatically. schema_filter: ~ # When true, queries are logged to a "doctrine" monolog channel logging: "%kernel.debug%" ``` -------------------------------- ### Inject Multiple Entity Managers in a Service Source: https://context7.com/doctrine/doctrinebundle/llms.txt Demonstrates how to inject multiple Doctrine Entity Managers into a service using constructor property promotion. The entity managers are injected by their configured names (e.g., $defaultEntityManager, $customerEntityManager). ```php EntityManager private readonly EntityManagerInterface $defaultEntityManager, private readonly EntityManagerInterface $customerEntityManager, ) {} public function syncCustomer(int $id): void { $order = $this->defaultEntityManager->find(\App\Entity\Core\Order::class, $id); $customer = $this->customerEntityManager->find(\App\Entity\Customer\Profile::class, $order->getCustomerId()); // ... } } ``` -------------------------------- ### Configure Default Database Connection Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Defines the primary database connection for the application. Ensure all required parameters like host, port, user, and password are set correctly. Logging and profiling can be enabled based on the kernel debug mode. ```xml value string utf8mb4 utf8_unicode_ci InnoDB ``` -------------------------------- ### Register Event Listener with PHP Attributes Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/event-listeners.rst Use the AsDoctrineListener attribute to tag a service as an event listener. Specify the event name and optionally priority and connection. ```php namespace App\EventListener; use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener; use Doctrine\ORM\Event\LifecycleEventArgs; #[AsDoctrineListener('postPersist'/*, 500, 'default'*/)] class SearchIndexer { public function postPersist(LifecycleEventArgs $event): void { // ... } } ``` -------------------------------- ### Configure Lazy Entity Listener (YAML) Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/entity-listeners.rst Use the 'lazy: true' attribute in the tag to ensure the listener service is only instantiated when actually used. ```yaml services: App\UserListener: tags: - { name: doctrine.orm.entity_listener, lazy: true } ``` -------------------------------- ### Configure ORM Mapping Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Defines ORM mapping information. Specify bundle name, directory, and type. ```xml ``` -------------------------------- ### Configure Lazy Entity Listener (XML) Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/entity-listeners.rst Use the 'lazy: true' attribute in the tag to ensure the listener service is only instantiated when actually used. ```xml ``` -------------------------------- ### Configure Doctrine DBAL Connection in XML Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Defines a DBAL connection with various parameters like name, URL, host, port, user, password, driver, and specific driver options. This is useful for setting up database connections in Symfony applications. ```xml bar string utf8mb4 utf8_unicode_ci InnoDB Acme\HelloBundle\MyCustomType ``` -------------------------------- ### Doctrine Schema Management Commands Source: https://context7.com/doctrine/doctrinebundle/llms.txt Use these commands to manage your database schema based on entity mappings. Ensure you understand the implications before running update or drop commands. ```bash php bin/console doctrine:schema:create ``` ```bash php bin/console doctrine:schema:update --dump-sql ``` ```bash php bin/console doctrine:schema:update --force ``` ```bash php bin/console doctrine:schema:drop --force ``` ```bash php bin/console doctrine:schema:validate ``` -------------------------------- ### Register Entity Listener with #[ORM\EntityListeners] Source: https://context7.com/doctrine/doctrinebundle/llms.txt Use the #[ORM\EntityListeners] attribute on your entity class to specify which listener services should handle its lifecycle events. This is a straightforward way to associate listeners with specific entities. ```php directory mapping mappings: App: is_bundle: false type: attribute dir: '%kernel.project_dir%/src/Entity' prefix: 'App\Entity' alias: App # Cache pools (use Symfony Cache) metadata_cache_driver: type: pool pool: doctrine.system_cache_pool query_cache_driver: type: pool pool: doctrine.system_cache_pool result_cache_driver: type: pool pool: doctrine.result_cache_pool # Custom DQL functions dql: string_functions: GROUP_CONCAT: App\DQL\GroupConcatFunction datetime_functions: DATE_FORMAT: App\DQL\DateFormatFunction # SQL Filters filters: soft_delete: class: App\Filter\SoftDeleteFilter enabled: true framework: cache: pools: doctrine.system_cache_pool: adapter: cache.system doctrine.result_cache_pool: adapter: cache.app ``` -------------------------------- ### Oracle DB Middleware Configuration Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Configure a middleware for Oracle DB to ensure Doctrine is aware of the specific format used by Oracle DB. ```yaml services: oracle.middleware: class: Doctrine\DBAL\Driver\OCI8\Middleware\InitializeSession tags: - { name: doctrine.middleware, connection: default } ``` -------------------------------- ### Autowire Specific DBAL Connections by Type-Hinting Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Inject specific DBAL connections into your services by type-hinting the argument with the pattern `Doctrine\DBAL\Connection $Connection`. This allows for clear dependency injection of different database connections. ```diff - public function __construct(Connection $connection) + public function __construct(Connection $purchaseLogsConnection) { $this->connection = $purchaseLogsConnection; } ``` -------------------------------- ### Configure Replica Database Connection Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Defines a replica database connection. This is typically used for read-only replicas to distribute read traffic. ```xml ``` -------------------------------- ### Limit Middleware Scope to a Connection Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/middlewares.rst Use the `AsMiddleware` attribute with the `connections` option to apply the middleware only to the specified connection(s). ```php ``` -------------------------------- ### Register Event Listener with XML Configuration Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/event-listeners.rst Define event listeners in XML by using the 'doctrine.event_listener' tag on a service. The 'event' attribute is mandatory, and 'priority' and 'connection' can be specified for finer control. ```xml ``` -------------------------------- ### Configure Default Table Options Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Sets default options for all tables created by Doctrine ORM. This includes character set, collation, and storage engine. ```xml utf8mb4 utf8_unicode_ci InnoDB ``` -------------------------------- ### Configure ORM Second-Level Cache Logger Source: https://github.com/doctrine/doctrinebundle/blob/3.2.x/docs/en/configuration.rst Configures a logger for ORM's second-level cache operations. Specify the logger name and service. ```xml ```