Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Version:

Doctrine Configuration Reference (DoctrineBundle)

Edit this page

The DoctrineBundle integrates both theDBAL andORM Doctrine projects in Symfony applications. All theseoptions are configured under thedoctrine key in your applicationconfiguration.

12345
# displays the default config values defined by Symfony$php bin/console config:dump-reference doctrine# displays the actual config values used by your application$php bin/console debug:config doctrine

Note

When using XML, you must use thehttp://symfony.com/schema/dic/doctrinenamespace and the related XSD schema is available at:https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd

Doctrine DBAL Configuration

DoctrineBundle supports all parameters that default Doctrine driversaccept, converted to the XML or YAML naming standards that Symfonyenforces. See the DoctrineDBAL documentation for more information.The following block shows all possible configuration keys:

12345678910111213141516171819202122232425262728
doctrine:dbal:dbname:databasehost:localhostport:1234user:userpassword:secretdriver:pdo_mysql# if the url option is specified, it will override the above configurl:mysql://db_user:db_password@127.0.0.1:3306/db_name# the DBAL driverClass optiondriver_class:App\DBAL\MyDatabaseDriver# the DBAL driverOptions optionoptions:foo:barpath:'%kernel.project_dir%/var/data/data.sqlite'memory:trueunix_socket:/tmp/mysql.sock# the DBAL wrapperClass optionwrapper_class:App\DBAL\MyConnectionWrappercharset:utf8mb4logging:'%kernel.debug%'platform_service:App\DBAL\MyDatabasePlatformServiceserver_version:'8.0.37'mapping_types:enum:stringtypes:custom:App\DBAL\MyCustomType
12345678910111213141516171819202122232425262728293031323334
<?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:doctrine="http://symfony.com/schema/dic/doctrine"xsi:schemaLocation="http://symfony.com/schema/dic/services        https://symfony.com/schema/dic/services/services-1.0.xsd        http://symfony.com/schema/dic/doctrine        https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd"><doctrine:config><doctrine:dbalname="default"dbname="database"host="localhost"port="1234"user="user"password="secret"driver="pdo_mysql"driver-class="App\DBAL\MyDatabaseDriver"path="%kernel.project_dir%/var/data/data.sqlite"memory="true"unix-socket="/tmp/mysql.sock"wrapper-class="App\DBAL\MyConnectionWrapper"charset="utf8mb4"logging="%kernel.debug%"platform-service="App\DBAL\MyDatabasePlatformService"server-version="8.0.37"><doctrine:optionkey="foo">bar</doctrine:option><doctrine:mapping-typename="enum">string</doctrine:mapping-type><doctrine:typename="custom">App\DBAL\MyCustomType</doctrine:type></doctrine:dbal></doctrine:config></container>
123456789101112131415161718192021222324252627
useSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$dbal =$doctrine->dbal();$dbal =$dbal        ->connection('default')            ->dbname('database')            ->host('localhost')            ->port(1234)            ->user('user')            ->password('secret')            ->driver('pdo_mysql')            ->url('mysql://db_user:db_password@127.0.0.1:3306/db_name')// if the url option is specified, it will override the above config            ->driverClass(App\DBAL\MyDatabaseDriver::class)// the DBAL driverClass option            ->option('foo','bar')// the DBAL driverOptions option            ->path('%kernel.project_dir%/var/data/data.sqlite')            ->memory(true)            ->unixSocket('/tmp/mysql.sock')            ->wrapperClass(App\DBAL\MyConnectionWrapper::class)// the DBAL wrapperClass option            ->charset('utf8mb4')            ->logging('%kernel.debug%')            ->platformService(App\DBAL\MyDatabasePlatformService::class)            ->serverVersion('8.0.37')            ->mappingType('enum','string')            ->type('custom', App\DBAL\MyCustomType::class);};

Note

Theserver_version option was added in Doctrine DBAL 2.5, whichis used by DoctrineBundle 1.3. The value of this option should matchyour database server version (usepostgres -V orpsql -V commandto find your PostgreSQL version andmysql -V to get your MySQLversion).

If you are running a MariaDB database, you must prefix theserver_versionvalue withmariadb- (e.g.server_version: mariadb-10.4.14). This willchange in Doctrine DBAL 4.x, where you must define the version as output bythe server (e.g.10.4.14-MariaDB).

Always wrap the server version number with quotes to parse it as a stringinstead of a float number. Otherwise, the floating-point representationissues can make your version be considered a different number (e.g.5.7will be rounded as5.6999999999999996447286321199499070644378662109375).

If you don't define this option and you haven't created your databaseyet, you may getPDOException errors because Doctrine will try toguess the database server version automatically and none is available.

If you want to configure multiple connections in YAML, put them under theconnections key and give them a unique name:

12345678910111213141516
doctrine:dbal:default_connection:defaultconnections:default:dbname:Symfonyuser:rootpassword:nullhost:localhostserver_version:'8.0.37'customer:dbname:customeruser:rootpassword:nullhost:localhostserver_version:'8.2.0'
1234567891011121314151617181920
useSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$dbal =$doctrine->dbal();$dbal->defaultConnection('default');$dbal->connection('default')        ->dbname('Symfony')        ->user('root')        ->password('null')        ->host('localhost')        ->serverVersion('8.0.37');$dbal->connection('customer')        ->dbname('customer')        ->user('root')        ->password('null')        ->host('localhost')        ->serverVersion('8.2.0');};

Thedatabase_connection service always refers to thedefault connection,which is the first one defined or the one configured via thedefault_connection parameter.

Each connection is also accessible via thedoctrine.dbal.[name]_connectionservice where[name] is the name of the connection. In acontrolleryou can access it using thegetConnection() method and the name of the connection:

12345678910111213
// src/Controller/SomeController.phpuseDoctrine\Persistence\ManagerRegistry;classSomeController{publicfunctionsomeMethod(ManagerRegistry$doctrine):void{$connection =$doctrine->getConnection('customer');$result =$connection->fetchAllAssociative('SELECT name FROM customer');// ...    }}

Doctrine ORM Configuration

This following configuration example shows all the configuration defaultsthat the ORM resolves to:

123456789101112
doctrine:orm:auto_mapping:false# the standard distribution overrides this to be true in debug, false otherwiseauto_generate_proxy_classes:falseproxy_namespace:Proxiesproxy_dir:'%kernel.cache_dir%/doctrine/orm/Proxies'default_entity_manager:defaultmetadata_cache_driver:arrayquery_cache_driver:arrayresult_cache_driver:arraynaming_strategy:doctrine.orm.naming_strategy.default
1234567891011121314151617181920
useSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$orm =$doctrine->orm();$orm        ->entityManager('default')        ->connection('default')        ->autoMapping(true)        ->metadataCacheDriver()->type('array')        ->queryCacheDriver()->type('array')        ->resultCacheDriver()->type('array')        ->namingStrategy('doctrine.orm.naming_strategy.default');$orm        ->autoGenerateProxyClasses(false)        ->proxyNamespace('Proxies')        ->proxyDir('%kernel.cache_dir%/doctrine/orm/Proxies')        ->defaultEntityManager('default');};

There are lots of other configuration options that you can use to overwritecertain classes, but those are for very advanced use-cases only.

Shortened Configuration Syntax

When you are only using one entity manager, all config options availablecan be placed directly underdoctrine.orm config level.

12345678910111213141516171819202122
doctrine:orm:# ...query_cache_driver:# ...metadata_cache_driver:# ...result_cache_driver:# ...connection:~class_metadata_factory_name:Doctrine\ORM\Mapping\ClassMetadataFactorydefault_repository_class:Doctrine\ORM\EntityRepositoryauto_mapping:falsenaming_strategy:doctrine.orm.naming_strategy.defaulthydrators:# ...mappings:# ...dql:# ...filters:# ...

This shortened version is commonly used in other documentation sections.Keep in mind that you can't use both syntaxes at the same time.

Caching Drivers

Use any of the existingSymfony Cache pools or define new poolsto cache each of Doctrine ORM elements (queries, results, etc.):

123456789101112131415161718192021222324252627
# config/packages/prod/doctrine.yamlframework:cache:pools:doctrine.result_cache_pool:adapter:cache.appdoctrine.system_cache_pool:adapter:cache.systemdoctrine:orm:# ...metadata_cache_driver:type:poolpool:doctrine.system_cache_poolquery_cache_driver:type:poolpool:doctrine.system_cache_poolresult_cache_driver:type:poolpool:doctrine.result_cache_pool# in addition to Symfony cache pools, you can also use the# 'type: service' option to use any service as a cache poolquery_cache_driver:type:serviceid:App\ORM\MyCacheService
123456789101112131415161718192021222324252627282930
useSymfony\Config\DoctrineConfig;useSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework, DoctrineConfig$doctrine):void{$framework        ->cache()            ->pool('doctrine.result_cache_pool')                ->adapters('cache.app')            ->pool('doctrine.system_cache_pool')                ->adapters('cache.sytsem');$doctrine->orm()// ...        ->entityManager('default')        ->metadataCacheDriver()            ->type('pool')            ->pool('doctrine.system_cache_pool')        ->queryCacheDriver()            ->type('pool')            ->pool('doctrine.system_cache_pool')        ->resultCacheDriver()            ->type('pool')            ->pool('doctrine.result_cache_pool')// in addition to Symfony cache pools, you can also use the// 'type: service' option to use any service as a cache pool        ->queryCacheDriver()            ->type('service')            ->id(App\ORM\MyCacheService::class);};

Mapping Configuration

Explicit definition of all the mapped entities is the only necessaryconfiguration for the ORM and there are several configuration options thatyou can control. The following configuration options exist for a mapping:

type

One ofattribute (for PHP attributes; it's the default value),xml,php orstaticphp. This specifies whichtype of metadata type your mapping uses.

3.0

Theyml mapping configuration is deprecated and was removed in Doctrine ORM 3.0.

SeeDoctrine Metadata Drivers for more information about this option.

dir

Absolute path to the mapping or entity files (depending on the driver).

prefix

A common namespace prefix that all entities of this mapping share. This prefixshould never conflict with prefixes of other defined mappings otherwise some ofyour entities cannot be found by Doctrine.

alias

Doctrine offers a way to alias entity namespaces to simpler, shorter namesto be used in DQL queries or for Repository access.

is_bundle

This option isfalse by default and it's considered a legacy option. It wasonly useful in previous Symfony versions, when it was recommended to use bundlesto organize the application code.

Custom Mapping Entities in a Bundle

Doctrine'sauto_mapping feature loads attribute configuration fromtheEntity/ directory of each bundleand looks for other formats (e.g.YAML, XML) in theResources/config/doctrine directory.

If you store metadata somewhere else in your bundle, you can define yourown mappings, where you tell Doctrine exactlywhere to look, along withsome other configurations.

If you're using theauto_mapping configuration, you just need to overwritethe configurations you want. In this case it's important that the key ofthe mapping configurations corresponds to the name of the bundle.

For example, suppose you decide to store yourXML configuration forAppBundle entities in the@AppBundle/SomeResources/config/doctrinedirectory instead:

12345678910
doctrine:# ...orm:# ...auto_mapping:truemappings:# ...AppBundle:type:xmldir:SomeResources/config/doctrine
12345678910111213
<?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:doctrine="http://symfony.com/schema/dic/doctrine"xsi:schemaLocation="http://symfony.com/schema/dic/services        https://symfony.com/schema/dic/services/services-1.0.xsd"><doctrine:config><doctrine:ormauto-mapping="true"><mappingname="AppBundle"dir="SomeResources/config/doctrine"type="xml"/></doctrine:orm></doctrine:config></container>
1234567891011
useSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$emDefault =$doctrine->orm()->entityManager('default');$emDefault->autoMapping(true);$emDefault->mapping('AppBundle')        ->type('xml')        ->dir('SomeResources/config/doctrine')    ;};

Mapping Entities Outside of a Bundle

For example, the following looks for entity classes in theEntitynamespace in thesrc/Entity directory and gives them anApp alias(so you can say things likeApp:Post):

123456789101112
doctrine:# ...orm:# ...mappings:# ...SomeEntityNamespace:type:attributedir:'%kernel.project_dir%/src/Entity'is_bundle:falseprefix:App\Entityalias:App
12345678910111213141516171819
<?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:doctrine="http://symfony.com/schema/dic/doctrine"xsi:schemaLocation="http://symfony.com/schema/dic/services        https://symfony.com/schema/dic/services/services-1.0.xsd"><doctrine:config><doctrine:orm><mappingname="SomeEntityNamespace"type="attribute"dir="%kernel.project_dir%/src/Entity"is-bundle="false"prefix="App\Entity"alias="App"            /></doctrine:orm></doctrine:config></container>
1234567891011121314
useSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$emDefault =$doctrine->orm()->entityManager('default');$emDefault->autoMapping(true);$emDefault->mapping('SomeEntityNamespace')        ->type('attribute')        ->dir('%kernel.project_dir%/src/Entity')        ->isBundle(false)        ->prefix('App\Entity')        ->alias('App')    ;};

Detecting a Mapping Configuration Format

If thetype on the bundle configuration isn't set, the DoctrineBundlewill try to detect the correct mapping configuration format for the bundle.

DoctrineBundle will look for files matching*.orm.[FORMAT] (e.g.Post.orm.yaml) in the configureddir of your mapping (if you're mappinga bundle, thendir is relative to the bundle's directory).

The bundle looks for (in this order) XML, YAML and PHP files.Using theauto_mapping feature, every bundle can have only oneconfiguration format. The bundle will stop as soon as it locates one.

If it wasn't possible to determine a configuration format for a bundle,the DoctrineBundle will check if there is anEntity folder in the bundle'sroot directory. If the folder exist, Doctrine will fall back to usingattributes.

Default Value of Dir

Ifdir is not specified, then its default value depends on which configurationdriver is being used. For drivers that rely on the PHP files (attribute,staticphp) it will be[Bundle]/Entity. For drivers that are usingconfiguration files (XML, YAML, ...) it will be[Bundle]/Resources/config/doctrine.

If thedir configuration is set and theis_bundle configurationistrue, the DoctrineBundle will prefix thedir configuration withthe path of the bundle.

SSL Connection with MySQL

To securely configure an SSL connection to MySQL in your Symfony applicationwith Doctrine, you need to specify the SSL certificate options. Here's how toset up the connection using environment variables for the certificate paths:

123456789101112
doctrine:dbal:url:'%env(DATABASE_URL)%'server_version:'8.0.31'driver:'pdo_mysql'options:# SSL private key!php/const'PDO::MYSQL_ATTR_SSL_KEY':'%env(MYSQL_SSL_KEY)%'# SSL certificate!php/const'PDO::MYSQL_ATTR_SSL_CERT':'%env(MYSQL_SSL_CERT)%'# SSL CA authority!php/const'PDO::MYSQL_ATTR_SSL_CA':'%env(MYSQL_SSL_CA)%'
123456789101112131415161718192021
<?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:doctrine="http://symfony.com/schema/dic/doctrine"xsi:schemaLocation="http://symfony.com/schema/dic/services        https://symfony.com/schema/dic/services/services-1.0.xsd        http://symfony.com/schema/dic/doctrine        https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd"><doctrine:config><doctrine:dbalurl="%env(DATABASE_URL)%"server-version="8.0.31"driver="pdo_mysql"><doctrine:optionkey-type="constant"key="PDO::MYSQL_ATTR_SSL_KEY">%env(MYSQL_SSL_KEY)%</doctrine:option><doctrine:optionkey-type="constant"key="PDO::MYSQL_ATTR_SSL_CERT">%env(MYSQL_SSL_CERT)%</doctrine:option><doctrine:optionkey-type="constant"key="PDO::MYSQL_ATTR_SSL_CA">%env(MYSQL_SSL_CA)%</doctrine:option></doctrine:dbal></doctrine:config></container>
12345678910111213141516
// config/packages/doctrine.phpuseSymfony\Config\DoctrineConfig;returnstaticfunction(DoctrineConfig$doctrine):void{$doctrine->dbal()        ->connection('default')        ->url(env('DATABASE_URL')->resolve())        ->serverVersion('8.0.31')        ->driver('pdo_mysql');$doctrine->dbal()->defaultConnection('default');$doctrine->dbal()->option(\PDO::MYSQL_ATTR_SSL_KEY,'%env(MYSQL_SSL_KEY)%');$doctrine->dbal()->option(\PDO::MYSQL_SSL_CERT,'%env(MYSQL_ATTR_SSL_CERT)%');$doctrine->dbal()->option(\PDO::MYSQL_SSL_CA,'%env(MYSQL_ATTR_SSL_CA)%');};

Ensure your environment variables are correctly set in the.env.local or.env.local.php file as follows:

123
MYSQL_SSL_KEY=/path/to/your/server-key.pemMYSQL_SSL_CERT=/path/to/your/server-cert.pemMYSQL_SSL_CA=/path/to/your/ca-cert.pem

This configuration secures your MySQL connection with SSL by specifying the paths to the required certificates.

This work, including the code samples, is licensed under aCreative Commons BY-SA 3.0 license.
TOC
    Version

    Symfony 7.3backers


    [8]ページ先頭

    ©2009-2025 Movatter.jp