0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Symfony + DoctrineでQuery Serviceを実装する

0
Posted at

はじめに

doctrine ORMは便利ですが、複数行を返す一覧GETエンドポイントを実装する場合は何も考えずに実装するとエンティティにマッピングされた別のエンティティの値を取得するために、各行でクエリが発生して N+1が発生します。
かといって、生クエリを書くとそれはそれで、保守がしにくいコードになってしまいます。
Doctrine ORMをそのまま利用せず、Doctrine DBALを利用してQueryServiceパターンを適用することで保守性とクエリパフォーマンスを維持した実装を目指します。

Query serviceとは

Command(書き込み・更新・削除)とQuery(読み取り)の責務を分離するために採用するパターンで、複雑なJOINや集計、パフォーマンス最適化されたクエリを書きやすいです。
一覧getエンドポイントでは様々なテーブルとジョインしたり、検索機能のために複雑なクエリを書く必要があるため、このパターンを採用します。

実装の観点で話すと、repositoryではたとえばOrderなどの集約単位のエンティティクラスを返却するのに対して、Query Serviceは画面・APIレスポンスに最適化したDTOを返却します。
これより、RepositoryInterfaceはDomain Layerに属するのたいして、QueryServiceInterfaceはApplication Layerに属します。

実装例

まずApplication layerにquery service interfaceを定義します。

// src/Product/Application/Query/ProductListQueryServiceInterface.php
interface ProductListQueryServiceInterface
{
    /**
     * @return ProductListItemDto[]
     */
    public function findForListing(int $clientId, int $categoryId): array;
}

そしてinfrastructure layerに具象クラスの実装を行います。

// src/Product/Infrastructure/Query/ProductListQueryService.php
final class ProductListQueryService implements ProductListQueryServiceInterface
{
    public function __construct(private Connection $connection) {}

    public function findForListing(int $clientId, int $categoryId): array
    {
        $sql = <<<SQL
            SELECT 
                p.id, 
                p.name, 
                p.price,
                c.name AS category_name,
                (SELECT COUNT(*) FROM order_item oi WHERE oi.product_id = p.id) AS sold_count
            FROM product p
            JOIN category c ON p.category_id = c.id
            WHERE p.client_id = :clientId 
              AND p.category_id = :categoryId
            ORDER BY p.id DESC
        SQL;

        $rows = $this->connection->fetchAllAssociative($sql, [
            'clientId' => $clientId,
            'categoryId' => $categoryId,
        ]);

        return array_map(
            static fn(array $row): ProductListItemDto => new ProductListItemDto(
                id: (int) $row['id'],
                name: $row['name'],
                price: (int) $row['price'],
                categoryName: $row['category_name'],
                soldCount: (int) $row['sold_count'],
            ),
            $rows,
        );
    }
}

そしてquery serviceの返却値であるdtoクラスを準備します。

// src/Product/Application/Query/Dto/ProductListItemDto.php
final readonly class ProductListItemDto
{
    public function __construct(
        public int $id,
        public string $name,
        public int $price,
        public string $categoryName,
        public int $soldCount,
    ) {}
}

このようにquery serviceで特定のユースケースに特化したクエリを書くことができます。

終わりに

一覧系のエンドポイントを実装する時に、これまではdoctrine entityクラスを返却し、ui層でentityクラスのgetterメソッドを駆使してレスポンス用のdto(Resourceクラス)を生成していました。これだと先述したとおり、エンティティのlazy loadingが原因でN+1が起きてパフォーマンスが著しく劣化します。
query serviceを採用することでこれを解決しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?