跳到内容

Doctrine 配置参考 (DoctrineBundle)

编辑此页

DoctrineBundle 集成了 Symfony 应用程序中的 DBALORM Doctrine 项目。所有这些选项都在你的应用程序配置的 doctrine 键下配置。

1
2
3
4
5
# 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

注意

当使用 XML 时,你必须使用 http://symfony.ac.cn/schema/dic/doctrine 命名空间,相关的 XSD 模式可在以下网址找到:http://symfony.ac.cn/schema/dic/doctrine/doctrine-1.0.xsd

Doctrine DBAL 配置

DoctrineBundle 支持默认 Doctrine 驱动程序接受的所有参数,并转换为 Symfony 强制执行的 XML 或 YAML 命名标准。有关更多信息,请参阅 Doctrine DBAL 文档。以下代码块显示了所有可能的配置键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
doctrine:
    dbal:
        dbname:               database
        host:                 localhost
        port:                 1234
        user:                 user
        password:             secret
        driver:               pdo_mysql
        # if the url option is specified, it will override the above config
        url:                  mysql://db_user:[email protected]:3306/db_name
        # the DBAL driverClass option
        driver_class:         App\DBAL\MyDatabaseDriver
        # the DBAL driverOptions option
        options:
            foo: bar
        path:                 '%kernel.project_dir%/var/data/data.sqlite'
        memory:               true
        unix_socket:          /tmp/mysql.sock
        # the DBAL wrapperClass option
        wrapper_class:        App\DBAL\MyConnectionWrapper
        charset:              utf8mb4
        logging:              '%kernel.debug%'
        platform_service:     App\DBAL\MyDatabasePlatformService
        server_version:       '8.0.37'
        mapping_types:
            enum: string
        types:
            custom: App\DBAL\MyCustomType

注意

server_version 选项在 Doctrine DBAL 2.5 中添加,DoctrineBundle 1.3 使用了它。此选项的值应与你的数据库服务器版本匹配(使用 postgres -Vpsql -V 命令查找你的 PostgreSQL 版本,使用 mysql -V 获取你的 MySQL 版本)。

如果你正在运行 MariaDB 数据库,你必须在 server_version 值前加上 mariadb- 前缀(例如 server_version: mariadb-10.4.14)。这将在 Doctrine DBAL 4.x 中更改,你必须将版本定义为服务器输出的版本(例如 10.4.14-MariaDB)。

始终用引号包裹服务器版本号,将其解析为字符串而不是浮点数。否则,浮点表示问题可能会使你的版本被视为不同的数字(例如,5.7 将四舍五入为 5.6999999999999996447286321199499070644378662109375)。

如果你没有定义此选项,并且尚未创建数据库,你可能会收到 PDOException 错误,因为 Doctrine 将尝试自动猜测数据库服务器版本,但没有可用的版本。

如果要在 YAML 中配置多个连接,请将它们放在 connections 键下,并为它们指定唯一的名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
doctrine:
    dbal:
        default_connection:       default
        connections:
            default:
                dbname:           Symfony
                user:             root
                password:         null
                host:             localhost
                server_version:   '8.0.37'
            customer:
                dbname:           customer
                user:             root
                password:         null
                host:             localhost
                server_version:   '8.2.0'

database_connection 服务始终引用默认连接,即定义的第一个连接或通过 default_connection 参数配置的连接。

每个连接也可以通过 doctrine.dbal.[name]_connection 服务访问,其中 [name] 是连接的名称。在 控制器 中,你可以使用 getConnection() 方法和连接的名称来访问它

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/Controller/SomeController.php
use Doctrine\Persistence\ManagerRegistry;

class SomeController
{
    public function someMethod(ManagerRegistry $doctrine): void
    {
        $connection = $doctrine->getConnection('customer');
        $result = $connection->fetchAllAssociative('SELECT name FROM customer');

        // ...
    }
}

Doctrine ORM 配置

以下配置示例显示了 ORM 解析为的所有配置默认值

1
2
3
4
5
6
7
8
9
10
11
12
doctrine:
    orm:
        auto_mapping: true
        # the standard distribution overrides this to be true in debug, false otherwise
        auto_generate_proxy_classes: false
        proxy_namespace: Proxies
        proxy_dir: '%kernel.cache_dir%/doctrine/orm/Proxies'
        default_entity_manager: default
        metadata_cache_driver: array
        query_cache_driver: array
        result_cache_driver: array
        naming_strategy: doctrine.orm.naming_strategy.default

还有许多其他配置选项可用于覆盖某些类,但这些选项仅适用于非常高级的用例。

简化的配置语法

当你仅使用一个实体管理器时,所有可用的配置选项都可以直接放在 doctrine.orm 配置级别下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
doctrine:
    orm:
        # ...
        query_cache_driver:
            # ...
        metadata_cache_driver:
            # ...
        result_cache_driver:
            # ...
        connection: ~
        class_metadata_factory_name:  Doctrine\ORM\Mapping\ClassMetadataFactory
        default_repository_class:  Doctrine\ORM\EntityRepository
        auto_mapping: false
        naming_strategy: doctrine.orm.naming_strategy.default
        hydrators:
            # ...
        mappings:
            # ...
        dql:
            # ...
        filters:
            # ...

此缩短版本在其他文档章节中常用。请记住,你不能同时使用两种语法。

缓存驱动

使用任何现有的 Symfony 缓存 池或定义新的池来缓存 Doctrine ORM 的每个元素(查询、结果等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# config/packages/prod/doctrine.yaml
framework:
    cache:
        pools:
            doctrine.result_cache_pool:
                adapter: cache.app
            doctrine.system_cache_pool:
                adapter: cache.system

doctrine:
    orm:
        # ...
        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

        # in addition to Symfony Cache pools, you can also use the
        # 'type: service' option to use any service as the cache
        query_cache_driver:
            type: service
            id: App\ORM\MyCacheService

映射配置

显式定义所有映射实体是 ORM 的唯一必要配置,并且有几个配置选项可以控制。以下配置选项适用于映射

类型

以下之一:attribute(用于 PHP 属性;它是默认值)、xmlphpstaticphp。这指定了你的映射使用的元数据类型。

3.0

yml 映射配置已弃用,并在 Doctrine ORM 3.0 中删除。

有关此选项的更多信息,请参阅 Doctrine 元数据驱动

目录

映射或实体文件的绝对路径(取决于驱动程序)。

前缀

此映射的所有实体共享的公共命名空间前缀。此前缀绝不能与其他已定义映射的前缀冲突,否则 Doctrine 将无法找到你的某些实体。

别名

Doctrine 提供了一种别名实体命名空间的方法,可以使用更简单、更短的名称用于 DQL 查询或 Repository 访问。

is_bundle

此选项默认为 false,并且被认为是遗留选项。它仅在以前的 Symfony 版本中很有用,当时建议使用 bundle 来组织应用程序代码。

Bundle 中的自定义映射实体

Doctrine 的 auto_mapping 功能从每个 bundle 的 Entity/ 目录加载属性配置,Resources/config/doctrine 目录中查找其他格式(例如 YAML、XML)。

如果将元数据存储在 bundle 中的其他位置,你可以定义自己的映射,在其中告诉 Doctrine 在哪里查找,以及一些其他配置。

如果你正在使用 auto_mapping 配置,你只需要覆盖你想要的配置。在这种情况下,映射配置的键与 bundle 的名称相对应非常重要。

例如,假设你决定将 AppBundle 实体的 XML 配置存储在 @AppBundle/SomeResources/config/doctrine 目录中,而不是

1
2
3
4
5
6
7
8
9
10
doctrine:
    # ...
    orm:
        # ...
        auto_mapping: true
        mappings:
            # ...
            AppBundle:
                type: xml
                dir: SomeResources/config/doctrine

Bundle 外部的映射实体

例如,以下代码在 src/Entity 目录中的 Entity 命名空间中查找实体类,并为它们提供 App 别名(因此你可以说诸如 App:Post 之类的话)

1
2
3
4
5
6
7
8
9
10
11
12
doctrine:
        # ...
        orm:
            # ...
            mappings:
                # ...
                SomeEntityNamespace:
                    type: attribute
                    dir: '%kernel.project_dir%/src/Entity'
                    is_bundle: false
                    prefix: App\Entity
                    alias: App

检测映射配置格式

如果未在 bundle 配置上设置 type,则 DoctrineBundle 将尝试检测 bundle 的正确映射配置格式。

DoctrineBundle 将在你的映射的配置 dir 中查找与 *.orm.[FORMAT] 匹配的文件(例如 Post.orm.yaml)(如果你正在映射 bundle,则 dir 相对于 bundle 的目录)。

bundle 按此顺序查找 XML、YAML 和 PHP 文件。使用 auto_mapping 功能,每个 bundle 只能有一种配置格式。bundle 将在找到一种格式后立即停止。

如果无法确定 bundle 的配置格式,DoctrineBundle 将检查 bundle 的根目录中是否存在 Entity 文件夹。如果文件夹存在,Doctrine 将回退到使用属性。

Dir 的默认值

如果未指定 dir,则其默认值取决于正在使用的配置驱动程序。对于依赖于 PHP 文件(属性、staticphp)的驱动程序,它将是 [Bundle]/Entity。对于使用配置文件(XML、YAML 等)的驱动程序,它将是 [Bundle]/Resources/config/doctrine

如果设置了 dir 配置,并且 is_bundle 配置为 true,则 DoctrineBundle 将在 dir 配置前加上 bundle 的路径。

使用 MySQL 的 SSL 连接

要在你的 Symfony 应用程序中使用 Doctrine 安全地配置到 MySQL 的 SSL 连接,你需要指定 SSL 证书选项。以下是如何使用环境变量为证书路径设置连接

1
2
3
4
5
6
7
8
9
10
11
12
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)%'

确保你的环境变量在 .env.local.env.local.php 文件中正确设置,如下所示

1
2
3
MYSQL_SSL_KEY=/path/to/your/server-key.pem
MYSQL_SSL_CERT=/path/to/your/server-cert.pem
MYSQL_SSL_CA=/path/to/your/ca-cert.pem

此配置通过指定所需证书的路径来保护你的 MySQL 连接与 SSL 的安全。

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可证获得许可。
目录
    版本