Getting Started with Doctrine

This guide covers getting started with the Doctrine ORM. After working through the guide you should know:

このガイドでは、Doctrine ORM の使用を開始する方法について説明します。ガイドを読み終えたら、次のことを知っておく必要があります。

  • How to install and configure Doctrine by connecting it to a database

    Doctrine をデータベースに接続してインストールおよび設定する方法

  • Mapping PHP objects to database tables

    PHP オブジェクトをデータベース テーブルにマッピングする

  • Generating a database schema from PHP objects

    PHP オブジェクトからデータベース スキーマを生成する

  • Using the EntityManager to insert, update, delete and find objects in the database.

    EntityManager を使用して、データベース内のオブジェクトを挿入、更新、削除、および検索します。

Guide Assumptions

This guide is designed for beginners that haven’t worked with Doctrine ORM before. There are some prerequisites for the tutorial that have to be installed:

このガイドは、Doctrine ORM を使用したことがない初心者向けに設計されています。インストールする必要があるチュートリアルの前提条件がいくつかあります。

  • PHP (latest stable version)

    PHP (最新の安定版)

  • Composer Package Manager (Install Composer)

    Composer パッケージ マネージャー (Composer のインストール)

The code of this tutorial is available on Github.

このチュートリアルのコードは、Github で入手できます。

What is Doctrine?

Doctrine ORM is an object-relational mapper (ORM) for PHP 7.1+ that provides transparent persistence for PHP objects. It uses the Data Mapper pattern at the heart, aiming for a complete separation of your domain/business logic from the persistence in a relational database management system.

Doctrine ORM は、PHP オブジェクトの透過的な永続性を提供する PHP 7.1+ 用のオブジェクト リレーショナル マッパー (ORM) です。リレーショナル データベース管理システムの永続性からドメイン/ビジネス ロジックを完全に分離することを目的として、中心に Data Mapperpattern を使用します。

The benefit of Doctrine for the programmer is the ability to focus on the object-oriented business logic and worry about persistence only as a secondary problem. This doesn’t mean persistence is downplayed by Doctrine 2, however it is our belief that there are considerable benefits for object-oriented programming if persistence and entities are kept separated.

プログラマーにとっての Doctrine の利点は、オブジェクト指向のビジネス ロジックに集中し、持続性を二次的な問題としてのみ心配できることです。これは、Doctrine2 が永続性を軽視しているという意味ではありませんが、永続性とエンティティを分離しておくと、オブジェクト指向プログラミングに大きなメリットがあると私たちは信じています。

What are Entities?

Entities are PHP Objects that can be identified over many requests by a unique identifier or primary key. These classes don’t need to extend any abstract base class or interface.

エンティティは、一意の識別子または主キーによって多くのリクエストで識別できる PHP オブジェクトです。これらのクラスは、抽象基本クラスまたはインターフェイスを拡張する必要はありません。

An entity contains persistable properties. A persistable property is an instance variable of the entity that is saved into and retrieved from the database by Doctrine’s data mapping capabilities.

エンティティには永続化可能なプロパティが含まれています。持続可能プロパティは、Doctrine のデータ マッピング機能によってデータベースに保存され、データベースから取得されるエンティティのインスタンス変数です。

An entity class must not be final nor read-only, although it can contain final methods or read-only properties.

エンティティ クラスは、final メソッドまたは読み取り専用プロパティを含むことができますが、final または読み取り専用であってはなりません。

An Example Model: Bug Tracker

For this Getting Started Guide for Doctrine we will implement the Bug Tracker domain model from the Zend_Db_Table documentation. Reading their documentation we can extract the requirements:

この Doctrine の入門ガイドでは、Zend_Db_Table ドキュメントから Bug Tracker ドメイン モデルを実装します。ドキュメントを読むと、要件を抽出できます。

  • A Bug has a description, creation date, status, reporter and engineer

    バグには、説明、作成日、ステータス、レポーター、およびエンジニアがあります。

  • A Bug can occur on different Products (platforms)

    異なる製品 (プラットフォーム) でバグが発生する可能性があります

  • A Product has a name.

    製品には名前があります。

  • Bug reporters and engineers are both Users of the system.

    バグ報告者とエンジニアはどちらもシステムのユーザーです。

  • A User can create new Bugs.

    ユーザーは新しいバグを作成できます。

  • The assigned engineer can close a Bug.

    割り当てられたエンジニアはバグをクローズできます。

  • A User can see all their reported or assigned Bugs.

    ユーザーは、報告または割り当てられたすべてのバグを表示できます。

  • Bugs can be paginated through a list-view.

    バグは、リスト ビューを介してページ付けできます。

Project Setup

Create a new empty folder for this tutorial project, for example doctrine2-tutorial and create a new file composer.json inside that directory with the following contents:

このチュートリアル プロジェクト用に新しい空のフォルダー (doctrine2-tutorial など) を作成し、そのディレクトリ内に新しいファイル composer.json を次の内容で作成します。

{
    "require": {
        "doctrine/orm": "^2.11.0",
        "doctrine/dbal": "^3.2",
        "symfony/yaml": "^5.4",
        "symfony/cache": "^5.4"
    },
    "autoload": {
        "psr-0": {"": "src/"}
    }
}

Install Doctrine using the Composer Dependency Management tool, by calling:

以下を呼び出して、Composer 依存関係管理ツールを使用して Doctrine をインストールします。

$ composer install

This will install the packages Doctrine Common, Doctrine DBAL, Doctrine ORM, into the vendor directory.

これにより、パッケージ Doctrine Common、Doctrine DBAL、Doctrine ORM が vendor ディレクトリにインストールされます。

Add the following directories:

次のディレクトリを追加します。

doctrine2-tutorial
|-- config
|   `-- xml
|   `-- yaml
`-- src

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

Note

ノート

It is strongly recommended that you require doctrine/dbal in your composer.json as well, because using the ORM means mapping objects and their fields to database tables and their columns, and that requires mentioning so-called types that are defined in doctrine/dbal in your application. Having an explicit requirement means you control when the upgrade to the next major version happens, so that you can do the necessary changes in your application beforehand.

ORM を使用することは、オブジェクトとそのフィールドをデータベース テーブルとその列にマッピングすることを意味し、アプリケーションの doctrine/dbal で定義されているいわゆるタイプについて言及する必要があるため、yourcomposer.json にも doctrine/dbal を要求することを強くお勧めします。明示的な要件があるということは、次のメジャー バージョンへのアップグレードがいつ行われるかを制御できることを意味し、事前にアプリケーションで必要な変更を行うことができます。

Obtaining the EntityManager

Doctrine’s public interface is through the EntityManager. This class provides access points to the complete lifecycle management for your entities, and transforms entities from and back to persistence. You have to configure and create it to use your entities with Doctrine ORM. I will show the configuration steps and then discuss them step by step:

Doctrine のパブリック インターフェイスは EntityManager を介して行われます。このクラスは、エンティティの完全なライフサイクル管理へのアクセス ポイントを提供し、エンティティを永続化から永続化に変換します。 Doctrine ORM でエンティティを使用するには、構成して作成する必要があります。構成手順を示してから、順を追って説明します。

<?php
// bootstrap.php
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMSetup;

require_once "vendor/autoload.php";

// Create a simple "default" Doctrine ORM configuration for Attributes
$config = ORMSetup::createAttributeMetadataConfiguration(
    paths: array(__DIR__."/src"),
    isDevMode: true,
);
// or if you prefer annotation, YAML or XML
// $config = ORMSetup::createAnnotationMetadataConfiguration(
//    paths: array(__DIR__."/src"),
//    isDevMode: true,
// );
// $config = ORMSetup::createXMLMetadataConfiguration(
//    paths: array(__DIR__."/config/xml"),
//    isDevMode: true,
//);
// $config = ORMSetup::createYAMLMetadataConfiguration(
//    paths: array(__DIR__."/config/yaml"),
//    isDevMode: true,
// );

// configuring the database connection
$connection = DriverManager::getConnection([
    'driver' => 'pdo_sqlite',
    'path' => __DIR__ . '/db.sqlite',
], $config)

// obtaining the entity manager
$entityManager = new EntityManager($connection, $config);

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

The require_once statement sets up the class autoloading for Doctrine and its dependencies using Composer’s autoloader.

require_once ステートメントは、Composer のオートローダーを使用して、Doctrine とその依存関係のクラスのオートローディングを設定します。

The second block consists of the instantiation of the ORM Configuration object using the ORMSetup helper. It assumes a bunch of defaults that you don’t have to bother about for now. You can read up on the configuration details in the reference chapter on configuration.

2 番目のブロックは、ORMSetup ヘルパーを使用した ORMConfiguration オブジェクトのインスタンス化で構成されます。今のところ気にする必要のない一連のデフォルトを想定しています。構成の詳細については、構成に関するリファレンスの章を参照してください。

The third block shows the configuration options required to connect to a database. In this case, we’ll use a file-based SQLite database. All the configuration options for all the shipped drivers are given in the DBAL Configuration section of the manual.

3 番目のブロックは、データベースへの接続に必要な構成オプションを示しています。この場合、ファイルベースの SQLite データベースを使用します。出荷されたすべてのドライバーのすべての構成オプションは、マニュアルの DBAL 構成セクションに記載されています。

The last block shows how the EntityManager is obtained from a factory method.

最後のブロックは、ファクトリ メソッドから EntityManager を取得する方法を示しています。

Generating the Database Schema

Doctrine has a command-line interface that allows you to access the SchemaTool, a component that can generate a relational database schema based entirely on the defined entity classes and their metadata. For this tool to work, you need to create an executable console script as described in the tools chapter.

Doctrine には、定義されたエンティティ クラスとそのメタデータに完全に基づいてリレーショナル データベース スキーマを生成できるコンポーネントである SchemaTool にアクセスできるコマンドライン インターフェイスがあります。このツールを機能させるには、ツールの章で説明されているように、実行可能なコンソール スクリプトを作成する必要があります。

If you created the bootstrap.php file as described in the previous section, that script could look like this:

前のセクションで説明したように bootstrap.php ファイルを作成した場合、そのスクリプトは次のようになります。

#!/usr/bin/env php
<?php
// bin/doctrine

use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Doctrine\ORM\Tools\Console\EntityManagerProvider\SingleManagerProvider;

// Adjust this path to your actual bootstrap.php
require __DIR__ . 'path/to/your/bootstrap.php';

ConsoleRunner::run(
    new SingleManagerProvider($entityManager)
);

In the following examples, we will assume that this script has been created as bin/doctrine.

以下の例では、このスクリプトが asbin/doctrine として作成されていると想定しています。

$ php bin/doctrine orm:schema-tool:create

Since we haven’t added any entity metadata in src yet, you’ll see a message stating “No Metadata Classes to process.” In the next section, we’ll create a Product entity along with the corresponding metadata, and run this command again.

まだ src にエンティティ メタデータを追加していないため、「処理するメタデータ クラスがありません」というメッセージが表示されます。次のセクションでは、対応するメタデータとともに aProduct エンティティを作成し、このコマンドを再度実行します。

Note that as you modify your entities’ metadata during the development process, you’ll need to update your database schema to stay in sync with the metadata. You can easily recreate the database using the following commands:

開発プロセス中にエンティティのメタデータを変更する場合、データベース スキーマを更新してメタデータとの同期を維持する必要があることに注意してください。次のコマンドを使用して、データベースを簡単に再作成できます。

$ php bin/doctrine orm:schema-tool:drop --force
$ php bin/doctrine orm:schema-tool:create

Or you can use the update functionality:

または、更新機能を使用できます。

$ php bin/doctrine orm:schema-tool:update --force

The updating of databases uses a diff algorithm for a given database schema. This is a cornerstone of the Doctrine\DBAL package, which can even be used without the Doctrine ORM package.

データベースの更新では、特定のデータベース スキーマの差分アルゴリズムが使用されます。これは Doctrine\DBAL パッケージの基礎であり、Doctrine ORM パッケージがなくても使用できます。

Starting with the Product Entity

We start with the simplest entity, the Product. Create a src/Product.php file to contain the Product entity definition:

最も単純なエンティティである製品から始めます。 Productentity 定義を含む src/Product.php ファイルを作成します。

<?php
// src/Product.php
class Product
{
    private int|null $id = null;
    private string $name;
}

When creating entity classes, all of the fields should be private.

エンティティ クラスを作成するときは、すべてのフィールドを非公開にする必要があります。

Use protected when strictly needed and very rarely if not ever public.

厳密に必要な場合は protected を使用し、公開されていない場合はごくまれに使用します。

Adding behavior to Entities

There are two options to define methods in entities: getters/setters, or mutators and DTOs, respectively for anemic entities or rich entities.

エンティティでメソッドを定義するための 2 つのオプションがあります: getter/setter、または mutators と DTO で、それぞれ貧血エンティティまたは豊富なエンティティに対応します。

Anemic entities: Getters and setters

貧血エンティティ: ゲッターとセッター

The most popular method is to create two kinds of methods to read (getter) and update (setter) the object’s properties.

最も一般的な方法は、オブジェクトのプロパティを読み取り (getter) および更新 (setter) する 2 種類のメソッドを作成することです。

The id field has no setter since, generally speaking, your code should not set this value since it represents a database id value. (Note that Doctrine itself can still set the value using the Reflection API instead of a defined setter function.)

id フィールドには setter がありません。一般的に言えば、この値はデータベースの id 値を表しているため、コードでこの値を設定してはならないからです。

Note

ノート

Doctrine ORM does not use any of the methods you defined: it uses reflection to read and write values to your objects, and will never call methods, not even __construct.

Doctrine ORM はあなたが定義したメソッドを一切使用しません: オブジェクトの値を読み書きするためにリフレクションを使用し、__construct でさえメソッドを呼び出すことはありません。

This approach is mostly used when you want to focus on behavior-less entities, and when you want to have all your business logic in your services rather than in the objects themselves.

このアプローチは、ほとんどの場合、動作の少ないエンティティに焦点を当てたい場合、およびすべてのビジネス ロジックをオブジェクト自体ではなくサービスに含めたい場合に使用されます。

Getters and setters are a common convention which makes it possible to expose each field of your entity to the external world, while allowing you to keep some type safety in place.

ゲッターとセッターは、エンティティの各フィールドを外部の世界に公開することを可能にすると同時に、型の安全性を維持することを可能にする一般的な規則です。

Such an approach is a good choice for RAD (rapid application development), but may lead to problems later down the road, because providing such an easy way to modify any field in your entity means that the entity itself cannot guarantee validity of its internal state. Having any object in invalid state is dangerous:

このようなアプローチは RAD (迅速なアプリケーション開発) には適していますが、後で問題が発生する可能性があります。これは、エンティティ内の任意のフィールドを変更する簡単な方法を提供すると、エンティティ自体が内部状態の有効性を保証できないためです。無効な状態のオブジェクトを持つことは危険です:

  • An invalid state can bring bugs in your business logic.

    無効な状態は、ビジネス ロジックにバグをもたらす可能性があります。

  • The state can be implicitly saved in the database: any forgotten flush can persist the broken state.

    状態はデータベースに暗黙的に保存できます。忘れたフラッシュは壊れた状態を保持できます。

  • If persisted, the corrupted data will be retrieved later in your application when the data is loaded again, thereby leading to bugs in your business logic.

    永続化された場合、破損したデータは後でデータが再度読み込まれたときにアプリケーションで取得されるため、ビジネス ロジックにバグが発生します。

  • When bugs occur after corrupted data is persisted, troubleshooting will become much harder, and you might be aware of the bug too late to fix it in a proper manner.

    破損したデータが残った後にバグが発生すると、トラブルシューティングが非常に困難になり、適切な方法で修正するには遅すぎるバグに気付く可能性があります。

implicitly saved in database, thereby leading to corrupted or inconsistent data in your storage, and later in your application when the data is loaded again.

暗黙的にデータベースに保存されるため、ストレージ内のデータが破損したり矛盾したりし、後でデータが再びロードされるときにアプリケーションで発生します。

Note

ノート

This method, although very common, is inappropriate for Domain Driven Design (DDD <https://en.wikipedia.org/wiki/Domain-driven_design>) where methods should represent real business operations and not simple property change, And business invariants should be maintained both in the application state (entities in this case) and in the database, with no space for data corruption.

この方法は、非常に一般的ですが、ドメイン駆動設計 (DDD) には適していません。メソッドは、単純なプロパティの変更ではなく、実際のビジネス オペレーションを表す必要があります。また、アプリケーションの状態 (この場合はエンティティ) とデータベースの両方で、スペースなしでビジネスの不変条件を維持する必要があります。データ破損のため。

Here is an example of a simple anemic entity:

単純な貧血エンティティの例を次に示します。

In the example above, we avoid all possible logic in the entity and only care about putting and retrieving data into it without validation (except the one provided by type-hints) nor consideration about the object’s state.

上記の例では、エンティティ内で考えられるすべてのロジックを回避し、検証 (型ヒントによって提供されるものを除く) もオブジェクトの状態についての考慮もなしに、エンティティにデータを入れたり取得したりすることにのみ注意を払います。

As Doctrine ORM is a persistence tool for your domain, the state of an object is really important. This is why we strongly recommend using rich entities.

Doctrine ORM はドメインの永続化ツールであるため、オブジェクトの状態は非常に重要です。これが、リッチ エンティティの使用を強くお勧めする理由です。

Rich entities: Mutators and DTOs

豊富なエンティティ: ミューテーターと DTO

We recommend using a rich entity design and rely on more complex mutators, and if needed based on DTOs. In this design, you should not use getters nor setters, and instead, implement methods that represent the behavior of your domain.

リッチ エンティティ デザインを使用し、より複雑なミューテーターに依存することをお勧めします。また、必要に応じて DTO に基づくこともお勧めします。このデザインでは、ゲッターやセッターを使用せず、代わりにドメインの動作を表すメソッドを実装します。

For example, when having a User entity, we could foresee the following kind of optimization.

たとえば、User エンティティがある場合、次の種類の最適化を予測できます。

Example of a rich entity with proper accessors and mutators:

適切なアクセサーとミューテーターを備えたリッチ エンティティの例:

Note

ノート

Please note that this example is only a stub. When going further in the documentation, we will update this object with more behavior and maybe update some methods.

この例は単なるスタブであることに注意してください。ドキュメントをさらに進めると、このオブジェクトの動作が更新され、いくつかのメソッドが更新される可能性があります。

The entities should only mutate state after checking that all business logic invariants are being respected. Additionally, our entities should never see their state change without validation. For example, creating a new Product() object without any data makes it an invalid object. Rich entities should represent behavior, not data, therefore they should be valid even after a __construct() call.

エンティティは、すべてのビジネス ロジックの不変条件が尊重されていることを確認した後にのみ状態を変更する必要があります。たとえば、データなしで新しい Product() オブジェクトを作成すると、無効なオブジェクトになります。リッチ エンティティは、データではなく動作を表す必要があるため、__construct() 呼び出しの後でも有効である必要があります。

To help creating such objects, we can rely on DTOs, and/or make our entities always up-to-date. This can be performed with static constructors, or rich mutators that accept DTOs as parameters.

このようなオブジェクトの作成を支援するために、DTO を利用したり、エンティティを常に最新の状態にしたりできます。これは、静的コンストラクター、または DTO をパラメーターとして受け入れる豊富なミューテーターで実行できます。

The role of the DTO is to maintain the entity’s state and to help us rely upon objects that correctly represent the data that is used to mutate the entity.

DTO の役割は、エンティティの状態を維持し、エンティティの変更に使用されるデータを正しく表すオブジェクトに依存できるようにすることです。

Note

ノート

A DTO <https://en.wikipedia.org/wiki/Data_transfer_object> is an object that only carries data without any logic. Its only goal is to be transferred from one service to another. A DTO often represents data sent by a client and that has to be validated, but can also be used as simple data carrier for other cases.

DTO は、ロジックなしでデータを運ぶだけのオブジェクトです。その唯一の目的は、あるサービスから別のサービスに転送されることです。DTO は、多くの場合、クライアントによって送信され、検証が必要なデータを表しますが、他の場合の単純なデータ キャリアとしても使用できます。

By using DTOs, if we take our previous User example, we could create a ProfileEditingForm DTO that will be a plain model, totally unrelated to our database, that will be populated via a form and validated. Then we can add a new mutator to our User:

DTO を使用することで、前の User の例を取り上げると、フォームを介して入力され、検証されるデータベースとはまったく関係のない単純なモデルになる ProfileEditingForm DTO を作成できます。次に、新しいミューテーターを User に追加できます。

There are several advantages to using such a model:

このようなモデルを使用することには、いくつかの利点があります。

  • Entity state is always valid. Since no setters exist, this means that we

    エンティティの状態は常に有効です。セッターが存在しないため、これは次のことを意味します。

only update portions of the entity that should already be valid.

すでに有効であるはずのエンティティの部分のみを更新します。

  • Instead of having plain getters and setters, our entity now has

    プレーンなゲッターとセッターの代わりに、私たちのエンティティは

real behavior: it is much easier to determine the logic in the domain.

実際の動作: ドメイン内のロジックを決定する方がはるかに簡単です。

  • DTOs can be reused in other components, for example deserializing mixed

    DTO は他のコンポーネントで再利用できます。

content, using forms…

コンテンツ、フォームの使用…

  • Classic and static constructors can be used to manage different ways to

    クラシック コンストラクターと静的コンストラクターを使用して、さまざまな方法を管理できます。

create our objects, and they can also use DTOs.

オブジェクトを作成し、DTO を使用することもできます。

  • Anemic entities tend to isolate the entity from logic, whereas rich

    貧弱なエンティティは、エンティティをロジックから分離する傾向がありますが、リッチなエンティティは

entities allow putting the logic in the object itself, including data validation.

エンティティを使用すると、データ検証を含むロジックをオブジェクト自体に配置できます。

The next step for persistence with Doctrine is to describe the structure of the Product entity to Doctrine using a metadata language. The metadata language describes how entities, their properties and references should be persisted and what constraints should be applied to them.

Doctrine で永続化するための次のステップは、メタデータ言語を使用して Doctrine に Product エンティティの構造を記述することです。メタデータ言語は、エンティティ、そのプロパティ、および参照を永続化する方法と、それらに適用する必要がある制約を記述します。

Metadata for an Entity can be configured using attributes directly in the Entity class itself, or in an external XML or YAML file. This Getting Started guide will demonstrate metadata mappings using all three methods, but you only need to choose one.

エンティティのメタデータは、エンティティ クラス自体、または外部の XML または YAML ファイルで属性を直接使用して構成できます。この入門ガイドでは、3 つの方法すべてを使用したメタデータ マッピングについて説明しますが、選択する必要があるのは 1 つだけです。

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

# config/yaml/Product.dcm.yml
Product:
  type: entity
  table: products
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string

The top-level entity definition specifies information about the class and table name. The primitive type Product#name is defined as a field attribute. The id property is defined with the id tag. It has a generator tag nested inside, which specifies that the primary key generation mechanism should automatically use the database platform’s native id generation strategy (for example, AUTO INCREMENT in the case of MySql, or Sequences in the case of PostgreSql and Oracle).

トップレベルのエンティティ定義は、クラスとテーブル名に関する情報を指定します。プリミティブ型 Product#name は、フィールド属性として定義されています。 id プロパティは id タグで定義されます。内部にはジェネレーター タグがネストされており、主キー生成メカニズムがデータベース プラットフォームのネイティブ ID 生成戦略 (たとえば、MySql の場合は AUTO INCREMENT、PostgreSql の場合は Sequences) を自動的に使用する必要があることを指定します。およびオラクル)。

Now that we have defined our first entity and its metadata, let’s update the database schema:

最初のエンティティとそのメタデータを定義したので、データベース スキーマを更新しましょう。

$ php bin/doctrine orm:schema-tool:update --force --dump-sql

Specifying both flags --force and --dump-sql will cause the DDL statements to be executed and then printed to the screen.

--force と --dump-sql の両方のフラグを指定すると、DDL ステートメントが実行され、画面に出力されます。

Now, we’ll create a new script to insert products into the database:

次に、製品をデータベースに挿入する新しいスクリプトを作成します。

<?php
// create_product.php <name>
require_once "bootstrap.php";

$newProductName = $argv[1];

$product = new Product();
$product->setName($newProductName);

$entityManager->persist($product);
$entityManager->flush();

echo "Created Product with ID " . $product->getId() . "\n";

Call this script from the command-line to see how new products are created:

コマンドラインからこのスクリプトを呼び出して、新しい製品がどのように作成されるかを確認します。

$ php create_product.php ORM
$ php create_product.php DBAL

What is happening here? Using the Product class is pretty standard OOP. The interesting bits are the use of the EntityManager service. To notify the EntityManager that a new entity should be inserted into the database, you have to call persist(). To initiate a transaction to actually perform the insertion, you have to explicitly call flush() on the EntityManager.

ここで何が起きてるの? Product クラスの使用はかなり標準的な OOP です。興味深い点は、EntityManager サービスの使用です。新しいエンティティをデータベースに挿入する必要があることを EntityManager に通知するには、persist() を呼び出す必要があります。実際に挿入を実行するトランザクションを開始するには、EntityManager で明示的に flush() を呼び出す必要があります。

This distinction between persist and flush is what allows the aggregation of all database writes (INSERT, UPDATE, DELETE) into one single transaction, which is executed when flush() is called. Using this approach, the write-performance is significantly better than in a scenario in which writes are performed on each entity in isolation.

この持続とフラッシュの違いにより、すべてのデータベース書き込み (INSERT、UPDATE、DELETE) を 1 つのトランザクションに集約できます。これは、flush() が呼び出されたときに実行されます。このアプローチを使用すると、書き込みパフォーマンスは、書き込みが各エンティティで分離して実行されるシナリオよりも大幅に向上します。

Next, we’ll fetch a list of all the Products in the database. Let’s create a new script for this:

次に、データベース内のすべての製品のリストを取得します。このための新しいスクリプトを作成しましょう。

<?php
// list_products.php
require_once "bootstrap.php";

$productRepository = $entityManager->getRepository('Product');
$products = $productRepository->findAll();

foreach ($products as $product) {
    echo sprintf("-%s\n", $product->getName());
}

The EntityManager#getRepository() method can create a finder object (called a repository) for every type of entity. It is provided by Doctrine and contains some finder methods like findAll().

EntityManager#getRepository() メソッドは、すべてのタイプのエンティティに対してファインダー オブジェクト (リポジトリと呼ばれる) を作成できます。これは Doctrine によって提供され、findAll() のようないくつかのファインダー メソッドを含んでいます。

Let’s continue by creating a script to display the name of a product based on its ID:

ID に基づいて製品の名前を表示するスクリプトを作成してみましょう。

<?php
// show_product.php <id>
require_once "bootstrap.php";

$id = $argv[1];
$product = $entityManager->find('Product', $id);

if ($product === null) {
    echo "No product found.\n";
    exit(1);
}

echo sprintf("-%s\n", $product->getName());

Next we’ll update a product’s name, given its id. This simple example will help demonstrate Doctrine’s implementation of the UnitOfWork pattern. Doctrine keeps track of all the entities that were retrieved from the Entity Manager, and can detect when any of those entities’ properties have been modified. As a result, rather than needing to call persist($entity) for each individual entity whose properties were changed, a single call to flush() at the end of a request is sufficient to update the database for all of the modified entities.

次に、ID を指定して製品の名前を更新します。この単純な例は、Doctrine の UnitOfWork パターンの実装を示すのに役立ちます。 Doctrine は Entity Manager から取得されたすべてのエンティティを追跡し、それらのエンティティのプロパティがいつ変更されたかを検出できます。その結果、プロパティが変更された個々のエンティティごとに persist($entity) を呼び出す必要はなく、変更されたすべてのエンティティのデータベースを更新するには、request の最後に flush() を 1 回呼び出すだけで十分です。

<?php
// update_product.php <id> <new-name>
require_once "bootstrap.php";

$id = $argv[1];
$newName = $argv[2];

$product = $entityManager->find('Product', $id);

if ($product === null) {
    echo "Product $id does not exist.\n";
    exit(1);
}

$product->setName($newName);

$entityManager->flush();

After calling this script on one of the existing products, you can verify the product name changed by calling the show_product.php script.

既存の製品の 1 つでこのスクリプトを呼び出した後、show_product.php スクリプトを呼び出して、変更された製品名を確認できます。

Adding Bug and User Entities

We continue with the bug tracker example by creating the Bug and User classes. We’ll store them in src/Bug.php and src/User.php, respectively.

Bug および Userclasses を作成して、バグ トラッカーの例を続けます。それぞれ src/Bug.php と src/User.php に保存します。

<?php
// src/Bug.php

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'bugs')]
class Bug
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    #[ORM\GeneratedValue]
    private int $id;

    #[ORM\Column(type: 'string')]
    private string $description;

    #[ORM\Column(type: 'datetime')]
    private DateTime $created;

    #[ORM\Column(type: 'string')]
    private string $status;

    public function getId(): int|null
    {
        return $this->id;
    }

    public function getDescription(): string
    {
        return $this->description;
    }

    public function setDescription(string $description): void
    {
        $this->description = $description;
    }

    public function setCreated(DateTime $created)
    {
        $this->created = $created;
    }

    public function getCreated(): DateTime
    {
        return $this->created;
    }

    public function setStatus($status): void
    {
        $this->status = $status;
    }

    public function getStatus():string
    {
        return $this->status;
    }
}
<?php
// src/User.php

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'users')]
class User
{
    /** @var int */
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int|null $id = null;

    /** @var string */
    #[ORM\Column(type: 'string')]
    private string $name;

    public function getId(): int|null
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

All of the properties we’ve seen so far are of simple types (integer, string, and datetime). But now, we’ll add properties that will store objects of specific entity types in order to model the relationships between different entities.

これまで見てきたすべてのプロパティは単純な型 (整数、文字列、日時) です。しかしここでは、異なるエンティティ間の関係をモデル化するために、特定のエンティティ タイプのオブジェクトを格納するプロパティを追加します。

At the database level, relationships between entities are represented by foreign keys. But with Doctrine, you’ll never have to (and never should) work with the foreign keys directly. You should only work with objects that represent foreign keys through their own identities.

データベース レベルでは、エンティティ間の関係は外部キーによって表されます。しかし、Doctrine を使用すると、外部キーを直接操作する必要はありません (また、操作する必要もありません)。独自の ID を通じて外部キーを表すオブジェクトのみを操作する必要があります。

For every foreign key you either have a Doctrine ManyToOne or OneToOne association. On the inverse sides of these foreign keys you can have OneToMany associations. Obviously you can have ManyToMany associations that connect two tables with each other through a join table with two foreign keys.

すべての外部キーに対して、Doctrine ManyToOne または OneToOneassociation があります。これらの外部キーの反対側では、OneToMany アソシエーションを持つことができます。明らかに、2 つの外部キーを持つ結合テーブルを介して 2 つのテーブルを相互に接続する多対多の関連付けを持つことができます。

Now that you know the basics about references in Doctrine, we can extend the domain model to match the requirements:

Doctrine での参照に関する基本を理解したので、ドメイン モデルを要件に合わせて拡張できます。

<?php
// src/Bug.php

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

class Bug
{
    // ... (previous code)

    /** @var Collection<int, Product> */
    private Collection $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }
}
<?php
// src/User.php
use Doctrine\Common\Collections\ArrayCollection;

class User
{
    // ... (previous code)

    /** @var Collection<int, Bug> */
    private Collection $reportedBugs;
    /** @var Collection<int, Bug> */
    private Collection $assignedBugs;

    public function __construct()
    {
        $this->reportedBugs = new ArrayCollection();
        $this->assignedBugs = new ArrayCollection();
    }
}

Note

ノート

Whenever an entity is created from the database, a Collection implementation of the type PersistentCollection will be injected into your entity instead of an ArrayCollection. This helps Doctrine ORM understand the changes that have happened to the collection that are noteworthy for persistence.

データベースからエンティティが作成されるたびに、タイプ PersistentCollection のコレクション実装が、ArrayCollection の代わりにエンティティに注入されます。これは Doctrine ORM がコレクションに起こった、持続性に関して注目に値する変更を理解するのに役立ちます。

Because we only work with collections for the references we must be careful to implement a bidirectional reference in the domain model. The concept of owning or inverse side of a relation is central to this notion and should always be kept in mind. The following assumptions are made about relations and have to be followed to be able to work with Doctrine ORM. These assumptions are not unique to Doctrine ORM but are best practices in handling database relations and Object-Relational Mapping.

参照用のコレクションのみを使用するため、ドメイン モデルで双方向参照を実装するように注意する必要があります。関係の所有側または逆側の概念は、この概念の中心であり、常に心に留めておく必要があります。以下の仮定はリレーションについて作られ、Doctrine ORM で作業できるようにするために従う必要があります。これらの仮定は Doctrine ORM に固有のものではありませんが、データベース関係とオブジェクト リレーショナル マッピングを処理する際のベスト プラクティスです。

  • In a one-to-one relation, the entity holding the foreign key of the related entity on its own database table is always the owning side of the relation.

    1 対 1 の関係では、関連するエンティティの外部キーを独自のデータベース テーブルに保持しているエンティティが、常に関係の所有側になります。

  • In a many-to-one relation, the Many-side is the owning side by default because it holds the foreign key. Accordingly, the One-side is the inverse side by default.

    多対 1 の関係では、多側が外部キーを保持するため、デフォルトで所有側になります。したがって、片側はデフォルトで反対側です。

  • In a many-to-one relation, the One-side can only be the owning side if the relation is implemented as a ManyToMany with a join table, and the One-side is restricted to allow only UNIQUE values per database constraint.

    多対 1 のリレーションでは、リレーションが結合テーブルを使用して ManyToMany として実装されている場合にのみ One-side を所有側にすることができ、One-side はデータベース制約ごとに UNIQUE 値のみを許可するように制限されています。

  • In a many-to-many relation, both sides can be the owning side of the relation. However, in a bi-directional many-to-many relation, only one side is allowed to be the owning side.

    多対多の関係では、両側が関係の所有側になることができます。ただし、双方向の多対多の関係では、一方の側だけが所有側になることができます。

  • Changes to Collections are saved or updated, when the entity on the owning side of the collection is saved or updated.

    コレクションの所有側のエンティティが保存または更新されると、コレクションへの変更が保存または更新されます。

  • Saving an Entity at the inverse side of a relation never triggers a persist operation to changes to the collection.

    リレーションの逆側でエンティティを保存しても、コレクションへの変更に対する永続化操作がトリガーされることはありません。

Note

ノート

Consistency of bi-directional references on the inverse side of a relation have to be managed in userland application code. Doctrine cannot magically update your collections to be consistent.

関係の逆側での双方向参照の一貫性は、ユーザーランド アプリケーション コードで管理する必要があります。 Doctrine は魔法のようにコレクションを更新して一貫性を保つことはできません。

In the case of Users and Bugs we have references back and forth to the assigned and reported bugs from a user, making this relation bi-directional. We have to change the code to ensure consistency of the bi-directional reference:

ユーザーとバグの場合、ユーザーから割り当てられ、報告されたバグへの参照が前後にあり、この関係は双方向になります。双方向参照の一貫性を確保するために、コードを変更する必要があります。

<?php
// src/Bug.php
class Bug
{
    // ... (previous code)

    private User $engineer;
    private User $reporter;

    public function setEngineer(User $engineer): void
    {
        $engineer->assignedToBug($this);
        $this->engineer = $engineer;
    }

    public function setReporter(User $reporter): void
    {
        $reporter->addReportedBug($this);
        $this->reporter = $reporter;
    }

    public function getEngineer(): User
    {
        return $this->engineer;
    }

    public function getReporter(): User
    {
        return $this->reporter;
    }
}
<?php
// src/User.php
class User
{
    // ... (previous code)

    /** @var Collection<int, Bug> */
    private Collection $reportedBugs;
    /** @var Collection<int, Bug> */
    private Collection $assignedBugs;

    public function addReportedBug(Bug $bug): void
    {
        $this->reportedBugs[] = $bug;
    }

    public function assignedToBug(Bug $bug): void
    {
        $this->assignedBugs[] = $bug;
    }
}

I chose to name the inverse methods in past-tense, which should indicate that the actual assigning has already taken place and the methods are only used for ensuring consistency of the references. This approach is my personal preference, you can choose whatever method to make this work.

過去形の逆メソッドに名前を付けることを選択しました。これは、実際の割り当てが既に行われており、メソッドが参照の一貫性を確保するためにのみ使用されていることを示す必要があります.このアプローチは私の個人的な好みです.

You can see from User#addReportedBug() and User#assignedToBug() that using this method in userland alone would not add the Bug to the collection of the owning side in Bug#reporter or Bug#engineer. Using these methods and calling Doctrine for persistence would not update the Collections’ representation in the database.

User#addReportedBug() と User#assignedToBug() から、このメソッドをユーザーランドで単独で使用しても、Bug#reporter または Bug#engineer の所有側のコレクションにバグが追加されないことがわかります。これらのメソッドを使用して Doctrine を呼び出して永続化しても、データベース内のコレクションの表現は更新されません。

Only using Bug#setEngineer() or Bug#setReporter() correctly saves the relation information.

Bug#setEngineer() または Bug#setReporter() を正しく使用した場合にのみ、関連情報が保存されます。

The Bug#reporter and Bug#engineer properties are Many-To-One relations, which point to a User. In a normalized relational model, the foreign key is saved on the Bug’s table, hence in our object-relation model the Bug is at the owning side of the relation. You should always make sure that the use-cases of your domain model should drive which side is an inverse or owning one in your Doctrine mapping. In our example, whenever a new bug is saved or an engineer is assigned to the bug, we don’t want to update the User to persist the reference, but the Bug. This is the case with the Bug being at the owning side of the relation.

Bug#reporter プロパティと Bug#engineer プロパティは多対 1 の関係であり、ユーザーを指します。正規化されたリレーショナル モデルでは、外部キーはバグのテーブルに保存されるため、オブジェクト リレーション モデルでは、バグはリレーションの所有側にあります。ドメイン モデルのユースケースが、Doctrine マッピングでどちらの側が逆であるか、所有する側であるかを常に確認する必要があります。この例では、新しいバグが保存されるか、エンジニアがバグに割り当てられるたびに、参照を永続化するためにユーザーを更新するのではなく、バグを更新します。これは、Bug がリレーションの所有側にある場合です。

Bugs reference Products by a uni-directional ManyToMany relation in the database that points from Bugs to Products.

バグは、バグから製品を指すデータベース内の一方向の多対多関係によって製品を参照します。

<?php
// src/Bug.php
class Bug
{
    // ... (previous code)

    /** @var Collection<int, Product> */
    private Collection $products;

    public function assignToProduct(Product $product): void
    {
        $this->products[] = $product;
    }

    /** @return Collection<int, Product> */
    public function getProducts(): Collection
    {
        return $this->products;
    }
}

We are now finished with the domain model given the requirements. Lets add metadata mappings for the Bug entity, as we did for the Product before:

これで、要件が与えられたドメイン モデルが完成しました。前に製品に対して行ったように、バグ エンティティのメタデータ マッピングを追加しましょう。

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

# config/yaml/Bug.dcm.yml
Bug:
  type: entity
  table: bugs
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    description:
      type: text
    created:
      type: datetime
    status:
      type: string
  manyToOne:
    reporter:
      targetEntity: User
      inversedBy: reportedBugs
    engineer:
      targetEntity: User
      inversedBy: assignedBugs
  manyToMany:
    products:
      targetEntity: Product

Here we have the entity, id and primitive type definitions. For the “created” field we have used the datetime type, which translates the YYYY-mm-dd HH:mm:ss database format into a PHP DateTime instance and back.

ここには、エンティティ、id、およびプリミティブ型の定義があります。「created」フィールドには、YYYY-mm-dd HH:mm:ss データベース形式を PHP の DateTime インスタンスに変換して戻す datetime 型を使用しました。

After the field definitions, the two qualified references to the user entity are defined. They are created by the many-to-one tag. The class name of the related entity has to be specified with the target-entity attribute, which is enough information for the database mapper to access the foreign-table. Since reporter and engineer are on the owning side of a bi-directional relation, we also have to specify the inversed-by attribute. They have to point to the field names on the inverse side of the relationship. We will see in the next example that the inversed-by attribute has a counterpart mapped-by which makes that the inverse side.

フィールド定義の後、ユーザー エンティティへの 2 つの限定参照が定義されます。それらは多対一タグによって作成されます。関連エンティティのクラス名は、target-entity 属性で指定する必要があります。これは、データベース マッパーが外部テーブルにアクセスするための十分な情報です。レポーターとエンジニアは双方向の関係の所有側にあるため、inversed-by 属性も指定する必要があります。リレーションシップの反対側にあるフィールド名を指す必要があります。次の例では、inversed-by 属性に対応する mapping-by があり、それが反対側になることがわかります。

The last definition is for the Bug#products collection. It holds all products where the specific bug occurs. Again you have to define the target-entity and field attributes on the many-to-many tag.

最後の定義は Bug#products コレクション用です。特定のバグが発生するすべての製品を保持します。ここでも、多対多タグでターゲット エンティティとフィールド属性を定義する必要があります。

Finally, we’ll add metadata mappings for the User entity.

最後に、User エンティティのメタデータ マッピングを追加します。

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

# config/yaml/User.dcm.yml
User:
  type: entity
  table: users
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string
  oneToMany:
    reportedBugs:
      targetEntity: Bug
      mappedBy: reporter
    assignedBugs:
      targetEntity: Bug
      mappedBy: engineer

Here are some new things to mention about the one-to-many tags. Remember that we discussed about the inverse and owning side. Now both reportedBugs and assignedBugs are inverse relations, which means the join details have already been defined on the owning side. Therefore we only have to specify the property on the Bug class that holds the owning sides.

ここでは、1 対多のタグについて言及すべきいくつかの新しい事項を示します。逆の側と所有する側について説明したことを思い出してください。これで、reportedBugs と assignedBugs は逆の関係になりました。これは、結合の詳細が所有側で既に定義されていることを意味します。したがって、所有側を保持する Bugclass のプロパティを指定するだけで済みます。

Update your database schema by running:

次を実行して、データベース スキーマを更新します。

$ php bin/doctrine orm:schema-tool:update --force

Implementing more Requirements

So far, we’ve seen the most basic features of the metadata definition language. To explore additional functionality, let’s first create new User entities:

これまで、メタデータ定義言語の最も基本的な機能を見てきました。追加機能を調べるために、最初に新しいユーザー エンティティを作成しましょう。

<?php
// create_user.php
require_once "bootstrap.php";

$newUsername = $argv[1];

$user = new User();
$user->setName($newUsername);

$entityManager->persist($user);
$entityManager->flush();

echo "Created User with ID " . $user->getId() . "\n";

Now call:

今すぐ呼び出します:

$ php create_user.php beberlei

We now have the necessary data to create a new Bug entity:

これで、新しいバグ エンティティを作成するために必要なデータが揃いました。

<?php
// create_bug.php <reporter-id> <engineer-id> <product-ids>
require_once "bootstrap.php";

$reporterId = $argv[1];
$engineerId = $argv[2];
$productIds = explode(",", $argv[3]);

$reporter = $entityManager->find("User", $reporterId);
$engineer = $entityManager->find("User", $engineerId);
if (!$reporter || !$engineer) {
    echo "No reporter and/or engineer found for the given id(s).\n";
    exit(1);
}

$bug = new Bug();
$bug->setDescription("Something does not work!");
$bug->setCreated(new DateTime("now"));
$bug->setStatus("OPEN");

foreach ($productIds as $productId) {
    $product = $entityManager->find("Product", $productId);
    $bug->assignToProduct($product);
}

$bug->setReporter($reporter);
$bug->setEngineer($engineer);

$entityManager->persist($bug);
$entityManager->flush();

echo "Your new Bug Id: ".$bug->getId()."\n";

Since we only have one user and product, probably with the ID of 1, we can call this script as follows:

おそらくIDが1のユーザーと製品が1つしかないため、このスクリプトを次のように呼び出すことができます。

php create_bug.php 1 1 1

See how simple it is to relate a Bug, Reporter, Engineer and Products? Also recall that thanks to the UnitOfWork pattern, Doctrine will detect these relations and update all of the modified entities in the database automatically when flush() is called.

Bug、Reporter、Engineer、および Products を関連付けるのがいかに簡単であるかをご覧ください。また、UnitOfWork パターンのおかげで、Doctrine はこれらの関係を検出し、flush() が呼び出されたときにデータベース内の変更されたすべてのエンティティを自動的に更新することを思い出してください。

Queries for Application Use-Cases

List of Bugs

Using the previous examples we can fill up the database quite a bit. However, we now need to discuss how to query the underlying mapper for the required view representations. When opening the application, bugs can be paginated through a list-view, which is the first read-only use-case:

前の例を使用すると、データベースをかなりいっぱいにすることができます。ただし、必要なビュー表現について基になるマッパーをクエリする方法について説明する必要があります。アプリケーションを開くと、最初の読み取り専用のユース ケースであるリスト ビューを介してバグをページ付けできます。

<?php
// list_bugs.php
require_once "bootstrap.php";

$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ORDER BY b.created DESC";

$query = $entityManager->createQuery($dql);
$query->setMaxResults(30);
$bugs = $query->getResult();

foreach ($bugs as $bug) {
    echo $bug->getDescription()." - ".$bug->getCreated()->format('d.m.Y')."\n";
    echo "    Reported by: ".$bug->getReporter()->getName()."\n";
    echo "    Assigned to: ".$bug->getEngineer()->getName()."\n";
    foreach ($bug->getProducts() as $product) {
        echo "    Platform: ".$product->getName()."\n";
    }
    echo "\n";
}

The DQL Query in this example fetches the 30 most recent bugs with their respective engineer and reporter in one single SQL statement. The console output of this script is then:

この例の DQL クエリは、最新の 30 件のバグをそれぞれのエンジニアとレポーターと共に 1 つの SQL ステートメントで取得します。このスクリプトのコンソール出力は次のようになります。

Something does not work! - 02.04.2010
    Reported by: beberlei
    Assigned to: beberlei
    Platform: My Product

Note

ノート

DQL is not SQL

DQL は SQL ではありません

You may wonder why we start writing SQL at the beginning of this use-case. Don’t we use an ORM to get rid of all the endless hand-writing of SQL? Doctrine introduces DQL which is best described as object-query-language and is a dialect of OQL and similar to HQL or JPQL. It does not know the concept of columns and tables, but only those of Entity-Class and property. Using the Metadata we defined before it allows for very short distinctive and powerful queries.

なぜこのユースケースの冒頭で SQL を書き始めるのか疑問に思われるかもしれません。 ORM を使用して、終わりのない SQL の手書きをすべて取り除きませんか? Doctrine は、オブジェクトクエリ言語として最もよく説明され、OQL の方言であり、HQL または JPQL に類似した DQL を導入します。これは、列とテーブルの概念を認識しませんが、エンティティクラスとプロパティの概念のみを認識します。以前に定義したメタデータを使用すると、非常に短く、特徴的で強力なクエリが可能になります。

An important reason why DQL is favourable to the Query API of most ORMs is its similarity to SQL. The DQL language allows query constructs that most ORMs don’t: GROUP BY even with HAVING, Sub-selects, Fetch-Joins of nested classes, mixed results with entities and scalar data such as COUNT() results and much more. Using DQL you should seldom come to the point where you want to throw your ORM into the dumpster, because it doesn’t support some the more powerful SQL concepts.

DQL がほとんどの ORM のクエリ API に適している重要な理由は、SQL との類似性です。 DQL 言語では、ほとんどの ORM では使用できないクエリ構造を使用できます: GROUP BY を使用しても、HAVING、サブ選択、ネストされたクラスの Fetch-Joins、エンティティとの混合結果、および COUNT() の結果などのスカラー データなどを使用できます。DQL を使用する必要はほとんどありませんORM はより強力な SQL の概念をサポートしていないため、ORM をごみ箱に捨てたいと思うところまで来てください。

If you need to build your query dynamically, you can use the QueryBuilder retrieved by calling $entityManager->createQueryBuilder(). There are more details about this in the relevant part of the documentation.

クエリを動的に作成する必要がある場合は、$entityManager->createQueryBuilder() を呼び出して取得した QueryBuilder を使用できます。これについては、ドキュメントの関連部分に詳細があります。

As a last resort you can still use Native SQL and a description of the result set to retrieve entities from the database. DQL boils down to a Native SQL statement and a ResultSetMapping instance itself. Using Native SQL you could even use stored procedures for data retrieval, or make use of advanced non-portable database queries like PostgreSql’s recursive queries.

最後の手段として、ネイティブ SQL と結果セットの記述を使用して、データベースからエンティティを取得できます。 DQL は、ネイティブ SQL ステートメントと ResultSetMapping インスタンス自体に要約されます。ネイティブ SQL を使用すると、ストアド プロシージャを使用してデータを取得したり、PostgreSql の再帰クエリのような高度な移植性のないデータベース クエリを使用したりすることもできます。

Array Hydration of the Bug List

In the previous use-case we retrieved the results as their respective object instances. We are not limited to retrieving objects only from Doctrine however. For a simple list view like the previous one we only need read access to our entities and can switch the hydration from objects to simple PHP arrays instead.

前の使用例では、結果をそれぞれのオブジェクト インスタンスとして取得しました。ただし、Doctrine からのみオブジェクトを取得することに限定されているわけではありません。前のような単純なリスト ビューの場合、エンティティへの読み取りアクセスのみが必要であり、ハイドレーションをオブジェクトから単純な PHP 配列に切り替えることができます。

Hydration can be an expensive process so only retrieving what you need can yield considerable performance benefits for read-only requests.

ハイドレーションは高価なプロセスになる可能性があるため、必要なものだけを取得することで、読み取り専用リクエストのパフォーマンスを大幅に向上させることができます。

Implementing the same list view as before using array hydration we can rewrite our code:

配列ハイドレーションを使用する前と同じリスト ビューを実装して、コードを書き直すことができます。

<?php
// list_bugs_array.php
require_once "bootstrap.php";

$dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
       "JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
$query = $entityManager->createQuery($dql);
$bugs = $query->getArrayResult();

foreach ($bugs as $bug) {
    echo $bug['description'] . " - " . $bug['created']->format('d.m.Y')."\n";
    echo "    Reported by: ".$bug['reporter']['name']."\n";
    echo "    Assigned to: ".$bug['engineer']['name']."\n";
    foreach ($bug['products'] as $product) {
        echo "    Platform: ".$product['name']."\n";
    }
    echo "\n";
}

There is one significant difference in the DQL query however, we have to add an additional fetch-join for the products connected to a bug. The resulting SQL query for this single select statement is pretty large, however still more efficient to retrieve compared to hydrating objects.

DQL クエリには大きな違いが 1 つありますが、バグに関連する製品にフェッチと結合を追加する必要があります。この 1 つの select ステートメントの結果の SQL クエリはかなり大きくなりますが、オブジェクトをハイドレートするよりも効率的に取得できます。

Find by Primary Key

The next Use-Case is displaying a Bug by primary key. This could be done using DQL as in the previous example with a where clause, however there is a convenience method on the EntityManager that handles loading by primary key, which we have already seen in the write scenarios:

次のユースケースは、主キーによるバグの表示です。これは、前の例のように where 句を使用して DQL を使用して実行できますが、書き込みシナリオで既に見たように、主キーによる読み込みを処理する EntityManager に便利なメソッドがあります。

<?php
// show_bug.php <id>
require_once "bootstrap.php";

$theBugId = $argv[1];

$bug = $entityManager->find("Bug", (int)$theBugId);

echo "Bug: ".$bug->getDescription()."\n";
echo "Engineer: ".$bug->getEngineer()->getName()."\n";

The output of the engineer’s name is fetched from the database! What is happening?

エンジニアの名前の出力は、データベースからフェッチされます!何が起こっている?

Since we only retrieved the bug by primary key both the engineer and reporter are not immediately loaded from the database but are replaced by LazyLoading proxies. These proxies will load behind the scenes, when attempting to access any of their un-initialized state.

主キーでバグを取得しただけなので、エンジニアとレポーターの両方がデータベースからすぐにロードされず、LazyLoading プロキシに置き換えられます。これらのプロキシは、初期化されていない状態にアクセスしようとすると、舞台裏で読み込まれます。

The call prints:

呼び出しは次のように表示されます。

$ php show_bug.php 1
Bug: Something does not work!
Engineer: beberlei

Warning

警告

Lazy loading additional data can be very convenient but the additional queries create an overhead. If you know that certain fields will always (or usually) be required by the query then you will get better performance by explicitly retrieving them all in the first query.

追加データの遅延ロードは非常に便利ですが、追加のクエリによってオーバーヘッドが生じます。特定のフィールドが常に (または通常) クエリで必要になることがわかっている場合は、最初のクエリですべてのフィールドを明示的に取得することで、パフォーマンスが向上します。

Dashboard of the User

For the next use-case we want to retrieve the dashboard view, a list of all open bugs the user reported or was assigned to. This will be achieved using DQL again, this time with some WHERE clauses and usage of bound parameters:

次のユース ケースでは、ダッシュボード ビュー、つまりユーザーが報告した、または割り当てられたすべての未解決のバグのリストを取得します。これは、再び DQL を使用して実現されます。今回は、いくつかの WHERE 句とバインドされたパラメーターの使用を使用します。

<?php
// dashboard.php <user-id>
require_once "bootstrap.php";

$theUserId = $argv[1];

$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ".
       "WHERE b.status = 'OPEN' AND (e.id = ?1 OR r.id = ?1) ORDER BY b.created DESC";

$myBugs = $entityManager->createQuery($dql)
                        ->setParameter(1, $theUserId)
                        ->setMaxResults(15)
                        ->getResult();

echo "You have created or assigned to " . count($myBugs) . " open bugs:\n\n";

foreach ($myBugs as $bug) {
    echo $bug->getId() . " - " . $bug->getDescription()."\n";
}

Number of Bugs

Until now we only retrieved entities or their array representation. Doctrine also supports the retrieval of non-entities through DQL. These values are called “scalar result values” and may even be aggregate values using COUNT, SUM, MIN, MAX or AVG functions.

これまで、エンティティまたはその配列表現のみを取得していました。Doctrine は、DQL を介した非エンティティの取得もサポートしています。これらの値は「スカラー結果値」と呼ばれ、COUNT、SUM、MIN、MAX、または AVG 関数を使用して値を集計することさえできます。

We will need this knowledge to retrieve the number of open bugs grouped by product:

製品ごとにグループ化された未解決のバグの数を取得するには、この知識が必要です。

<?php
// products.php
require_once "bootstrap.php";

$dql = "SELECT p.id, p.name, count(b.id) AS openBugs FROM Bug b ".
       "JOIN b.products p WHERE b.status = 'OPEN' GROUP BY p.id";
$productBugs = $entityManager->createQuery($dql)->getScalarResult();

foreach ($productBugs as $productBug) {
    echo $productBug['name']." has " . $productBug['openBugs'] . " open bugs!\n";
}

Updating Entities

There is a single use-case missing from the requirements, Engineers should be able to close a bug. This looks like:

要件に欠けているユースケースが 1 つあります。エンジニアはバグをクローズできる必要があります。これは次のようになります。

<?php
// src/Bug.php

class Bug
{
    public function close()
    {
        $this->status = "CLOSE";
    }
}
<?php
// close_bug.php <bug-id>
require_once "bootstrap.php";

$theBugId = $argv[1];

$bug = $entityManager->find("Bug", (int)$theBugId);
$bug->close();

$entityManager->flush();

When retrieving the Bug from the database it is inserted into the IdentityMap inside the UnitOfWork of Doctrine. This means your Bug with exactly this id can only exist once during the whole request no matter how often you call EntityManager#find(). It even detects entities that are hydrated using DQL and are already present in the Identity Map.

データベースからバグを取得すると、Doctrine の UnitOfWork 内の IdentityMap に挿入されます。これは、EntityManager#find() を呼び出す頻度に関係なく、正確にこの ID を持つバグがリクエスト全体で 1 回しか存在できないことを意味します。 DQL を使用してハイドレートされ、ID マップに既に存在するエンティティも検出します。

When flush is called the EntityManager loops over all the entities in the identity map and performs a comparison between the values originally retrieved from the database and those values the entity currently has. If at least one of these properties is different the entity is scheduled for an UPDATE against the database. Only the changed columns are updated, which offers a pretty good performance improvement compared to updating all the properties.

フラッシュが呼び出されると、EntityManager は ID マップ内のすべてのエンティティをループし、データベースから最初に取得した値とエンティティが現在持っている値との比較を実行します。これらのプロパティの少なくとも 1 つが異なる場合、エンティティはデータベースに対する UPDATE に対してスケジュールされます。変更された列のみが更新されるため、すべてのプロパティを更新する場合に比べてパフォーマンスが大幅に向上します。

Entity Repositories

For now we have not discussed how to separate the Doctrine query logic from your model. In Doctrine 1 there was the concept of Doctrine_Table instances for this separation. The similar concept in Doctrine2 is called Entity Repositories, integrating the repository pattern at the heart of Doctrine.

今のところ、Doctrine クエリ ロジックをモデルから分離する方法については説明していません。Doctrine 1 では、この分離のために Doctrine_Table インスタンスの概念がありました。 Doctrine2 の同様の概念はエンティティ リポジトリと呼ばれ、リポジトリ パターンを Doctrine の中心に統合します。

Every Entity uses a default repository by default and offers a bunch of convenience methods that you can use to query for instances of that Entity. Take for example our Product entity. If we wanted to Query by name, we can use:

すべてのエンティティはデフォルトでデフォルトのリポジトリを使用し、そのエンティティのインスタンスを照会するために使用できる一連の便利なメソッドを提供します。たとえば、Product エンティティを考えてみましょう。名前でクエリしたい場合は、次を使用できます。

<?php
$product = $entityManager->getRepository('Product')
                         ->findOneBy(array('name' => $productName));

The method findOneBy() takes an array of fields or association keys and the values to match against.

メソッド findOneBy() は、照合するフィールドまたは関連付けキーと値の配列を取ります。

If you want to find all entities matching a condition you can use findBy(), for example querying for all closed bugs:

条件に一致するすべてのエンティティを検索する場合は、findBy() を使用できます。たとえば、クローズされたすべてのバグを照会します。

<?php
$bugs = $entityManager->getRepository('Bug')
                      ->findBy(array('status' => 'CLOSED'));

foreach ($bugs as $bug) {
    // do stuff
}

Compared to DQL these query methods are falling short of functionality very fast. Doctrine offers you a convenient way to extend the functionalities of the default EntityRepository and put all the specialized DQL query logic on it. For this you have to create a subclass of Doctrine\ORM\EntityRepository, in our case a BugRepository and group all the previously discussed query functionality in it:

DQL と比較すると、これらのクエリ メソッドは非常に急速に機能が不足しています。Doctrine は、デフォルトの EntityRepository の機能を拡張し、すべての特殊な DQL クエリ ロジックを配置する便利な方法を提供します。このためには、Doctrine\ORM\EntityRepository のサブクラスを作成する必要があります。この場合は BugRepository であり、前述のすべてのクエリ機能をその中にグループ化します。

<?php
// src/BugRepository.php

use Doctrine\ORM\EntityRepository;

class BugRepository extends EntityRepository
{
    public function getRecentBugs($number = 30)
    {
        $dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ORDER BY b.created DESC";

        $query = $this->getEntityManager()->createQuery($dql);
        $query->setMaxResults($number);
        return $query->getResult();
    }

    public function getRecentBugsArray($number = 30)
    {
        $dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
               "JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
        $query = $this->getEntityManager()->createQuery($dql);
        $query->setMaxResults($number);
        return $query->getArrayResult();
    }

    public function getUsersBugs($userId, $number = 15)
    {
        $dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ".
               "WHERE b.status = 'OPEN' AND e.id = ?1 OR r.id = ?1 ORDER BY b.created DESC";

        return $this->getEntityManager()->createQuery($dql)
                             ->setParameter(1, $userId)
                             ->setMaxResults($number)
                             ->getResult();
    }

    public function getOpenBugsByProduct()
    {
        $dql = "SELECT p.id, p.name, count(b.id) AS openBugs FROM Bug b ".
               "JOIN b.products p WHERE b.status = 'OPEN' GROUP BY p.id";
        return $this->getEntityManager()->createQuery($dql)->getScalarResult();
    }
}

To be able to use this query logic through $this->getEntityManager()->getRepository('Bug') we have to adjust the metadata slightly.

$this->getEntityManager()->getRepository('Bug') を通じてこのクエリ ロジックを使用できるようにするには、メタデータを少し調整する必要があります。

Note

ノート

The YAML driver is deprecated and will be removed in version 3.0. It is strongly recommended to switch to one of the other mappings.

YAML ドライバーは推奨されておらず、バージョン 3.0 で削除されます。他のマッピングのいずれかに切り替えることを強くお勧めします。

Bug:
  type: entity
  repositoryClass: BugRepository

Now we can remove our query logic in all the places and instead use them through the EntityRepository. As an example here is the code of the first use case “List of Bugs”:

これで、すべての場所でクエリ ロジックを削除し、代わりに EntityRepository を通じてそれらを使用できるようになりました。例として、最初のユース ケース「バグのリスト」のコードを次に示します。

<?php
// list_bugs_repository.php
require_once "bootstrap.php";

$bugs = $entityManager->getRepository('Bug')->getRecentBugs();

foreach ($bugs as $bug) {
    echo $bug->getDescription()." - ".$bug->getCreated()->format('d.m.Y')."\n";
    echo "    Reported by: ".$bug->getReporter()->getName()."\n";
    echo "    Assigned to: ".$bug->getEngineer()->getName()."\n";
    foreach ($bug->getProducts() as $product) {
        echo "    Platform: ".$product->getName()."\n";
    }
    echo "\n";
}

Using EntityRepositories you can avoid coupling your model with specific query logic. You can also re-use query logic easily throughout your application.

EntityRepositories を使用すると、モデルを特定のクエリ ロジックと結合することを回避できます。アプリケーション全体でクエリ ロジックを簡単に再利用することもできます。

The method count() takes an array of fields or association keys and the values to match against. This provides you with a convenient and lightweight way to count a resultset when you don’t need to deal with it:

メソッド count() は、フィールドまたは関連付けキーの配列と、照合する値を受け取ります。これにより、結果セットを処理する必要がない場合に、結果セットをカウントするための便利で軽量な方法が提供されます。

<?php
$productCount = $entityManager->getRepository(Product::class)
                         ->count(['name' => $productName]);

Conclusion

This tutorial is over here, I hope you had fun. Additional content will be added to this tutorial incrementally, topics will include:

このチュートリアルはここまでです。楽しんでいただければ幸いです。このチュートリアルには追加コンテンツが段階的に追加されます。トピックには次のものが含まれます。

  • More on Association Mappings

    関連マッピングの詳細

  • Lifecycle Events triggered in the UnitOfWork

    UnitOfWork でトリガーされるライフサイクル イベント

  • Ordering of Collections

    コレクションの注文

Additional details on all the topics discussed here can be found in the respective manual chapters.

ここで説明するすべてのトピックの詳細については、それぞれのマニュアルの章を参照してください。

Table Of Contents

Previous topic

Welcome to Doctrine 2 ORM’s documentation!

Doctrine 2 ORM のドキュメントへようこそ!

Next topic

Getting Started: Database First

はじめに: データベース ファースト

This Page

Fork me on GitHub