Separating Concerns using Embeddables

Embeddables are classes which are not entities themselves, but are embedded in entities and can also be queried in DQL. You’ll mostly want to use them to reduce duplication or separating concerns. Value objects such as date range or address are the primary use case for this feature.

Embeddables は、エンティティ自体ではなく、エンティティに埋め込まれており、DQL でクエリすることもできるクラスです。ほとんどの場合、それらを使用して重複を減らしたり、懸念を分離したりする必要があります。日付範囲や住所などの値オブジェクトは、この機能の主な使用例です。

Note

ノート

Embeddables can only contain properties with basic @Column mapping.

Embeddables には、基本的な @Column マッピングを持つプロパティのみを含めることができます。

For the purposes of this tutorial, we will assume that you have a User class in your application and you would like to store an address in the User class. We will model the Address class as an embeddable instead of simply adding the respective columns to the User class.

このチュートリアルでは、アプリケーションに User クラスがあり、その User クラスにアドレスを格納したいと想定しています。それぞれの列を単純に User クラスに追加するのではなく、Address クラスを埋め込み可能なものとしてモデル化します。

In terms of your database schema, Doctrine will automatically inline all columns from the Address class into the table of the User class, just as if you had declared them directly there.

データベース スキーマに関しては、Doctrine は Address クラスのすべての列を User クラスのテーブルに自動的にインライン化し、あたかもそこで直接宣言したかのようにします。

Initializing embeddables

In case all fields in the embeddable are nullable, you might want to initialize the embeddable, to avoid getting a null value instead of the embedded object.

埋め込み可能オブジェクトのすべてのフィールドが null 可能である場合、埋め込みオブジェクトの代わりに null 値を取得しないように、埋め込み可能オブジェクトを初期化することができます。

public function __construct()
{
    $this->address = new Address();
}

Column Prefixing

By default, Doctrine names your columns by prefixing them, using the value object name.

デフォルトでは、Doctrine は valueobject 名を使用して列にプレフィックスを付けて名前を付けます。

Following the example above, your columns would be named as address_street, address_postalCode

上記の例に従うと、列は address_street,address_postalCode… という名前になります。

You can change this behaviour to meet your needs by changing the columnPrefix attribute in the @Embedded notation.

@Embedded 表記の columnPrefix 属性を変更することで、ニーズに合わせてこの動作を変更できます。

The following example shows you how to set your prefix to myPrefix_:

次の例は、プレフィックスを myPrefix_ に設定する方法を示しています。

To have Doctrine drop the prefix and use the value object’s property name directly, set columnPrefix=false (use-column-prefix="false" for XML):

Doctrine にプレフィックスを削除させ、値オブジェクトのプロパティ名を直接使用させるには、columnPrefix=false (XML の場合は use-column-prefix="false") を設定します。

DQL

You can also use mapped fields of embedded classes in DQL queries, just as if they were declared in the User class:

User クラスで宣言されているかのように、DQL クエリで埋め込みクラスのマップされたフィールドを使用することもできます。

SELECT u FROM User u WHERE u.address.city = :myCity

Table Of Contents

Previous topic

30. Pagination

30. ページネーション

Next topic

1. Architecture

1. 建築

This Page

Fork me on GitHub