33. Advanced Configuration

The configuration of the EntityManager requires a Doctrine\ORM\Configuration instance as well as some database connection parameters. This example shows all the potential steps of configuration.

EntityManager の構成には、Doctrine\ORM\Configuration インスタンスといくつかのデータベース接続パラメーターが必要です。この例は、構成の潜在的なすべてのステップを示しています。

<?php

use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AttributeDriver;
use Doctrine\ORM\ORMSetup;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;

// ...

if ($applicationMode == "development") {
    $queryCache = new ArrayAdapter();
    $metadataCache = new ArrayAdapter();
} else {
    $queryCache = new PhpFilesAdapter('doctrine_queries');
    $metadataCache = new PhpFilesAdapter('doctrine_metadata');
}

$config = new Configuration;
$config->setMetadataCache($metadataCache);
$driverImpl = new AttributeDriver(['/path/to/lib/MyProject/Entities']);
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCache($queryCache);
$config->setProxyDir('/path/to/myproject/lib/MyProject/Proxies');
$config->setProxyNamespace('MyProject\Proxies');

if ($applicationMode == "development") {
    $config->setAutoGenerateProxyClasses(true);
} else {
    $config->setAutoGenerateProxyClasses(false);
}

$connection = DriverManager::getConnection([
    'driver' => 'pdo_sqlite',
    'path' => 'database.sqlite',
], $config);

$em = new EntityManager($connection, $config);

33.1. Doctrine and Caching

Doctrine is optimized for working with caches. The main parts in Doctrine that are optimized for caching are the metadata mapping information with the metadata cache and the DQL to SQL conversions with the query cache. These 2 caches require only an absolute minimum of memory yet they heavily improve the runtime performance of Doctrine.

Doctrine は、キャッシュを操作するために最適化されています。キャッシング用に最適化された Doctrine の主な部分は、メタデータ キャッシュを使用したメタデータ マッピング情報と、クエリ キャッシュを使用した DQL から SQL への変換です。これら 2 つのキャッシュは、最小限のメモリしか必要としませんが、Doctrine のランタイム パフォーマンスを大幅に向上させます。

Doctrine does not bundle its own cache implementation anymore. Instead, the PSR-6 standard interfaces are used to access the cache. In the examples in this documentation, Symfony Cache is used as a reference implementation.

Doctrine は独自のキャッシュ実装をバンドルしなくなりました。代わりに、PSR-6 標準インターフェイスを使用してキャッシュにアクセスします。このドキュメントの例では、Symfony Cache が参照実装として使用されています。

Note

ノート

Do not use Doctrine without a metadata and query cache!

メタデータとクエリ キャッシュなしで Doctrine を使用しないでください!

33.2. Configuration Options

The following sections describe all the configuration options available on a Doctrine\ORM\Configuration instance.

以下のセクションでは、Doctrine\ORM\Configuration インスタンスで利用可能なすべての設定オプションについて説明します。

33.2.1. Proxy Directory (*REQUIRED*)

<?php
$config->setProxyDir($dir);
$config->getProxyDir();

Gets or sets the directory where Doctrine generates any proxy classes. For a detailed explanation on proxy classes and how they are used in Doctrine, refer to the “Proxy Objects” section further down.

Doctrine がプロキシクラスを生成するディレクトリを取得または設定します。プロキシ クラスの詳細な説明と Doctrine での使用方法については、「プロキシ オブジェクト」セクションを参照してください。

33.2.2. Proxy Namespace (*REQUIRED*)

<?php
$config->setProxyNamespace($namespace);
$config->getProxyNamespace();

Gets or sets the namespace to use for generated proxy classes. For a detailed explanation on proxy classes and how they are used in Doctrine, refer to the “Proxy Objects” section further down.

生成されたプロキシ クラスに使用する名前空間を取得または設定します。プロキシ クラスとそれらが Doctrine でどのように使用されるかについての詳細な説明については、「プロキシ オブジェクト」セクションを参照してください。

33.2.3. Metadata Driver (*REQUIRED*)

<?php
$config->setMetadataDriverImpl($driver);
$config->getMetadataDriverImpl();

Gets or sets the metadata driver implementation that is used by Doctrine to acquire the object-relational metadata for your classes.

クラスのオブジェクト リレーショナル メタデータを取得するために Doctrine によって使用されるメタデータ ドライバーの実装を取得または設定します。

There are currently 5 available implementations:

現在利用可能な実装は 5 つあります。

  • Doctrine\ORM\Mapping\Driver\AttributeDriver

    Doctrine\ORM\Mapping\Driver\AttributeDriver

  • Doctrine\ORM\Mapping\Driver\XmlDriver

    Doctrine\ORM\Mapping\Driver\XmlDriver

  • Doctrine\ORM\Mapping\Driver\DriverChain

    Doctrine\ORM\Mapping\Driver\DriverChain

  • Doctrine\ORM\Mapping\Driver\AnnotationDriver (deprecated and will

    Doctrine\ORM\Mapping\Driver\AnnotationDriver (非推奨であり、

be removed in doctrine/orm 3.0)

doctrine/orm 3.0 で削除されます)

  • Doctrine\ORM\Mapping\Driver\YamlDriver (deprecated and will be removed in doctrine/orm 3.0)

    Doctrine\ORM\Mapping\Driver\YamlDriver (非推奨であり、doctrine/orm 3.0 で削除されます)

Throughout the most part of this manual the AttributeDriver is used in the examples. For information on the usage of the AnnotationDriver, XmlDriver or YamlDriver please refer to the dedicated chapters Annotation Reference, XML Mapping and YAML Mapping.

このマニュアルのほとんどの部分で、AttributeDriver が例で使用されています。 AnnotationDriver、XmlDriver、または YamlDriver の使用方法については、注釈リファレンス、XML マッピング、および YAML マッピングの専用の章を参照してください。

The attribute driver can be injected in the Doctrine\ORM\Configuration:

属性ドライバーは、Doctrine\ORM\Configuration に挿入できます。

<?php
use Doctrine\ORM\Mapping\Driver\AttributeDriver;

$driverImpl = new AttributeDriver(['/path/to/lib/MyProject/Entities']);
$config->setMetadataDriverImpl($driverImpl);

The path information to the entities is required for the attribute driver, because otherwise mass-operations on all entities through the console could not work correctly. All of metadata drivers accept either a single directory as a string or an array of directories. With this feature a single driver can support multiple directories of Entities.

属性ドライバにはエンティティへのパス情報が必要です。そうしないと、コンソールを介したすべてのエンティティに対する一括操作が正しく機能しない可能性があるためです。すべてのメタデータ ドライバーは、単一のディレクトリを文字列またはディレクトリの配列として受け入れます。この機能を使用すると、1 つのドライバーでエンティティの複数のディレクトリをサポートできます。

33.2.6. SQL Logger (*Optional*)

<?php
$config->setSQLLogger($logger);
$config->getSQLLogger();

Gets or sets the logger to use for logging all SQL statements executed by Doctrine. The logger class must implement the deprecated Doctrine\DBAL\Logging\SQLLogger interface.

Doctrine によって実行されるすべての SQL ステートメントをログに記録するために使用するロガーを取得または設定します。ロガー クラスは非推奨の Doctrine\DBAL\Logging\SQLLogger インターフェイスを実装する必要があります。

33.2.7. Auto-generating Proxy Classes (*OPTIONAL*)

Proxy classes can either be generated manually through the Doctrine Console or automatically at runtime by Doctrine. The configuration option that controls this behavior is:

Proxy クラスは、DoctrineConsole を介して手動で生成することも、実行時に Doctrine によって自動的に生成することもできます。この動作を制御する構成オプションは次のとおりです。

<?php
$config->setAutoGenerateProxyClasses($mode);

Possible values for $mode are:

$mode の可能な値は次のとおりです。

  • Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_NEVER

    Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_NEVER

Never autogenerate a proxy. You will need to generate the proxies manually, for this use the Doctrine Console like so:

プロキシを自動生成しないでください。プロキシを手動で生成する必要があります。これには、Doctrine コンソールを次のように使用します。

$ ./doctrine orm:generate-proxies

When you do this in a development environment, be aware that you may get class/file not found errors if certain proxies are not yet generated. You may also get failing lazy-loads if new methods were added to the entity class that are not yet in the proxy class. In such a case, simply use the Doctrine Console to (re)generate the proxy classes.

開発環境でこれを行う場合、特定のプロキシがまだ生成されていない場合、クラス/ファイルが見つからないというエラーが発生する可能性があることに注意してください。プロキシ クラスにまだない新しいメソッドがエンティティ クラスに追加された場合、遅延読み込みに失敗することもあります。そのような場合は、単純に Doctrine コンソールを使用してプロキシ クラスを (再) 生成します。

  • Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_ALWAYS

    Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_ALWAYS

Always generates a new proxy in every request and writes it to disk.

すべてのリクエストで常に新しいプロキシを生成し、ディスクに書き込みます。

  • Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS

    Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS

Generate the proxy class when the proxy file does not exist. This strategy causes a file exists call whenever any proxy is used the first time in a request.

プロキシ ファイルが存在しない場合にプロキシ クラスを生成します。この方法では、リクエストで初めてプロキシが使用されるたびに、ファイルが存在するという呼び出しが発生します。

  • Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_EVAL

    Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_EVAL

Generate the proxy classes and evaluate them on the fly via eval(), avoiding writing the proxies to disk. This strategy is only sane for development.

プロキシ クラスを生成し、eval() を介してオンザフライで評価し、プロキシをディスクに書き込むことを回避します。この戦略は、開発にのみ有効です。

In a production environment, it is highly recommended to use AUTOGENERATE_NEVER to allow for optimal performances. The other options are interesting in development environment.

本番環境では、AUTOGENERATE_NEVER を使用して最適なパフォーマンスを実現することを強くお勧めします。その他のオプションは、開発環境で興味深いものです。

setAutoGenerateProxyClasses can accept a boolean value. This is still possible, FALSE being equivalent to AUTOGENERATE_NEVER and TRUE to AUTOGENERATE_ALWAYS.

setAutoGenerateProxyClasses はブール値を受け入れることができます。これはまだ可能で、FALSE は AUTOGENERATE_NEVER に相当し、TRUE は AUTOGENERATE_ALWAYS に相当します。

33.3. Development vs Production Configuration

You should code your Doctrine2 bootstrapping with two different runtime models in mind. There are some serious benefits of using APCu or Memcache in production. In development however this will frequently give you fatal errors, when you change your entities and the cache still keeps the outdated metadata. That is why we recommend an array cache for development.

2 つの異なるランタイム モデルを念頭に置いて、Doctrine2 ブートストラップをコーディングする必要があります。本番環境で APCu または Memcache を使用することには、いくつかの重大な利点があります。ただし、開発中は、エンティティを変更し、キャッシュがまだ古いメタデータを保持している場合に、致命的なエラーが発生することがよくあります。これが、開発用に配列キャッシュを推奨する理由です。

Furthermore you should have the Auto-generating Proxy Classes option to true in development and to false in production. If this option is set to TRUE it can seriously hurt your script performance if several proxy classes are re-generated during script execution. Filesystem calls of that magnitude can even slower than all the database queries Doctrine issues. Additionally writing a proxy sets an exclusive file lock which can cause serious performance bottlenecks in systems with regular concurrent requests.

さらに、Auto-generating Proxy Classes オプションを開発では true に、本番環境では false にする必要があります。このオプションが TRUE に設定されている場合、スクリプトの実行中に複数のプロキシ クラスが再生成されると、スクリプトのパフォーマンスが大幅に低下する可能性があります。その規模のファイルシステム呼び出しは、Doctrine が発行するすべてのデータベース クエリよりも遅くなる可能性があります。さらに aproxy を書き込むと排他的なファイル ロックが設定され、通常の同時要求があるシステムで深刻なパフォーマンスのボトルネックを引き起こす可能性があります。

33.4. Connection

The $connection passed as the first argument to he constructor of EntityManager has to be an instance of Doctrine\DBAL\Connection. You can use the factory Doctrine\DBAL\DriverManager::getConnection() to create such a connection. The DBAL configuration is explained in the DBAL section.

EntityManager のコンストラクターに最初の引数として渡される $connection は、Doctrine\DBAL\Connection のインスタンスでなければなりません。ファクトリ Doctrine\DBAL\DriverManager::getConnection() を使用して、そのような接続を作成できます。 DBAL 構成については、DBAL セクションで説明されています。

33.5. Proxy Objects

A proxy object is an object that is put in place or used instead of the “real” object. A proxy object can add behavior to the object being proxied without that object being aware of it. In ORM, proxy objects are used to realize several features but mainly for transparent lazy-loading.

プロキシ オブジェクトは、「実際の」オブジェクトの代わりに配置または使用されるオブジェクトです。プロキシ オブジェクトは、オブジェクトが認識しなくても、プロキシ対象のオブジェクトに動作を追加できます。 ORM では、プロキシ オブジェクトはいくつかの機能を実現するために使用されますが、主に透過的な遅延読み込みに使用されます。

Proxy objects with their lazy-loading facilities help to keep the subset of objects that are already in memory connected to the rest of the objects. This is an essential property as without it there would always be fragile partial objects at the outer edges of your object graph.

遅延読み込み機能を備えたプロキシ オブジェクトは、メモリ内に既に存在するオブジェクトのサブセットを残りのオブジェクトに接続しておくのに役立ちます。これがないと、オブジェクト グラフの外縁に壊れやすい部分オブジェクトが常に存在するため、これは必須のプロパティです。

Doctrine ORM implements a variant of the proxy pattern where it generates classes that extend your entity classes and adds lazy-loading capabilities to them. Doctrine can then give you an instance of such a proxy class whenever you request an object of the class being proxied. This happens in two situations:

Doctrine ORM はプロキシ パターンのバリアントを実装し、エンティティ クラスを拡張して遅延読み込み機能を追加するクラスを生成します。 Doctrine は、プロキシされているクラスのオブジェクトをリクエストするたびに、そのようなプロキシ クラスのインスタンスを提供できます。これは、次の 2 つの状況で発生します。

33.5.1. Reference Proxies

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier. You could simply do this:

メソッド EntityManager#getReference($entityName, $identifier) を使用すると、データベースからエンティティをロードすることなく、識別子が既知のエンティティへの参照を取得できます。これは、たとえば、識別子を持つエンティティへの関連付けを確立する場合に、パフォーマンスの向上として役立ちます。これを簡単に行うことができます:

<?php
// $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
// $itemId comes from somewhere, probably a request parameter
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->addItem($item);

Here, we added an Item to a Cart without loading the Item from the database. If you access any state that isn’t yet available in the Item instance, the proxying mechanism would fully initialize the object’s state transparently from the database. Here $item is actually an instance of the proxy class that was generated for the Item class but your code does not need to care. In fact it should not care. Proxy objects should be transparent to your code.

ここでは、アイテムをデータベースからロードせずにカートに追加しました。 Item インスタンスでまだ使用できない状態にアクセスすると、プロキシ メカニズムによってオブジェクトの状態がデータベースから透過的に完全に初期化されます。 $item は、実際には Item クラス用に生成されたプロキシ クラスのインスタンスですが、コードで気にする必要はありません。実際、気にする必要はありません。プロキシ オブジェクトはコードに対して透過的である必要があります。

33.5.2. Association proxies

The second most important situation where Doctrine uses proxy objects is when querying for objects. Whenever you query for an object that has a single-valued association to another object that is configured LAZY, without joining that association in the same query, Doctrine puts proxy objects in place where normally the associated object would be. Just like other proxies it will transparently initialize itself on first access.

Doctrine がプロキシオブジェクトを使用する 2 番目に重要な状況は、オブジェクトをクエリするときです。同じクエリでその関連付けに参加せずに、LAZY に設定された別のオブジェクトへの単一値の関連付けを持つオブジェクトをクエリすると、Doctrine は通常関連付けられたオブジェクトがある場所にプロキシ オブジェクトを配置します。他のプロキシと同様に、最初のアクセス時に自身を透過的に初期化します。

Note

ノート

Joining an association in a DQL or native query essentially means eager loading of that association in that query. This will override the ‘fetch’ option specified in the mapping for that association, but only for that query.

DQL またはネイティブ クエリでアソシエーションに参加することは、本質的に、そのクエリでそのアソシエーションを熱心に読み込むことを意味します。

33.5.3. Generating Proxy classes

In a production environment, it is highly recommended to use AUTOGENERATE_NEVER to allow for optimal performances. However you will be required to generate the proxies manually using the Doctrine Console:

実稼働環境では、最適なパフォーマンスを可能にするために AUTOGENERATE_NEVER を使用することを強くお勧めします。ただし、Doctrine コンソールを使用してプロキシを手動で生成する必要があります。

$ ./doctrine orm:generate-proxies

The other options are interesting in development environment:

その他のオプションは、開発環境で興味深いものです。

  • AUTOGENERATE_ALWAYS will require you to create and configure a proxy directory. Proxies will be generated and written to file on each request, so any modification to your code will be acknowledged.

    AUTOGENERATE_ALWAYS では、プロキシ ディレクトリを作成して構成する必要があります。プロキシはリクエストごとに生成されてファイルに書き込まれるため、コードの変更はすべて承認されます。

  • AUTOGENERATE_FILE_NOT_EXISTS will not overwrite an existing proxy file. If your code changes, you will need to regenerate the proxies manually.

    AUTOGENERATE_FILE_NOT_EXISTS は、既存のプロキシ ファイルを上書きしません。コードが変更された場合は、プロキシを手動で再生成する必要があります。

  • AUTOGENERATE_EVAL will regenerate each proxy on each request, but without writing them to disk.

    AUTOGENERATE_EVAL は、要求ごとに各プロキシを再生成しますが、それらをディスクに書き込むことはありません。

33.6. Autoloading Proxies

When you deserialize proxy objects from the session or any other storage it is necessary to have an autoloading mechanism in place for these classes. For implementation reasons Proxy class names are not PSR-0 compliant. This means that you have to register a special autoloader for these classes:

セッションまたはその他のストレージからプロキシ オブジェクトをデシリアライズするときは、これらのクラスにオートロード メカニズムを配置する必要があります。実装上の理由から、プロキシ クラス名は PSR-0 に準拠していません。これは、これらのクラス用に特別なオートローダーを登録する必要があることを意味します:

<?php
use Doctrine\Common\Proxy\Autoloader;

$proxyDir = "/path/to/proxies";
$proxyNamespace = "MyProxies";

Autoloader::register($proxyDir, $proxyNamespace);

If you want to execute additional logic to intercept the proxy file not found state you can pass a closure as the third argument. It will be called with the arguments proxydir, namespace and className when the proxy file could not be found.

追加のロジックを実行してプロキシ ファイルの not foundstate をインターセプトする場合は、3 番目の引数としてクロージャを渡すことができます。プロキシ ファイルが見つからない場合、引数 proxydir、namespace、および className で呼び出されます。

33.7. Multiple Metadata Sources

When using different components using Doctrine ORM you may end up with them using two different metadata drivers, for example XML and YAML. You can use the MappingDriverChain Metadata implementations to aggregate these drivers based on namespaces:

Doctrine ORM を使用して異なるコンポーネントを使用する場合、XML と YAML などの 2 つの異なるメタデータ ドライバーを使用することになります。 MappingDriverChain メタデータの実装を使用して、名前空間に基づいてこれらのドライバーを集約できます。

<?php
use Doctrine\Persistence\Mapping\Driver\MappingDriverChain;

$chain = new MappingDriverChain();
$chain->addDriver($xmlDriver, 'Doctrine\Tests\Models\Company');
$chain->addDriver($yamlDriver, 'Doctrine\Tests\ORM\Mapping');

Based on the namespace of the entity the loading of entities is delegated to the appropriate driver. The chain semantics come from the fact that the driver loops through all namespaces and matches the entity class name against the namespace using a strpos() === 0 call. This means you need to order the drivers correctly if sub-namespaces use different metadata driver implementations.

エンティティの名前空間に基づいて、エンティティのロードは適切なドライバーに委譲されます。チェーン セマンティクスは、ドライバーがすべての名前空間をループし、astrpos() === 0 呼び出しを使用して名前空間に対してエンティティ クラス名を照合するという事実に由来します。これは、サブ名前空間が異なるメタデータ ドライバーの実装を使用する場合、ドライバーを正しく注文する必要があることを意味します。

33.8. Default Repository (*OPTIONAL*)

Specifies the FQCN of a subclass of the EntityRepository. That will be available for all entities without a custom repository class.

EntityRepository のサブクラスの FQCN を指定します。これは、カスタム リポジトリ クラスを持たないすべてのエンティティで使用できます。

<?php
$config->setDefaultRepositoryClassName($fqcn);
$config->getDefaultRepositoryClassName();

The default value is Doctrine\ORM\EntityRepository. Any repository class must be a subclass of EntityRepository otherwise you got an ORMException

デフォルト値は Doctrine\ORM\EntityRepository です。どのリポジトリ クラスも EntityRepository のサブクラスである必要があります。それ以外の場合は、ORMException が発生します。

33.9. Ignoring entities (*OPTIONAL*)

Specifies the Entity FQCNs to ignore. SchemaTool will then skip these (e.g. when comparing schemas).

無視するエンティティ FQCN を指定します。SchemaTool はこれらをスキップします (スキーマを比較する場合など)。

<?php
$config->setSchemaIgnoreClasses([$fqcn]);
$config->getSchemaIgnoreClasses();

33.10. Setting up the Console

Doctrine uses the Symfony Console component for generating the command line interface. You can take a look at the tools chapter for inspiration how to setup the cli.

Doctrine は Symfony Console コンポーネントを使用してコマンドライン インターフェイスを生成します。 CLI のセットアップ方法については、ツールの章を参照してください。

Table Of Contents

Previous topic

32. Implementing a NamingStrategy

32. NamingStrategy の実装

Next topic

34. The Second Level Cache

34. セカンドレベルキャッシュ

This Page

Fork me on GitHub